ETH Price: $2,138.72 (+4.92%)

Transaction Decoder

Block:
14366397 at Mar-11-2022 03:42:42 PM +UTC
Transaction Fee:
0.011538945092493851 ETH $24.68
Gas Used:
228,593 Gas / 50.478120907 Gwei

Emitted Events:

17 TetherToken.Transfer( from=EternalStorageProxy, to=[Sender] 0x20c848ec0d51c6296ebab81bf45e758536b42a74, value=50194905201 )
18 EternalStorageProxy.0x9afd47907e25028cdaca89d193518c302bbb128617d5a992c5abd45815526593( 0x9afd47907e25028cdaca89d193518c302bbb128617d5a992c5abd45815526593, 0x000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec7, 0x00000000000000000000000020c848ec0d51c6296ebab81bf45e758536b42a74, 0x0005000059b5445a336ce5818ed6b5f1ae2d5480930e10b300000000000005e8, 0000000000000000000000000000000000000000000000000000000bafd97871 )
19 EternalStorageProxy.0x27333edb8bdcd40a0ae944fb121b5e2d62ea782683946654a0f5e607a908d578( 0x27333edb8bdcd40a0ae944fb121b5e2d62ea782683946654a0f5e607a908d578, 0x000000000000000000000000c2220646e1e76d5ff3a441edd9e8eff0e4a8ef03, 0x000000000000000000000000f301d525da003e874df574bcdd309a6bf0535bb6, 0x0005000059b5445a336ce5818ed6b5f1ae2d5480930e10b300000000000005e8, 0000000000000000000000000000000000000000000000000000000000000001 )

Account State Difference:

  Address   Before After State Difference Code
0x20C848ec...536b42a74
0.227484134784207387 Eth
Nonce: 33
0.215945189691713536 Eth
Nonce: 34
0.011538945092493851
0x63C47c29...35014039f
0xdAC17F95...13D831ec7
(Ethermine)
721.751535729956412207 Eth721.752251253411280237 Eth0.00071552345486803
0xf301d525...BF0535bb6
(Voltage Finance: ERC-20 Tokens Bridge)

Execution Trace

EternalStorageProxy.3f7658fd( )
  • ForeignAMB.executeSignatures( _data=0x0005000059B5445A336CE5818ED6B5F1AE2D5480930E10B300000000000005E8C2220646E1E76D5FF3A441EDD9E8EFF0E4A8EF03F301D525DA003E874DF574BCDD309A6BF0535BB6001E84800101007A01125E4CFB000000000000000000000000DAC17F958D2EE523A2206206994597C13D831EC700000000000000000000000020C848EC0D51C6296EBAB81BF45E758536B42A740000000000000000000000000000000000000000000000000000000BAFD97871, _signatures=0x011BF08C15F621C68723BECBE0BD8D2B07C066E6A48C2D47247738E897940B38BB8220D92372DF3C4E521C89F791B74FC62DF77D5CC2ABAAE3359B463076120D1BCD )
    • EternalStorageProxy.CALL( )
      • BridgeValidators.DELEGATECALL( )
      • Null: 0x000...001.c494d2a0( )
      • EternalStorageProxy.facd743b( )
        • BridgeValidators.isValidator( _validator=0xb093ba323d42bd1854235c81979DC27B2dA43887 ) => ( True )
        • EternalStorageProxy.125e4cfb( )
          • ForeignMultiAMBErc20ToErc677.handleBridgedTokens( _token=0xdAC17F958D2ee523a2206206994597C13D831ec7, _recipient=0x20C848ec0d51C6296ebAB81bf45E758536b42a74, _value=50194905201 )
            • EternalStorageProxy.CALL( )
              • ForeignAMB.DELEGATECALL( )
              • EternalStorageProxy.CALL( )
                • ForeignAMB.DELEGATECALL( )
                • TetherToken.transfer( _to=0x20C848ec0d51C6296ebAB81bf45E758536b42a74, _value=50194905201 )
                  executeSignatures[BasicForeignAMB (ln:1383)]
                  File 1 of 7: EternalStorageProxy
                  // File: contracts/upgradeability/EternalStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title EternalStorage
                   * @dev This contract holds all the necessary state variables to carry out the storage of any contract.
                   */
                  contract EternalStorage {
                      mapping(bytes32 => uint256) internal uintStorage;
                      mapping(bytes32 => string) internal stringStorage;
                      mapping(bytes32 => address) internal addressStorage;
                      mapping(bytes32 => bytes) internal bytesStorage;
                      mapping(bytes32 => bool) internal boolStorage;
                      mapping(bytes32 => int256) internal intStorage;
                  
                  }
                  
                  // File: openzeppelin-solidity/contracts/AddressUtils.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * Utility library of inline functions on addresses
                   */
                  library AddressUtils {
                  
                    /**
                     * Returns whether the target address is a contract
                     * @dev This function will return false if invoked during the constructor of a contract,
                     * as the code is not actually created until after the constructor finishes.
                     * @param _addr address to check
                     * @return whether the target address is a contract
                     */
                    function isContract(address _addr) internal view returns (bool) {
                      uint256 size;
                      // XXX Currently there is no better way to check if there is a contract in an address
                      // than to check the size of the code at that address.
                      // See https://ethereum.stackexchange.com/a/14016/36603
                      // for more details about how this works.
                      // TODO Check this again before the Serenity release, because all addresses will be
                      // contracts then.
                      // solium-disable-next-line security/no-inline-assembly
                      assembly { size := extcodesize(_addr) }
                      return size > 0;
                    }
                  
                  }
                  
                  // File: contracts/upgradeability/Proxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title Proxy
                   * @dev Gives the possibility to delegate any call to a foreign implementation.
                   */
                  contract Proxy {
                      /**
                      * @dev Tells the address of the implementation where every call will be delegated.
                      * @return address of the implementation to which it will be delegated
                      */
                      /* solcov ignore next */
                      function implementation() public view returns (address);
                  
                      /**
                      * @dev Fallback function allowing to perform a delegatecall to the given implementation.
                      * This function will return whatever the implementation call returns
                      */
                      function() public payable {
                          // solhint-disable-previous-line no-complex-fallback
                          address _impl = implementation();
                          require(_impl != address(0));
                          assembly {
                              /*
                                  0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
                                  loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
                                  memory. It's needed because we're going to write the return data of delegatecall to the
                                  free memory slot.
                              */
                              let ptr := mload(0x40)
                              /*
                                  `calldatacopy` is copy calldatasize bytes from calldata
                                  First argument is the destination to which data is copied(ptr)
                                  Second argument specifies the start position of the copied data.
                                      Since calldata is sort of its own unique location in memory,
                                      0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
                                      That's always going to be the zeroth byte of the function selector.
                                  Third argument, calldatasize, specifies how much data will be copied.
                                      calldata is naturally calldatasize bytes long (same thing as msg.data.length)
                              */
                              calldatacopy(ptr, 0, calldatasize)
                              /*
                                  delegatecall params explained:
                                  gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
                                      us the amount of gas still available to execution
                  
                                  _impl: address of the contract to delegate to
                  
                                  ptr: to pass copied data
                  
                                  calldatasize: loads the size of `bytes memory data`, same as msg.data.length
                  
                                  0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
                                          these are set to 0, 0 so the output data will not be written to memory. The output
                                          data will be read using `returndatasize` and `returdatacopy` instead.
                  
                                  result: This will be 0 if the call fails and 1 if it succeeds
                              */
                              let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
                              /*
                  
                              */
                              /*
                                  ptr current points to the value stored at 0x40,
                                  because we assigned it like ptr := mload(0x40).
                                  Because we use 0x40 as a free memory pointer,
                                  we want to make sure that the next time we want to allocate memory,
                                  we aren't overwriting anything important.
                                  So, by adding ptr and returndatasize,
                                  we get a memory location beyond the end of the data we will be copying to ptr.
                                  We place this in at 0x40, and any reads from 0x40 will now read from free memory
                              */
                              mstore(0x40, add(ptr, returndatasize))
                              /*
                                  `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
                                      slot it will copy to, 0 means copy from the beginning of the return data, and size is
                                      the amount of data to copy.
                                  `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
                              */
                              returndatacopy(ptr, 0, returndatasize)
                  
                              /*
                                  if `result` is 0, revert.
                                  if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
                                  copied to `ptr` from the delegatecall return data
                              */
                              switch result
                                  case 0 {
                                      revert(ptr, returndatasize)
                                  }
                                  default {
                                      return(ptr, returndatasize)
                                  }
                          }
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title UpgradeabilityStorage
                   * @dev This contract holds all the necessary state variables to support the upgrade functionality
                   */
                  contract UpgradeabilityStorage {
                      // Version name of the current implementation
                      uint256 internal _version;
                  
                      // Address of the current implementation
                      address internal _implementation;
                  
                      /**
                      * @dev Tells the version name of the current implementation
                      * @return uint256 representing the name of the current version
                      */
                      function version() external view returns (uint256) {
                          return _version;
                      }
                  
                      /**
                      * @dev Tells the address of the current implementation
                      * @return address of the current implementation
                      */
                      function implementation() public view returns (address) {
                          return _implementation;
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  /**
                   * @title UpgradeabilityProxy
                   * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
                   */
                  contract UpgradeabilityProxy is Proxy, UpgradeabilityStorage {
                      /**
                      * @dev This event will be emitted every time the implementation gets upgraded
                      * @param version representing the version name of the upgraded implementation
                      * @param implementation representing the address of the upgraded implementation
                      */
                      event Upgraded(uint256 version, address indexed implementation);
                  
                      /**
                      * @dev Upgrades the implementation address
                      * @param version representing the version name of the new implementation to be set
                      * @param implementation representing the address of the new implementation to be set
                      */
                      function _upgradeTo(uint256 version, address implementation) internal {
                          require(_implementation != implementation);
                  
                          // This additional check verifies that provided implementation is at least a contract
                          require(AddressUtils.isContract(implementation));
                  
                          // This additional check guarantees that new version will be at least greater than the privios one,
                          // so it is impossible to reuse old versions, or use the last version twice
                          require(version > _version);
                  
                          _version = version;
                          _implementation = implementation;
                          emit Upgraded(version, implementation);
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityOwnerStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title UpgradeabilityOwnerStorage
                   * @dev This contract keeps track of the upgradeability owner
                   */
                  contract UpgradeabilityOwnerStorage {
                      // Owner of the contract
                      address internal _upgradeabilityOwner;
                  
                      /**
                      * @dev Tells the address of the owner
                      * @return the address of the owner
                      */
                      function upgradeabilityOwner() public view returns (address) {
                          return _upgradeabilityOwner;
                      }
                  
                      /**
                      * @dev Sets the address of the owner
                      */
                      function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
                          _upgradeabilityOwner = newUpgradeabilityOwner;
                      }
                  }
                  
                  // File: contracts/upgradeability/OwnedUpgradeabilityProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title OwnedUpgradeabilityProxy
                   * @dev This contract combines an upgradeability proxy with basic authorization control functionalities
                   */
                  contract OwnedUpgradeabilityProxy is UpgradeabilityOwnerStorage, UpgradeabilityProxy {
                      /**
                      * @dev Event to show ownership has been transferred
                      * @param previousOwner representing the address of the previous owner
                      * @param newOwner representing the address of the new owner
                      */
                      event ProxyOwnershipTransferred(address previousOwner, address newOwner);
                  
                      /**
                      * @dev the constructor sets the original owner of the contract to the sender account.
                      */
                      constructor() public {
                          setUpgradeabilityOwner(msg.sender);
                      }
                  
                      /**
                      * @dev Throws if called by any account other than the owner.
                      */
                      modifier onlyUpgradeabilityOwner() {
                          require(msg.sender == upgradeabilityOwner());
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner The address to transfer ownership to.
                      */
                      function transferProxyOwnership(address newOwner) external onlyUpgradeabilityOwner {
                          require(newOwner != address(0));
                          emit ProxyOwnershipTransferred(upgradeabilityOwner(), newOwner);
                          setUpgradeabilityOwner(newOwner);
                      }
                  
                      /**
                      * @dev Allows the upgradeability owner to upgrade the current version of the proxy.
                      * @param version representing the version name of the new implementation to be set.
                      * @param implementation representing the address of the new implementation to be set.
                      */
                      function upgradeTo(uint256 version, address implementation) public onlyUpgradeabilityOwner {
                          _upgradeTo(version, implementation);
                      }
                  
                      /**
                      * @dev Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation
                      * to initialize whatever is needed through a low level call.
                      * @param version representing the version name of the new implementation to be set.
                      * @param implementation representing the address of the new implementation to be set.
                      * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
                      * signature of the implementation to be called with the needed payload
                      */
                      function upgradeToAndCall(uint256 version, address implementation, bytes data)
                          external
                          payable
                          onlyUpgradeabilityOwner
                      {
                          upgradeTo(version, implementation);
                          // solhint-disable-next-line avoid-call-value
                          require(address(this).call.value(msg.value)(data));
                      }
                  }
                  
                  // File: contracts/upgradeability/EternalStorageProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title EternalStorageProxy
                   * @dev This proxy holds the storage of the token contract and delegates every call to the current implementation set.
                   * Besides, it allows to upgrade the token's behaviour towards further implementations, and provides basic
                   * authorization control functionalities
                   */
                  // solhint-disable-next-line no-empty-blocks
                  contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {}
                  

                  File 2 of 7: EternalStorageProxy
                  // File: contracts/upgradeability/EternalStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title EternalStorage
                   * @dev This contract holds all the necessary state variables to carry out the storage of any contract.
                   */
                  contract EternalStorage {
                      mapping(bytes32 => uint256) internal uintStorage;
                      mapping(bytes32 => string) internal stringStorage;
                      mapping(bytes32 => address) internal addressStorage;
                      mapping(bytes32 => bytes) internal bytesStorage;
                      mapping(bytes32 => bool) internal boolStorage;
                      mapping(bytes32 => int256) internal intStorage;
                  
                  }
                  
                  // File: openzeppelin-solidity/contracts/AddressUtils.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * Utility library of inline functions on addresses
                   */
                  library AddressUtils {
                  
                    /**
                     * Returns whether the target address is a contract
                     * @dev This function will return false if invoked during the constructor of a contract,
                     * as the code is not actually created until after the constructor finishes.
                     * @param _addr address to check
                     * @return whether the target address is a contract
                     */
                    function isContract(address _addr) internal view returns (bool) {
                      uint256 size;
                      // XXX Currently there is no better way to check if there is a contract in an address
                      // than to check the size of the code at that address.
                      // See https://ethereum.stackexchange.com/a/14016/36603
                      // for more details about how this works.
                      // TODO Check this again before the Serenity release, because all addresses will be
                      // contracts then.
                      // solium-disable-next-line security/no-inline-assembly
                      assembly { size := extcodesize(_addr) }
                      return size > 0;
                    }
                  
                  }
                  
                  // File: contracts/upgradeability/Proxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title Proxy
                   * @dev Gives the possibility to delegate any call to a foreign implementation.
                   */
                  contract Proxy {
                      /**
                      * @dev Tells the address of the implementation where every call will be delegated.
                      * @return address of the implementation to which it will be delegated
                      */
                      /* solcov ignore next */
                      function implementation() public view returns (address);
                  
                      /**
                      * @dev Fallback function allowing to perform a delegatecall to the given implementation.
                      * This function will return whatever the implementation call returns
                      */
                      function() public payable {
                          // solhint-disable-previous-line no-complex-fallback
                          address _impl = implementation();
                          require(_impl != address(0));
                          assembly {
                              /*
                                  0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
                                  loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
                                  memory. It's needed because we're going to write the return data of delegatecall to the
                                  free memory slot.
                              */
                              let ptr := mload(0x40)
                              /*
                                  `calldatacopy` is copy calldatasize bytes from calldata
                                  First argument is the destination to which data is copied(ptr)
                                  Second argument specifies the start position of the copied data.
                                      Since calldata is sort of its own unique location in memory,
                                      0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
                                      That's always going to be the zeroth byte of the function selector.
                                  Third argument, calldatasize, specifies how much data will be copied.
                                      calldata is naturally calldatasize bytes long (same thing as msg.data.length)
                              */
                              calldatacopy(ptr, 0, calldatasize)
                              /*
                                  delegatecall params explained:
                                  gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
                                      us the amount of gas still available to execution
                  
                                  _impl: address of the contract to delegate to
                  
                                  ptr: to pass copied data
                  
                                  calldatasize: loads the size of `bytes memory data`, same as msg.data.length
                  
                                  0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
                                          these are set to 0, 0 so the output data will not be written to memory. The output
                                          data will be read using `returndatasize` and `returdatacopy` instead.
                  
                                  result: This will be 0 if the call fails and 1 if it succeeds
                              */
                              let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
                              /*
                  
                              */
                              /*
                                  ptr current points to the value stored at 0x40,
                                  because we assigned it like ptr := mload(0x40).
                                  Because we use 0x40 as a free memory pointer,
                                  we want to make sure that the next time we want to allocate memory,
                                  we aren't overwriting anything important.
                                  So, by adding ptr and returndatasize,
                                  we get a memory location beyond the end of the data we will be copying to ptr.
                                  We place this in at 0x40, and any reads from 0x40 will now read from free memory
                              */
                              mstore(0x40, add(ptr, returndatasize))
                              /*
                                  `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
                                      slot it will copy to, 0 means copy from the beginning of the return data, and size is
                                      the amount of data to copy.
                                  `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
                              */
                              returndatacopy(ptr, 0, returndatasize)
                  
                              /*
                                  if `result` is 0, revert.
                                  if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
                                  copied to `ptr` from the delegatecall return data
                              */
                              switch result
                                  case 0 {
                                      revert(ptr, returndatasize)
                                  }
                                  default {
                                      return(ptr, returndatasize)
                                  }
                          }
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title UpgradeabilityStorage
                   * @dev This contract holds all the necessary state variables to support the upgrade functionality
                   */
                  contract UpgradeabilityStorage {
                      // Version name of the current implementation
                      uint256 internal _version;
                  
                      // Address of the current implementation
                      address internal _implementation;
                  
                      /**
                      * @dev Tells the version name of the current implementation
                      * @return uint256 representing the name of the current version
                      */
                      function version() external view returns (uint256) {
                          return _version;
                      }
                  
                      /**
                      * @dev Tells the address of the current implementation
                      * @return address of the current implementation
                      */
                      function implementation() public view returns (address) {
                          return _implementation;
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  /**
                   * @title UpgradeabilityProxy
                   * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
                   */
                  contract UpgradeabilityProxy is Proxy, UpgradeabilityStorage {
                      /**
                      * @dev This event will be emitted every time the implementation gets upgraded
                      * @param version representing the version name of the upgraded implementation
                      * @param implementation representing the address of the upgraded implementation
                      */
                      event Upgraded(uint256 version, address indexed implementation);
                  
                      /**
                      * @dev Upgrades the implementation address
                      * @param version representing the version name of the new implementation to be set
                      * @param implementation representing the address of the new implementation to be set
                      */
                      function _upgradeTo(uint256 version, address implementation) internal {
                          require(_implementation != implementation);
                  
                          // This additional check verifies that provided implementation is at least a contract
                          require(AddressUtils.isContract(implementation));
                  
                          // This additional check guarantees that new version will be at least greater than the privios one,
                          // so it is impossible to reuse old versions, or use the last version twice
                          require(version > _version);
                  
                          _version = version;
                          _implementation = implementation;
                          emit Upgraded(version, implementation);
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityOwnerStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title UpgradeabilityOwnerStorage
                   * @dev This contract keeps track of the upgradeability owner
                   */
                  contract UpgradeabilityOwnerStorage {
                      // Owner of the contract
                      address internal _upgradeabilityOwner;
                  
                      /**
                      * @dev Tells the address of the owner
                      * @return the address of the owner
                      */
                      function upgradeabilityOwner() public view returns (address) {
                          return _upgradeabilityOwner;
                      }
                  
                      /**
                      * @dev Sets the address of the owner
                      */
                      function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
                          _upgradeabilityOwner = newUpgradeabilityOwner;
                      }
                  }
                  
                  // File: contracts/upgradeability/OwnedUpgradeabilityProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title OwnedUpgradeabilityProxy
                   * @dev This contract combines an upgradeability proxy with basic authorization control functionalities
                   */
                  contract OwnedUpgradeabilityProxy is UpgradeabilityOwnerStorage, UpgradeabilityProxy {
                      /**
                      * @dev Event to show ownership has been transferred
                      * @param previousOwner representing the address of the previous owner
                      * @param newOwner representing the address of the new owner
                      */
                      event ProxyOwnershipTransferred(address previousOwner, address newOwner);
                  
                      /**
                      * @dev the constructor sets the original owner of the contract to the sender account.
                      */
                      constructor() public {
                          setUpgradeabilityOwner(msg.sender);
                      }
                  
                      /**
                      * @dev Throws if called by any account other than the owner.
                      */
                      modifier onlyUpgradeabilityOwner() {
                          require(msg.sender == upgradeabilityOwner());
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner The address to transfer ownership to.
                      */
                      function transferProxyOwnership(address newOwner) external onlyUpgradeabilityOwner {
                          require(newOwner != address(0));
                          emit ProxyOwnershipTransferred(upgradeabilityOwner(), newOwner);
                          setUpgradeabilityOwner(newOwner);
                      }
                  
                      /**
                      * @dev Allows the upgradeability owner to upgrade the current version of the proxy.
                      * @param version representing the version name of the new implementation to be set.
                      * @param implementation representing the address of the new implementation to be set.
                      */
                      function upgradeTo(uint256 version, address implementation) public onlyUpgradeabilityOwner {
                          _upgradeTo(version, implementation);
                      }
                  
                      /**
                      * @dev Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation
                      * to initialize whatever is needed through a low level call.
                      * @param version representing the version name of the new implementation to be set.
                      * @param implementation representing the address of the new implementation to be set.
                      * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
                      * signature of the implementation to be called with the needed payload
                      */
                      function upgradeToAndCall(uint256 version, address implementation, bytes data)
                          external
                          payable
                          onlyUpgradeabilityOwner
                      {
                          upgradeTo(version, implementation);
                          // solhint-disable-next-line avoid-call-value
                          require(address(this).call.value(msg.value)(data));
                      }
                  }
                  
                  // File: contracts/upgradeability/EternalStorageProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title EternalStorageProxy
                   * @dev This proxy holds the storage of the token contract and delegates every call to the current implementation set.
                   * Besides, it allows to upgrade the token's behaviour towards further implementations, and provides basic
                   * authorization control functionalities
                   */
                  // solhint-disable-next-line no-empty-blocks
                  contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {}
                  

                  File 3 of 7: TetherToken
                  pragma solidity ^0.4.17;
                  
                  /**
                   * @title SafeMath
                   * @dev Math operations with safety checks that throw on error
                   */
                  library SafeMath {
                      function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                          if (a == 0) {
                              return 0;
                          }
                          uint256 c = a * b;
                          assert(c / a == b);
                          return c;
                      }
                  
                      function div(uint256 a, uint256 b) internal pure returns (uint256) {
                          // assert(b > 0); // Solidity automatically throws when dividing by 0
                          uint256 c = a / b;
                          // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                          return c;
                      }
                  
                      function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                          assert(b <= a);
                          return a - b;
                      }
                  
                      function add(uint256 a, uint256 b) internal pure returns (uint256) {
                          uint256 c = a + b;
                          assert(c >= a);
                          return c;
                      }
                  }
                  
                  /**
                   * @title Ownable
                   * @dev The Ownable contract has an owner address, and provides basic authorization control
                   * functions, this simplifies the implementation of "user permissions".
                   */
                  contract Ownable {
                      address public owner;
                  
                      /**
                        * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                        * account.
                        */
                      function Ownable() public {
                          owner = msg.sender;
                      }
                  
                      /**
                        * @dev Throws if called by any account other than the owner.
                        */
                      modifier onlyOwner() {
                          require(msg.sender == owner);
                          _;
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner The address to transfer ownership to.
                      */
                      function transferOwnership(address newOwner) public onlyOwner {
                          if (newOwner != address(0)) {
                              owner = newOwner;
                          }
                      }
                  
                  }
                  
                  /**
                   * @title ERC20Basic
                   * @dev Simpler version of ERC20 interface
                   * @dev see https://github.com/ethereum/EIPs/issues/20
                   */
                  contract ERC20Basic {
                      uint public _totalSupply;
                      function totalSupply() public constant returns (uint);
                      function balanceOf(address who) public constant returns (uint);
                      function transfer(address to, uint value) public;
                      event Transfer(address indexed from, address indexed to, uint value);
                  }
                  
                  /**
                   * @title ERC20 interface
                   * @dev see https://github.com/ethereum/EIPs/issues/20
                   */
                  contract ERC20 is ERC20Basic {
                      function allowance(address owner, address spender) public constant returns (uint);
                      function transferFrom(address from, address to, uint value) public;
                      function approve(address spender, uint value) public;
                      event Approval(address indexed owner, address indexed spender, uint value);
                  }
                  
                  /**
                   * @title Basic token
                   * @dev Basic version of StandardToken, with no allowances.
                   */
                  contract BasicToken is Ownable, ERC20Basic {
                      using SafeMath for uint;
                  
                      mapping(address => uint) public balances;
                  
                      // additional variables for use if transaction fees ever became necessary
                      uint public basisPointsRate = 0;
                      uint public maximumFee = 0;
                  
                      /**
                      * @dev Fix for the ERC20 short address attack.
                      */
                      modifier onlyPayloadSize(uint size) {
                          require(!(msg.data.length < size + 4));
                          _;
                      }
                  
                      /**
                      * @dev transfer token for a specified address
                      * @param _to The address to transfer to.
                      * @param _value The amount to be transferred.
                      */
                      function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
                          uint fee = (_value.mul(basisPointsRate)).div(10000);
                          if (fee > maximumFee) {
                              fee = maximumFee;
                          }
                          uint sendAmount = _value.sub(fee);
                          balances[msg.sender] = balances[msg.sender].sub(_value);
                          balances[_to] = balances[_to].add(sendAmount);
                          if (fee > 0) {
                              balances[owner] = balances[owner].add(fee);
                              Transfer(msg.sender, owner, fee);
                          }
                          Transfer(msg.sender, _to, sendAmount);
                      }
                  
                      /**
                      * @dev Gets the balance of the specified address.
                      * @param _owner The address to query the the balance of.
                      * @return An uint representing the amount owned by the passed address.
                      */
                      function balanceOf(address _owner) public constant returns (uint balance) {
                          return balances[_owner];
                      }
                  
                  }
                  
                  /**
                   * @title Standard ERC20 token
                   *
                   * @dev Implementation of the basic standard token.
                   * @dev https://github.com/ethereum/EIPs/issues/20
                   * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
                   */
                  contract StandardToken is BasicToken, ERC20 {
                  
                      mapping (address => mapping (address => uint)) public allowed;
                  
                      uint public constant MAX_UINT = 2**256 - 1;
                  
                      /**
                      * @dev Transfer tokens from one address to another
                      * @param _from address The address which you want to send tokens from
                      * @param _to address The address which you want to transfer to
                      * @param _value uint the amount of tokens to be transferred
                      */
                      function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
                          var _allowance = allowed[_from][msg.sender];
                  
                          // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
                          // if (_value > _allowance) throw;
                  
                          uint fee = (_value.mul(basisPointsRate)).div(10000);
                          if (fee > maximumFee) {
                              fee = maximumFee;
                          }
                          if (_allowance < MAX_UINT) {
                              allowed[_from][msg.sender] = _allowance.sub(_value);
                          }
                          uint sendAmount = _value.sub(fee);
                          balances[_from] = balances[_from].sub(_value);
                          balances[_to] = balances[_to].add(sendAmount);
                          if (fee > 0) {
                              balances[owner] = balances[owner].add(fee);
                              Transfer(_from, owner, fee);
                          }
                          Transfer(_from, _to, sendAmount);
                      }
                  
                      /**
                      * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
                      * @param _spender The address which will spend the funds.
                      * @param _value The amount of tokens to be spent.
                      */
                      function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
                  
                          // To change the approve amount you first have to reduce the addresses`
                          //  allowance to zero by calling `approve(_spender, 0)` if it is not
                          //  already 0 to mitigate the race condition described here:
                          //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                          require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
                  
                          allowed[msg.sender][_spender] = _value;
                          Approval(msg.sender, _spender, _value);
                      }
                  
                      /**
                      * @dev Function to check the amount of tokens than an owner allowed to a spender.
                      * @param _owner address The address which owns the funds.
                      * @param _spender address The address which will spend the funds.
                      * @return A uint specifying the amount of tokens still available for the spender.
                      */
                      function allowance(address _owner, address _spender) public constant returns (uint remaining) {
                          return allowed[_owner][_spender];
                      }
                  
                  }
                  
                  
                  /**
                   * @title Pausable
                   * @dev Base contract which allows children to implement an emergency stop mechanism.
                   */
                  contract Pausable is Ownable {
                    event Pause();
                    event Unpause();
                  
                    bool public paused = false;
                  
                  
                    /**
                     * @dev Modifier to make a function callable only when the contract is not paused.
                     */
                    modifier whenNotPaused() {
                      require(!paused);
                      _;
                    }
                  
                    /**
                     * @dev Modifier to make a function callable only when the contract is paused.
                     */
                    modifier whenPaused() {
                      require(paused);
                      _;
                    }
                  
                    /**
                     * @dev called by the owner to pause, triggers stopped state
                     */
                    function pause() onlyOwner whenNotPaused public {
                      paused = true;
                      Pause();
                    }
                  
                    /**
                     * @dev called by the owner to unpause, returns to normal state
                     */
                    function unpause() onlyOwner whenPaused public {
                      paused = false;
                      Unpause();
                    }
                  }
                  
                  contract BlackList is Ownable, BasicToken {
                  
                      /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
                      function getBlackListStatus(address _maker) external constant returns (bool) {
                          return isBlackListed[_maker];
                      }
                  
                      function getOwner() external constant returns (address) {
                          return owner;
                      }
                  
                      mapping (address => bool) public isBlackListed;
                      
                      function addBlackList (address _evilUser) public onlyOwner {
                          isBlackListed[_evilUser] = true;
                          AddedBlackList(_evilUser);
                      }
                  
                      function removeBlackList (address _clearedUser) public onlyOwner {
                          isBlackListed[_clearedUser] = false;
                          RemovedBlackList(_clearedUser);
                      }
                  
                      function destroyBlackFunds (address _blackListedUser) public onlyOwner {
                          require(isBlackListed[_blackListedUser]);
                          uint dirtyFunds = balanceOf(_blackListedUser);
                          balances[_blackListedUser] = 0;
                          _totalSupply -= dirtyFunds;
                          DestroyedBlackFunds(_blackListedUser, dirtyFunds);
                      }
                  
                      event DestroyedBlackFunds(address _blackListedUser, uint _balance);
                  
                      event AddedBlackList(address _user);
                  
                      event RemovedBlackList(address _user);
                  
                  }
                  
                  contract UpgradedStandardToken is StandardToken{
                      // those methods are called by the legacy contract
                      // and they must ensure msg.sender to be the contract address
                      function transferByLegacy(address from, address to, uint value) public;
                      function transferFromByLegacy(address sender, address from, address spender, uint value) public;
                      function approveByLegacy(address from, address spender, uint value) public;
                  }
                  
                  contract TetherToken is Pausable, StandardToken, BlackList {
                  
                      string public name;
                      string public symbol;
                      uint public decimals;
                      address public upgradedAddress;
                      bool public deprecated;
                  
                      //  The contract can be initialized with a number of tokens
                      //  All the tokens are deposited to the owner address
                      //
                      // @param _balance Initial supply of the contract
                      // @param _name Token Name
                      // @param _symbol Token symbol
                      // @param _decimals Token decimals
                      function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
                          _totalSupply = _initialSupply;
                          name = _name;
                          symbol = _symbol;
                          decimals = _decimals;
                          balances[owner] = _initialSupply;
                          deprecated = false;
                      }
                  
                      // Forward ERC20 methods to upgraded contract if this one is deprecated
                      function transfer(address _to, uint _value) public whenNotPaused {
                          require(!isBlackListed[msg.sender]);
                          if (deprecated) {
                              return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
                          } else {
                              return super.transfer(_to, _value);
                          }
                      }
                  
                      // Forward ERC20 methods to upgraded contract if this one is deprecated
                      function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
                          require(!isBlackListed[_from]);
                          if (deprecated) {
                              return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
                          } else {
                              return super.transferFrom(_from, _to, _value);
                          }
                      }
                  
                      // Forward ERC20 methods to upgraded contract if this one is deprecated
                      function balanceOf(address who) public constant returns (uint) {
                          if (deprecated) {
                              return UpgradedStandardToken(upgradedAddress).balanceOf(who);
                          } else {
                              return super.balanceOf(who);
                          }
                      }
                  
                      // Forward ERC20 methods to upgraded contract if this one is deprecated
                      function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
                          if (deprecated) {
                              return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
                          } else {
                              return super.approve(_spender, _value);
                          }
                      }
                  
                      // Forward ERC20 methods to upgraded contract if this one is deprecated
                      function allowance(address _owner, address _spender) public constant returns (uint remaining) {
                          if (deprecated) {
                              return StandardToken(upgradedAddress).allowance(_owner, _spender);
                          } else {
                              return super.allowance(_owner, _spender);
                          }
                      }
                  
                      // deprecate current contract in favour of a new one
                      function deprecate(address _upgradedAddress) public onlyOwner {
                          deprecated = true;
                          upgradedAddress = _upgradedAddress;
                          Deprecate(_upgradedAddress);
                      }
                  
                      // deprecate current contract if favour of a new one
                      function totalSupply() public constant returns (uint) {
                          if (deprecated) {
                              return StandardToken(upgradedAddress).totalSupply();
                          } else {
                              return _totalSupply;
                          }
                      }
                  
                      // Issue a new amount of tokens
                      // these tokens are deposited into the owner address
                      //
                      // @param _amount Number of tokens to be issued
                      function issue(uint amount) public onlyOwner {
                          require(_totalSupply + amount > _totalSupply);
                          require(balances[owner] + amount > balances[owner]);
                  
                          balances[owner] += amount;
                          _totalSupply += amount;
                          Issue(amount);
                      }
                  
                      // Redeem tokens.
                      // These tokens are withdrawn from the owner address
                      // if the balance must be enough to cover the redeem
                      // or the call will fail.
                      // @param _amount Number of tokens to be issued
                      function redeem(uint amount) public onlyOwner {
                          require(_totalSupply >= amount);
                          require(balances[owner] >= amount);
                  
                          _totalSupply -= amount;
                          balances[owner] -= amount;
                          Redeem(amount);
                      }
                  
                      function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
                          // Ensure transparency by hardcoding limit beyond which fees can never be added
                          require(newBasisPoints < 20);
                          require(newMaxFee < 50);
                  
                          basisPointsRate = newBasisPoints;
                          maximumFee = newMaxFee.mul(10**decimals);
                  
                          Params(basisPointsRate, maximumFee);
                      }
                  
                      // Called when new token are issued
                      event Issue(uint amount);
                  
                      // Called when tokens are redeemed
                      event Redeem(uint amount);
                  
                      // Called when contract is deprecated
                      event Deprecate(address newAddress);
                  
                      // Called if contract ever adds fees
                      event Params(uint feeBasisPoints, uint maxFee);
                  }

                  File 4 of 7: ForeignAMB
                  // File: contracts/interfaces/IBridgeValidators.sol
                  
                  pragma solidity 0.4.24;
                  
                  interface IBridgeValidators {
                      function isValidator(address _validator) external view returns (bool);
                      function requiredSignatures() external view returns (uint256);
                      function owner() external view returns (address);
                  }
                  
                  // File: contracts/libraries/Message.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  library Message {
                      // function uintToString(uint256 inputValue) internal pure returns (string) {
                      //     // figure out the length of the resulting string
                      //     uint256 length = 0;
                      //     uint256 currentValue = inputValue;
                      //     do {
                      //         length++;
                      //         currentValue /= 10;
                      //     } while (currentValue != 0);
                      //     // allocate enough memory
                      //     bytes memory result = new bytes(length);
                      //     // construct the string backwards
                      //     uint256 i = length - 1;
                      //     currentValue = inputValue;
                      //     do {
                      //         result[i--] = byte(48 + currentValue % 10);
                      //         currentValue /= 10;
                      //     } while (currentValue != 0);
                      //     return string(result);
                      // }
                  
                      function addressArrayContains(address[] array, address value) internal pure returns (bool) {
                          for (uint256 i = 0; i < array.length; i++) {
                              if (array[i] == value) {
                                  return true;
                              }
                          }
                          return false;
                      }
                      // layout of message :: bytes:
                      // offset  0: 32 bytes :: uint256 - message length
                      // offset 32: 20 bytes :: address - recipient address
                      // offset 52: 32 bytes :: uint256 - value
                      // offset 84: 32 bytes :: bytes32 - transaction hash
                      // offset 104: 20 bytes :: address - contract address to prevent double spending
                  
                      // mload always reads 32 bytes.
                      // so we can and have to start reading recipient at offset 20 instead of 32.
                      // if we were to read at 32 the address would contain part of value and be corrupted.
                      // when reading from offset 20 mload will read 12 bytes (most of them zeros) followed
                      // by the 20 recipient address bytes and correctly convert it into an address.
                      // this saves some storage/gas over the alternative solution
                      // which is padding address to 32 bytes and reading recipient at offset 32.
                      // for more details see discussion in:
                      // https://github.com/paritytech/parity-bridge/issues/61
                      function parseMessage(bytes message)
                          internal
                          pure
                          returns (address recipient, uint256 amount, bytes32 txHash, address contractAddress)
                      {
                          require(isMessageValid(message));
                          assembly {
                              recipient := mload(add(message, 20))
                              amount := mload(add(message, 52))
                              txHash := mload(add(message, 84))
                              contractAddress := mload(add(message, 104))
                          }
                      }
                  
                      function isMessageValid(bytes _msg) internal pure returns (bool) {
                          return _msg.length == requiredMessageLength();
                      }
                  
                      function requiredMessageLength() internal pure returns (uint256) {
                          return 104;
                      }
                  
                      function recoverAddressFromSignedMessage(bytes signature, bytes message, bool isAMBMessage)
                          internal
                          pure
                          returns (address)
                      {
                          require(signature.length == 65);
                          bytes32 r;
                          bytes32 s;
                          bytes1 v;
                  
                          assembly {
                              r := mload(add(signature, 0x20))
                              s := mload(add(signature, 0x40))
                              v := mload(add(signature, 0x60))
                          }
                          return ecrecover(hashMessage(message, isAMBMessage), uint8(v), r, s);
                      }
                  
                      function hashMessage(bytes message, bool isAMBMessage) internal pure returns (bytes32) {
                          bytes memory prefix = "\x19Ethereum Signed Message:\n";
                          if (isAMBMessage) {
                              return keccak256(abi.encodePacked(prefix, uintToString(message.length), message));
                          } else {
                              string memory msgLength = "104";
                              return keccak256(abi.encodePacked(prefix, msgLength, message));
                          }
                      }
                  
                      /**
                      * @dev Validates provided signatures, only first requiredSignatures() number
                      * of signatures are going to be validated, these signatures should be from different validators.
                      * @param _message bytes message used to generate signatures
                      * @param _signatures bytes blob with signatures to be validated.
                      * First byte X is a number of signatures in a blob,
                      * next X bytes are v components of signatures,
                      * next 32 * X bytes are r components of signatures,
                      * next 32 * X bytes are s components of signatures.
                      * @param _validatorContract contract, which conforms to the IBridgeValidators interface,
                      * where info about current validators and required signatures is stored.
                      * @param isAMBMessage true if _message is an AMB message with arbitrary length.
                      */
                      function hasEnoughValidSignatures(
                          bytes _message,
                          bytes _signatures,
                          IBridgeValidators _validatorContract,
                          bool isAMBMessage
                      ) internal view {
                          require(isAMBMessage || isMessageValid(_message));
                          uint256 requiredSignatures = _validatorContract.requiredSignatures();
                          uint256 amount;
                          assembly {
                              amount := and(mload(add(_signatures, 1)), 0xff)
                          }
                          require(amount >= requiredSignatures);
                          bytes32 hash = hashMessage(_message, isAMBMessage);
                          address[] memory encounteredAddresses = new address[](requiredSignatures);
                  
                          for (uint256 i = 0; i < requiredSignatures; i++) {
                              uint8 v;
                              bytes32 r;
                              bytes32 s;
                              uint256 posr = 33 + amount + 32 * i;
                              uint256 poss = posr + 32 * amount;
                              assembly {
                                  v := mload(add(_signatures, add(2, i)))
                                  r := mload(add(_signatures, posr))
                                  s := mload(add(_signatures, poss))
                              }
                  
                              address recoveredAddress = ecrecover(hash, v, r, s);
                              require(_validatorContract.isValidator(recoveredAddress));
                              require(!addressArrayContains(encounteredAddresses, recoveredAddress));
                              encounteredAddresses[i] = recoveredAddress;
                          }
                      }
                  
                      function uintToString(uint256 i) internal pure returns (string) {
                          if (i == 0) return "0";
                          uint256 j = i;
                          uint256 length;
                          while (j != 0) {
                              length++;
                              j /= 10;
                          }
                          bytes memory bstr = new bytes(length);
                          uint256 k = length - 1;
                          while (i != 0) {
                              bstr[k--] = bytes1(48 + (i % 10));
                              i /= 10;
                          }
                          return string(bstr);
                      }
                  }
                  
                  // File: contracts/libraries/ArbitraryMessage.sol
                  
                  pragma solidity 0.4.24;
                  
                  library ArbitraryMessage {
                      /**
                      * @dev Unpacks data fields from AMB message
                      * layout of message :: bytes:
                      * offset  0              : 32 bytes :: uint256 - message length
                      * offset 32              : 32 bytes :: bytes32 - messageId
                      * offset 64              : 20 bytes :: address - sender address
                      * offset 84              : 20 bytes :: address - executor contract
                      * offset 104             : 4 bytes  :: uint32  - gasLimit
                      * offset 108             : 1 bytes  :: uint8   - source chain id length (X)
                      * offset 109             : 1 bytes  :: uint8   - destination chain id length (Y)
                      * offset 110             : 1 bytes  :: bytes1  - dataType
                      * (optional) 111         : 32 bytes :: uint256 - gasPrice
                      * (optional) 111         : 1 bytes  :: bytes1  - gasPriceSpeed
                      * offset 111/143/112     : X bytes  :: bytes   - source chain id
                      * offset 111/143/112 + X : Y bytes  :: bytes   - destination chain id
                  
                      * NOTE: when message structure is changed, make sure that MESSAGE_PACKING_VERSION from VersionableAMB is updated as well
                      * NOTE: assembly code uses calldatacopy, make sure that message is passed as the first argument in the calldata
                      * @param _data encoded message
                      */
                      function unpackData(bytes _data)
                          internal
                          pure
                          returns (
                              bytes32 messageId,
                              address sender,
                              address executor,
                              uint32 gasLimit,
                              bytes1 dataType,
                              uint256[2] chainIds,
                              uint256 gasPrice,
                              bytes memory data
                          )
                      {
                          // 32 (message id) + 20 (sender) + 20 (executor) + 4 (gasLimit) + 1 (source chain id length) + 1 (destination chain id length) + 1 (dataType)
                          uint256 srcdataptr = 32 + 20 + 20 + 4 + 1 + 1 + 1;
                          uint256 datasize;
                  
                          assembly {
                              messageId := mload(add(_data, 32)) // 32 bytes
                              sender := and(mload(add(_data, 52)), 0xffffffffffffffffffffffffffffffffffffffff) // 20 bytes
                  
                              // executor (20 bytes) + gasLimit (4 bytes) + srcChainIdLength (1 byte) + dstChainIdLength (1 bytes) + dataType (1 byte) + remainder (5 bytes)
                              let blob := mload(add(_data, 84))
                  
                              // after bit shift left 12 bytes are zeros automatically
                              executor := shr(96, blob)
                              gasLimit := and(shr(64, blob), 0xffffffff)
                  
                              // load source chain id length
                              let chainIdLength := byte(24, blob)
                  
                              dataType := and(shl(208, blob), 0xFF00000000000000000000000000000000000000000000000000000000000000)
                              switch dataType
                                  case 0x0000000000000000000000000000000000000000000000000000000000000000 {
                                      gasPrice := 0
                                  }
                                  case 0x0100000000000000000000000000000000000000000000000000000000000000 {
                                      gasPrice := mload(add(_data, 111)) // 32
                                      srcdataptr := add(srcdataptr, 32)
                                  }
                                  case 0x0200000000000000000000000000000000000000000000000000000000000000 {
                                      gasPrice := 0
                                      srcdataptr := add(srcdataptr, 1)
                                  }
                  
                              // at this moment srcdataptr points to sourceChainId
                  
                              // mask for sourceChainId
                              // e.g. length X -> (1 << (X * 8)) - 1
                              let mask := sub(shl(shl(3, chainIdLength), 1), 1)
                  
                              // increase payload offset by length of source chain id
                              srcdataptr := add(srcdataptr, chainIdLength)
                  
                              // write sourceChainId
                              mstore(chainIds, and(mload(add(_data, srcdataptr)), mask))
                  
                              // at this moment srcdataptr points to destinationChainId
                  
                              // load destination chain id length
                              chainIdLength := byte(25, blob)
                  
                              // mask for destinationChainId
                              // e.g. length X -> (1 << (X * 8)) - 1
                              mask := sub(shl(shl(3, chainIdLength), 1), 1)
                  
                              // increase payload offset by length of destination chain id
                              srcdataptr := add(srcdataptr, chainIdLength)
                  
                              // write destinationChainId
                              mstore(add(chainIds, 32), and(mload(add(_data, srcdataptr)), mask))
                  
                              // at this moment srcdataptr points to payload
                  
                              // datasize = message length - payload offset
                              datasize := sub(mload(_data), srcdataptr)
                          }
                  
                          data = new bytes(datasize);
                          assembly {
                              // 36 = 4 (selector) + 32 (bytes length header)
                              srcdataptr := add(srcdataptr, 36)
                  
                              // calldataload(4) - offset of first bytes argument in the calldata
                              calldatacopy(add(data, 32), add(calldataload(4), srcdataptr), datasize)
                          }
                      }
                  }
                  
                  // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  interface IUpgradeabilityOwnerStorage {
                      function upgradeabilityOwner() external view returns (address);
                  }
                  
                  // File: contracts/upgradeable_contracts/Upgradeable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract Upgradeable {
                      // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
                      modifier onlyIfUpgradeabilityOwner() {
                          require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner());
                          /* solcov ignore next */
                          _;
                      }
                  }
                  
                  // File: contracts/upgradeability/EternalStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title EternalStorage
                   * @dev This contract holds all the necessary state variables to carry out the storage of any contract.
                   */
                  contract EternalStorage {
                      mapping(bytes32 => uint256) internal uintStorage;
                      mapping(bytes32 => string) internal stringStorage;
                      mapping(bytes32 => address) internal addressStorage;
                      mapping(bytes32 => bytes) internal bytesStorage;
                      mapping(bytes32 => bool) internal boolStorage;
                      mapping(bytes32 => int256) internal intStorage;
                  
                  }
                  
                  // File: contracts/upgradeable_contracts/Initializable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract Initializable is EternalStorage {
                      bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
                  
                      function setInitialize() internal {
                          boolStorage[INITIALIZED] = true;
                      }
                  
                      function isInitialized() public view returns (bool) {
                          return boolStorage[INITIALIZED];
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/InitializableBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract InitializableBridge is Initializable {
                      bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock"))
                  
                      function deployedAtBlock() external view returns (uint256) {
                          return uintStorage[DEPLOYED_AT_BLOCK];
                      }
                  }
                  
                  // File: openzeppelin-solidity/contracts/AddressUtils.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * Utility library of inline functions on addresses
                   */
                  library AddressUtils {
                  
                    /**
                     * Returns whether the target address is a contract
                     * @dev This function will return false if invoked during the constructor of a contract,
                     * as the code is not actually created until after the constructor finishes.
                     * @param _addr address to check
                     * @return whether the target address is a contract
                     */
                    function isContract(address _addr) internal view returns (bool) {
                      uint256 size;
                      // XXX Currently there is no better way to check if there is a contract in an address
                      // than to check the size of the code at that address.
                      // See https://ethereum.stackexchange.com/a/14016/36603
                      // for more details about how this works.
                      // TODO Check this again before the Serenity release, because all addresses will be
                      // contracts then.
                      // solium-disable-next-line security/no-inline-assembly
                      assembly { size := extcodesize(_addr) }
                      return size > 0;
                    }
                  
                  }
                  
                  // File: contracts/upgradeable_contracts/ValidatorStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  contract ValidatorStorage {
                      bytes32 internal constant VALIDATOR_CONTRACT = 0x5a74bb7e202fb8e4bf311841c7d64ec19df195fee77d7e7ae749b27921b6ddfe; // keccak256(abi.encodePacked("validatorContract"))
                  }
                  
                  // File: contracts/upgradeable_contracts/Validatable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  contract Validatable is EternalStorage, ValidatorStorage {
                      function validatorContract() public view returns (IBridgeValidators) {
                          return IBridgeValidators(addressStorage[VALIDATOR_CONTRACT]);
                      }
                  
                      modifier onlyValidator() {
                          require(validatorContract().isValidator(msg.sender));
                          /* solcov ignore next */
                          _;
                      }
                  
                      function requiredSignatures() public view returns (uint256) {
                          return validatorContract().requiredSignatures();
                      }
                  
                  }
                  
                  // File: contracts/upgradeable_contracts/Ownable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title Ownable
                   * @dev This contract has an owner address providing basic authorization control
                   */
                  contract Ownable is EternalStorage {
                      bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
                  
                      /**
                      * @dev Event to show ownership has been transferred
                      * @param previousOwner representing the address of the previous owner
                      * @param newOwner representing the address of the new owner
                      */
                      event OwnershipTransferred(address previousOwner, address newOwner);
                  
                      /**
                      * @dev Throws if called by any account other than the owner.
                      */
                      modifier onlyOwner() {
                          require(msg.sender == owner());
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Throws if called by any account other than contract itself or owner.
                      */
                      modifier onlyRelevantSender() {
                          // proxy owner if used through proxy, address(0) otherwise
                          require(
                              !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
                                  msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
                                  msg.sender == address(this) // covers calls through upgradeAndCall proxy method
                          );
                          /* solcov ignore next */
                          _;
                      }
                  
                      bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
                  
                      /**
                      * @dev Tells the address of the owner
                      * @return the address of the owner
                      */
                      function owner() public view returns (address) {
                          return addressStorage[OWNER];
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner the address to transfer ownership to.
                      */
                      function transferOwnership(address newOwner) external onlyOwner {
                          require(newOwner != address(0));
                          setOwner(newOwner);
                      }
                  
                      /**
                      * @dev Sets a new owner address
                      */
                      function setOwner(address newOwner) internal {
                          emit OwnershipTransferred(owner(), newOwner);
                          addressStorage[OWNER] = newOwner;
                      }
                  }
                  
                  // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * @title ERC20Basic
                   * @dev Simpler version of ERC20 interface
                   * See https://github.com/ethereum/EIPs/issues/179
                   */
                  contract ERC20Basic {
                    function totalSupply() public view returns (uint256);
                    function balanceOf(address _who) public view returns (uint256);
                    function transfer(address _to, uint256 _value) public returns (bool);
                    event Transfer(address indexed from, address indexed to, uint256 value);
                  }
                  
                  // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  
                  /**
                   * @title ERC20 interface
                   * @dev see https://github.com/ethereum/EIPs/issues/20
                   */
                  contract ERC20 is ERC20Basic {
                    function allowance(address _owner, address _spender)
                      public view returns (uint256);
                  
                    function transferFrom(address _from, address _to, uint256 _value)
                      public returns (bool);
                  
                    function approve(address _spender, uint256 _value) public returns (bool);
                    event Approval(
                      address indexed owner,
                      address indexed spender,
                      uint256 value
                    );
                  }
                  
                  // File: contracts/upgradeable_contracts/Sacrifice.sol
                  
                  pragma solidity 0.4.24;
                  
                  contract Sacrifice {
                      constructor(address _recipient) public payable {
                          selfdestruct(_recipient);
                      }
                  }
                  
                  // File: contracts/libraries/Address.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  /**
                   * @title Address
                   * @dev Helper methods for Address type.
                   */
                  library Address {
                      /**
                      * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
                      * @param _receiver address that will receive the native tokens
                      * @param _value the amount of native tokens to send
                      */
                      function safeSendValue(address _receiver, uint256 _value) internal {
                          if (!_receiver.send(_value)) {
                              (new Sacrifice).value(_value)(_receiver);
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/Claimable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  contract Claimable {
                      bytes4 internal constant TRANSFER = 0xa9059cbb; // transfer(address,uint256)
                  
                      modifier validAddress(address _to) {
                          require(_to != address(0));
                          /* solcov ignore next */
                          _;
                      }
                  
                      function claimValues(address _token, address _to) internal {
                          if (_token == address(0)) {
                              claimNativeCoins(_to);
                          } else {
                              claimErc20Tokens(_token, _to);
                          }
                      }
                  
                      function claimNativeCoins(address _to) internal {
                          uint256 value = address(this).balance;
                          Address.safeSendValue(_to, value);
                      }
                  
                      function claimErc20Tokens(address _token, address _to) internal {
                          ERC20Basic token = ERC20Basic(_token);
                          uint256 balance = token.balanceOf(this);
                          safeTransfer(_token, _to, balance);
                      }
                  
                      function safeTransfer(address _token, address _to, uint256 _value) internal {
                          bytes memory returnData;
                          bool returnDataResult;
                          bytes memory callData = abi.encodeWithSelector(TRANSFER, _to, _value);
                          assembly {
                              let result := call(gas, _token, 0x0, add(callData, 0x20), mload(callData), 0, 32)
                              returnData := mload(0)
                              returnDataResult := mload(0)
                  
                              switch result
                                  case 0 {
                                      revert(0, 0)
                                  }
                          }
                  
                          // Return data is optional
                          if (returnData.length > 0) {
                              require(returnDataResult);
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/VersionableBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  contract VersionableBridge {
                      function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
                          return (5, 1, 0);
                      }
                  
                      /* solcov ignore next */
                      function getBridgeMode() external pure returns (bytes4);
                  }
                  
                  // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * @title SafeMath
                   * @dev Math operations with safety checks that throw on error
                   */
                  library SafeMath {
                  
                    /**
                    * @dev Multiplies two numbers, throws on overflow.
                    */
                    function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                      // Gas optimization: this is cheaper than asserting 'a' not being zero, but the
                      // benefit is lost if 'b' is also tested.
                      // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                      if (_a == 0) {
                        return 0;
                      }
                  
                      c = _a * _b;
                      assert(c / _a == _b);
                      return c;
                    }
                  
                    /**
                    * @dev Integer division of two numbers, truncating the quotient.
                    */
                    function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                      // assert(_b > 0); // Solidity automatically throws when dividing by 0
                      // uint256 c = _a / _b;
                      // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                      return _a / _b;
                    }
                  
                    /**
                    * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
                    */
                    function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                      assert(_b <= _a);
                      return _a - _b;
                    }
                  
                    /**
                    * @dev Adds two numbers, throws on overflow.
                    */
                    function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                      c = _a + _b;
                      assert(c >= _a);
                      return c;
                    }
                  }
                  
                  // File: contracts/upgradeable_contracts/DecimalShiftBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  contract DecimalShiftBridge is EternalStorage {
                      using SafeMath for uint256;
                  
                      bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift"))
                  
                      /**
                      * @dev Internal function for setting the decimal shift for bridge operations.
                      * Decimal shift can be positive, negative, or equal to zero.
                      * It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side.
                      * @param _shift new value of decimal shift.
                      */
                      function _setDecimalShift(int256 _shift) internal {
                          // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values
                          require(_shift > -77 && _shift < 77);
                          uintStorage[DECIMAL_SHIFT] = uint256(_shift);
                      }
                  
                      /**
                      * @dev Returns the value of foreign-to-home decimal shift.
                      * @return decimal shift.
                      */
                      function decimalShift() public view returns (int256) {
                          return int256(uintStorage[DECIMAL_SHIFT]);
                      }
                  
                      /**
                      * @dev Converts the amount of home tokens into the equivalent amount of foreign tokens.
                      * @param _value amount of home tokens.
                      * @return equivalent amount of foreign tokens.
                      */
                      function _unshiftValue(uint256 _value) internal view returns (uint256) {
                          return _shiftUint(_value, -decimalShift());
                      }
                  
                      /**
                      * @dev Converts the amount of foreign tokens into the equivalent amount of home tokens.
                      * @param _value amount of foreign tokens.
                      * @return equivalent amount of home tokens.
                      */
                      function _shiftValue(uint256 _value) internal view returns (uint256) {
                          return _shiftUint(_value, decimalShift());
                      }
                  
                      /**
                      * @dev Calculates _value * pow(10, _shift).
                      * @param _value amount of tokens.
                      * @param _shift decimal shift to apply.
                      * @return shifted value.
                      */
                      function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) {
                          if (_shift == 0) {
                              return _value;
                          }
                          if (_shift > 0) {
                              return _value.mul(10**uint256(_shift));
                          }
                          return _value.div(10**uint256(-_shift));
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/BasicBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  contract BasicBridge is
                      InitializableBridge,
                      Validatable,
                      Ownable,
                      Upgradeable,
                      Claimable,
                      VersionableBridge,
                      DecimalShiftBridge
                  {
                      event GasPriceChanged(uint256 gasPrice);
                      event RequiredBlockConfirmationChanged(uint256 requiredBlockConfirmations);
                  
                      bytes32 internal constant GAS_PRICE = 0x55b3774520b5993024893d303890baa4e84b1244a43c60034d1ced2d3cf2b04b; // keccak256(abi.encodePacked("gasPrice"))
                      bytes32 internal constant REQUIRED_BLOCK_CONFIRMATIONS = 0x916daedf6915000ff68ced2f0b6773fe6f2582237f92c3c95bb4d79407230071; // keccak256(abi.encodePacked("requiredBlockConfirmations"))
                  
                      /**
                      * @dev Public setter for fallback gas price value. Only bridge owner can call this method.
                      * @param _gasPrice new value for the gas price.
                      */
                      function setGasPrice(uint256 _gasPrice) external onlyOwner {
                          _setGasPrice(_gasPrice);
                      }
                  
                      function gasPrice() external view returns (uint256) {
                          return uintStorage[GAS_PRICE];
                      }
                  
                      function setRequiredBlockConfirmations(uint256 _blockConfirmations) external onlyOwner {
                          _setRequiredBlockConfirmations(_blockConfirmations);
                      }
                  
                      function _setRequiredBlockConfirmations(uint256 _blockConfirmations) internal {
                          require(_blockConfirmations > 0);
                          uintStorage[REQUIRED_BLOCK_CONFIRMATIONS] = _blockConfirmations;
                          emit RequiredBlockConfirmationChanged(_blockConfirmations);
                      }
                  
                      function requiredBlockConfirmations() external view returns (uint256) {
                          return uintStorage[REQUIRED_BLOCK_CONFIRMATIONS];
                      }
                  
                      function claimTokens(address _token, address _to) public onlyIfUpgradeabilityOwner validAddress(_to) {
                          claimValues(_token, _to);
                      }
                  
                      /**
                      * @dev Internal function for updating fallback gas price value.
                      * @param _gasPrice new value for the gas price, zero gas price is allowed.
                      */
                      function _setGasPrice(uint256 _gasPrice) internal {
                          uintStorage[GAS_PRICE] = _gasPrice;
                          emit GasPriceChanged(_gasPrice);
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/arbitrary_message/VersionableAMB.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract VersionableAMB is VersionableBridge {
                      // message format version as a single 4-bytes number padded to 32-bytes
                      // value, included into every outgoing relay request
                      //
                      // the message version should be updated every time when
                      // - new field appears
                      // - some field removed
                      // - fields order is changed
                      bytes32 internal constant MESSAGE_PACKING_VERSION = 0x00050000 << 224;
                  
                      /**
                       * Returns currently used bridge version
                       * @return (major, minor, patch) version triple
                       */
                      function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
                          return (5, 3, 0);
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/arbitrary_message/BasicAMB.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  contract BasicAMB is BasicBridge, VersionableAMB {
                      bytes32 internal constant MAX_GAS_PER_TX = 0x2670ecc91ec356e32067fd27b36614132d727b84a1e03e08f412a4f2cf075974; // keccak256(abi.encodePacked("maxGasPerTx"))
                      bytes32 internal constant NONCE = 0x7ab1577440dd7bedf920cb6de2f9fc6bf7ba98c78c85a3fa1f8311aac95e1759; // keccak256(abi.encodePacked("nonce"))
                      bytes32 internal constant SOURCE_CHAIN_ID = 0x67d6f42a1ed69c62022f2d160ddc6f2f0acd37ad1db0c24f4702d7d3343a4add; // keccak256(abi.encodePacked("sourceChainId"))
                      bytes32 internal constant SOURCE_CHAIN_ID_LENGTH = 0xe504ae1fd6471eea80f18b8532a61a9bb91fba4f5b837f80a1cfb6752350af44; // keccak256(abi.encodePacked("sourceChainIdLength"))
                      bytes32 internal constant DESTINATION_CHAIN_ID = 0xbbd454018e72a3f6c02bbd785bacc49e46292744f3f6761276723823aa332320; // keccak256(abi.encodePacked("destinationChainId"))
                      bytes32 internal constant DESTINATION_CHAIN_ID_LENGTH = 0xfb792ae4ad11102b93f26a51b3749c2b3667f8b561566a4806d4989692811594; // keccak256(abi.encodePacked("destinationChainIdLength"))
                  
                      /**
                       * Initializes AMB contract
                       * @param _sourceChainId chain id of a network where this contract is deployed
                       * @param _destinationChainId chain id of a network where all outgoing messages are directed
                       * @param _validatorContract address of the validators contract
                       * @param _maxGasPerTx maximum amount of gas per one message execution
                       * @param _gasPrice default gas price used by oracles for sending transactions in this network
                       * @param _requiredBlockConfirmations number of block confirmations oracle will wait before processing passed messages
                       * @param _owner address of new bridge owner
                       */
                      function initialize(
                          uint256 _sourceChainId,
                          uint256 _destinationChainId,
                          address _validatorContract,
                          uint256 _maxGasPerTx,
                          uint256 _gasPrice,
                          uint256 _requiredBlockConfirmations,
                          address _owner
                      ) external onlyRelevantSender returns (bool) {
                          require(!isInitialized());
                          require(AddressUtils.isContract(_validatorContract));
                  
                          _setChainIds(_sourceChainId, _destinationChainId);
                          addressStorage[VALIDATOR_CONTRACT] = _validatorContract;
                          uintStorage[DEPLOYED_AT_BLOCK] = block.number;
                          uintStorage[MAX_GAS_PER_TX] = _maxGasPerTx;
                          _setGasPrice(_gasPrice);
                          _setRequiredBlockConfirmations(_requiredBlockConfirmations);
                          setOwner(_owner);
                          setInitialize();
                  
                          return isInitialized();
                      }
                  
                      function getBridgeMode() external pure returns (bytes4 _data) {
                          return 0x2544fbb9; // bytes4(keccak256(abi.encodePacked("arbitrary-message-bridge-core")))
                      }
                  
                      function maxGasPerTx() public view returns (uint256) {
                          return uintStorage[MAX_GAS_PER_TX];
                      }
                  
                      function setMaxGasPerTx(uint256 _maxGasPerTx) external onlyOwner {
                          uintStorage[MAX_GAS_PER_TX] = _maxGasPerTx;
                      }
                  
                      /**
                       * Internal function for retrieving chain id for the source network
                       * @return chain id for the current network
                       */
                      function sourceChainId() public view returns (uint256) {
                          return uintStorage[SOURCE_CHAIN_ID];
                      }
                  
                      /**
                       * Internal function for retrieving chain id for the destination network
                       * @return chain id for the destination network
                       */
                      function destinationChainId() public view returns (uint256) {
                          return uintStorage[DESTINATION_CHAIN_ID];
                      }
                  
                      /**
                       * Updates chain ids of used networks
                       * @param _sourceChainId chain id for current network
                       * @param _destinationChainId chain id for opposite network
                       */
                      function setChainIds(uint256 _sourceChainId, uint256 _destinationChainId) external onlyOwner {
                          _setChainIds(_sourceChainId, _destinationChainId);
                      }
                  
                      /**
                       * Internal function for retrieving current nonce value
                       * @return nonce value
                       */
                      function _nonce() internal view returns (uint64) {
                          return uint64(uintStorage[NONCE]);
                      }
                  
                      /**
                       * Internal function for updating nonce value
                       * @param _nonce new nonce value
                       */
                      function _setNonce(uint64 _nonce) internal {
                          uintStorage[NONCE] = uint256(_nonce);
                      }
                  
                      /**
                       * Internal function for updating chain ids of used networks
                       * @param _sourceChainId chain id for current network
                       * @param _destinationChainId chain id for opposite network
                       */
                      function _setChainIds(uint256 _sourceChainId, uint256 _destinationChainId) internal {
                          require(_sourceChainId > 0 && _destinationChainId > 0);
                          require(_sourceChainId != _destinationChainId);
                          uint256 sourceChainIdLength = 0;
                          uint256 destinationChainIdLength = 0;
                          uint256 mask = 0xff;
                  
                          for (uint256 i = 1; sourceChainIdLength == 0 || destinationChainIdLength == 0; i++) {
                              if (sourceChainIdLength == 0 && _sourceChainId & mask == _sourceChainId) {
                                  sourceChainIdLength = i;
                              }
                              if (destinationChainIdLength == 0 && _destinationChainId & mask == _destinationChainId) {
                                  destinationChainIdLength = i;
                              }
                              mask = (mask << 8) | 0xff;
                          }
                  
                          uintStorage[SOURCE_CHAIN_ID] = _sourceChainId;
                          uintStorage[SOURCE_CHAIN_ID_LENGTH] = sourceChainIdLength;
                          uintStorage[DESTINATION_CHAIN_ID] = _destinationChainId;
                          uintStorage[DESTINATION_CHAIN_ID_LENGTH] = destinationChainIdLength;
                      }
                  
                      /**
                       * Internal function for retrieving chain id length for the source network
                       * @return chain id for the current network
                       */
                      function _sourceChainIdLength() internal view returns (uint256) {
                          return uintStorage[SOURCE_CHAIN_ID_LENGTH];
                      }
                  
                      /**
                       * Internal function for retrieving chain id length for the destination network
                       * @return chain id for the destination network
                       */
                      function _destinationChainIdLength() internal view returns (uint256) {
                          return uintStorage[DESTINATION_CHAIN_ID_LENGTH];
                      }
                  
                      /**
                       * Internal function for validating version of the received message
                       * @param _messageId id of the received message
                       */
                      function _isMessageVersionValid(bytes32 _messageId) internal returns (bool) {
                          return
                              _messageId & 0xffffffff00000000000000000000000000000000000000000000000000000000 == MESSAGE_PACKING_VERSION;
                      }
                  
                      /**
                       * Internal function for validating destination chain id of the received message
                       * @param _chainId destination chain id of the received message
                       */
                      function _isDestinationChainIdValid(uint256 _chainId) internal returns (bool res) {
                          return _chainId == sourceChainId();
                      }
                  }
                  
                  // File: contracts/libraries/Bytes.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title Bytes
                   * @dev Helper methods to transform bytes to other solidity types.
                   */
                  library Bytes {
                      /**
                      * @dev Converts bytes array to bytes32.
                      * Truncates bytes array if its size is more than 32 bytes.
                      * NOTE: This function does not perform any checks on the received parameter.
                      * Make sure that the _bytes argument has a correct length, not less than 32 bytes.
                      * A case when _bytes has length less than 32 will lead to the undefined behaviour,
                      * since assembly will read data from memory that is not related to the _bytes argument.
                      * @param _bytes to be converted to bytes32 type
                      * @return bytes32 type of the firsts 32 bytes array in parameter.
                      */
                      function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
                          assembly {
                              result := mload(add(_bytes, 32))
                          }
                      }
                  
                      /**
                      * @dev Truncate bytes array if its size is more than 20 bytes.
                      * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes.
                      * @param _bytes to be converted to address type
                      * @return address included in the firsts 20 bytes of the bytes array in parameter.
                      */
                      function bytesToAddress(bytes _bytes) internal pure returns (address addr) {
                          assembly {
                              addr := mload(add(_bytes, 20))
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/arbitrary_message/MessageProcessor.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  contract MessageProcessor is EternalStorage {
                      bytes32 internal constant MESSAGE_SENDER = 0x7b58b2a669d8e0992eae9eaef641092c0f686fd31070e7236865557fa1571b5b; // keccak256(abi.encodePacked("messageSender"))
                      bytes32 internal constant MESSAGE_ID = 0xe34bb2103dc34f2c144cc216c132d6ffb55dac57575c22e089161bbe65083304; // keccak256(abi.encodePacked("messageId"))
                      bytes32 internal constant MESSAGE_SOURCE_CHAIN_ID = 0x7f0fcd9e49860f055dd0c1682d635d309ecb5e3011654c716d9eb59a7ddec7d2; // keccak256(abi.encodePacked("messageSourceChainId"))
                  
                      /**
                      * @dev Returns a status of the message that came from the other side.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @return true if call executed successfully.
                      */
                      function messageCallStatus(bytes32 _messageId) external view returns (bool) {
                          return boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))];
                      }
                  
                      /**
                      * @dev Sets a status of the message that came from the other side.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @param _status execution status, true if executed successfully.
                      */
                      function setMessageCallStatus(bytes32 _messageId, bool _status) internal {
                          boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))] = _status;
                      }
                  
                      /**
                      * @dev Returns a data hash of the failed message that came from the other side.
                      * NOTE: dataHash was used previously to identify outgoing message before AMB message id was introduced.
                      * It is kept for backwards compatibility with old mediators contracts.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @return keccak256 hash of message data.
                      */
                      function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32) {
                          return bytes32(uintStorage[keccak256(abi.encodePacked("failedMessageDataHash", _messageId))]);
                      }
                  
                      /**
                      * @dev Sets a data hash of the failed message that came from the other side.
                      * NOTE: dataHash was used previously to identify outgoing message before AMB message id was introduced.
                      * It is kept for backwards compatibility with old mediators contracts.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @param data of the processed message.
                      */
                      function setFailedMessageDataHash(bytes32 _messageId, bytes data) internal {
                          uintStorage[keccak256(abi.encodePacked("failedMessageDataHash", _messageId))] = uint256(keccak256(data));
                      }
                  
                      /**
                      * @dev Returns a receiver address of the failed message that came from the other side.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @return receiver address.
                      */
                      function failedMessageReceiver(bytes32 _messageId) external view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))];
                      }
                  
                      /**
                      * @dev Sets a sender address of the failed message that came from the other side.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @param _receiver address of the receiver.
                      */
                      function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal {
                          addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver;
                      }
                  
                      /**
                      * @dev Returns a sender address of the failed message that came from the other side.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @return sender address on the other side.
                      */
                      function failedMessageSender(bytes32 _messageId) external view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("failedMessageSender", _messageId))];
                      }
                  
                      /**
                      * @dev Sets a sender address of the failed message that came from the other side.
                      * @param _messageId id of the message from the other side that triggered a call.
                      * @param _sender address of the sender on the other side.
                      */
                      function setFailedMessageSender(bytes32 _messageId, address _sender) internal {
                          addressStorage[keccak256(abi.encodePacked("failedMessageSender", _messageId))] = _sender;
                      }
                  
                      /**
                      * @dev Returns an address of the sender on the other side for the currently processed message.
                      * Can be used by executors for getting other side caller address.
                      * @return address of the sender on the other side.
                      */
                      function messageSender() external view returns (address) {
                          return addressStorage[MESSAGE_SENDER];
                      }
                  
                      /**
                      * @dev Sets an address of the sender on the other side for the currently processed message.
                      * @param _sender address of the sender on the other side.
                      */
                      function setMessageSender(address _sender) internal {
                          addressStorage[MESSAGE_SENDER] = _sender;
                      }
                  
                      /**
                      * @dev Returns an id of the currently processed message.
                      * @return id of the message that originated on the other side.
                      */
                      function messageId() public view returns (bytes32) {
                          return bytes32(uintStorage[MESSAGE_ID]);
                      }
                  
                      /**
                      * @dev Returns an id of the currently processed message.
                      * NOTE: transactionHash was used previously to identify incoming message before AMB message id was introduced.
                      * It is kept for backwards compatibility with old mediators contracts, although it doesn't return txHash anymore.
                      * @return id of the message that originated on the other side.
                      */
                      function transactionHash() external view returns (bytes32) {
                          return messageId();
                      }
                  
                      /**
                      * @dev Sets a message id of the currently processed message.
                      * @param _messageId id of the message that originated on the other side.
                      */
                      function setMessageId(bytes32 _messageId) internal {
                          uintStorage[MESSAGE_ID] = uint256(_messageId);
                      }
                  
                      /**
                      * @dev Returns an originating chain id of the currently processed message.
                      * @return source chain id of the message that originated on the other side.
                      */
                      function messageSourceChainId() external view returns (uint256) {
                          return uintStorage[MESSAGE_SOURCE_CHAIN_ID];
                      }
                  
                      /**
                      * @dev Returns an originating chain id of the currently processed message.
                      * @return source chain id of the message that originated on the other side.
                      */
                      function setMessageSourceChainId(uint256 _sourceChainId) internal returns (uint256) {
                          uintStorage[MESSAGE_SOURCE_CHAIN_ID] = _sourceChainId;
                      }
                  
                      /**
                      * @dev Processes received message. Makes a call to the message executor,
                      * sets dataHash, receive, sender variables for failed messages.
                      * @param _sender sender address on the other side.
                      * @param _executor address of an executor.
                      * @param _messageId id of the processed message.
                      * @param _gasLimit gas limit for a call to executor.
                      * @param _sourceChainId source chain id is of the received message.
                      * @param _data calldata for a call to executor.
                      */
                      function processMessage(
                          address _sender,
                          address _executor,
                          bytes32 _messageId,
                          uint256 _gasLimit,
                          bytes1, /* dataType */
                          uint256, /* gasPrice */
                          uint256 _sourceChainId,
                          bytes memory _data
                      ) internal {
                          bool status = _passMessage(_sender, _executor, _data, _gasLimit, _messageId, _sourceChainId);
                  
                          setMessageCallStatus(_messageId, status);
                          if (!status) {
                              setFailedMessageDataHash(_messageId, _data);
                              setFailedMessageReceiver(_messageId, _executor);
                              setFailedMessageSender(_messageId, _sender);
                          }
                          emitEventOnMessageProcessed(_sender, _executor, _messageId, status);
                      }
                  
                      /**
                      * @dev Makes a call to the message executor.
                      * @param _sender sender address on the other side.
                      * @param _contract address of an executor contract.
                      * @param _data calldata for a call to executor.
                      * @param _gas gas limit for a call to executor.
                      * @param _messageId id of the processed message.
                      * @param _sourceChainId source chain id is of the received message.
                      */
                      function _passMessage(
                          address _sender,
                          address _contract,
                          bytes _data,
                          uint256 _gas,
                          bytes32 _messageId,
                          uint256 _sourceChainId
                      ) internal returns (bool) {
                          setMessageSender(_sender);
                          setMessageId(_messageId);
                          setMessageSourceChainId(_sourceChainId);
                          bool status = _contract.call.gas(_gas)(_data);
                          setMessageSender(address(0));
                          setMessageId(bytes32(0));
                          setMessageSourceChainId(0);
                          return status;
                      }
                  
                      /* solcov ignore next */
                      function emitEventOnMessageProcessed(address sender, address executor, bytes32 messageId, bool status) internal;
                  }
                  
                  // File: contracts/upgradeable_contracts/arbitrary_message/MessageDelivery.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  contract MessageDelivery is BasicAMB, MessageProcessor {
                      using SafeMath for uint256;
                  
                      /**
                      * @dev Requests message relay to the opposite network
                      * @param _contract executor address on the other side
                      * @param _data calldata passed to the executor on the other side
                      * @param _gas gas limit used on the other network for executing a message
                      */
                      function requireToPassMessage(address _contract, bytes _data, uint256 _gas) public returns (bytes32) {
                          // it is not allowed to pass messages while other messages are processed
                          require(messageId() == bytes32(0));
                  
                          require(_gas >= getMinimumGasUsage(_data) && _gas <= maxGasPerTx());
                  
                          bytes32 _messageId;
                          bytes memory header = _packHeader(_contract, _gas);
                          _setNonce(_nonce() + 1);
                  
                          assembly {
                              _messageId := mload(add(header, 32))
                          }
                  
                          bytes memory eventData = abi.encodePacked(header, _data);
                  
                          emitEventOnMessageRequest(_messageId, eventData);
                          return _messageId;
                      }
                  
                      /**
                      * @dev Returns a lower limit on gas limit for the particular message data
                      * @param _data calldata passed to the executor on the other side
                      */
                      function getMinimumGasUsage(bytes _data) public pure returns (uint256 gas) {
                          // From Ethereum Yellow Paper
                          // 68 gas is paid for every non-zero byte of data or code for a transaction
                          // Starting from Istanbul hardfork, 16 gas is paid (EIP-2028)
                          return _data.length.mul(16);
                      }
                  
                      /**
                      * @dev Packs message header into a single bytes blob
                      * @param _contract executor address on the other side
                      * @param _gas gas limit used on the other network for executing a message
                      */
                      function _packHeader(address _contract, uint256 _gas) internal view returns (bytes memory header) {
                          uint256 srcChainId = sourceChainId();
                          uint256 srcChainIdLength = _sourceChainIdLength();
                          uint256 dstChainId = destinationChainId();
                          uint256 dstChainIdLength = _destinationChainIdLength();
                  
                          bytes32 mVer = MESSAGE_PACKING_VERSION;
                          uint256 nonce = _nonce();
                  
                          // Bridge id is recalculated every time again and again, since it is still cheaper than using SLOAD opcode (800 gas)
                          bytes32 bridgeId = keccak256(abi.encodePacked(srcChainId, address(this))) &
                              0x00000000ffffffffffffffffffffffffffffffffffffffff0000000000000000;
                          // 79 = 4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1
                          header = new bytes(79 + srcChainIdLength + dstChainIdLength);
                  
                          // In order to save the gas, the header is packed in the reverse order.
                          // With such approach, it is possible to store right-aligned values without any additional bit shifts.
                          assembly {
                              let ptr := add(header, mload(header)) // points to the last word of header
                              mstore(ptr, dstChainId)
                              mstore(sub(ptr, dstChainIdLength), srcChainId)
                  
                              mstore(add(header, 79), 0x00)
                              mstore(add(header, 78), dstChainIdLength)
                              mstore(add(header, 77), srcChainIdLength)
                              mstore(add(header, 76), _gas)
                              mstore(add(header, 72), _contract)
                              mstore(add(header, 52), caller)
                  
                              mstore(add(header, 32), or(mVer, or(bridgeId, nonce)))
                          }
                      }
                  
                      /* solcov ignore next */
                      function emitEventOnMessageRequest(bytes32 messageId, bytes encodedData) internal;
                  }
                  
                  // File: contracts/upgradeable_contracts/MessageRelay.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract MessageRelay is EternalStorage {
                      function relayedMessages(bytes32 _txHash) public view returns (bool) {
                          return boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))];
                      }
                  
                      function setRelayedMessages(bytes32 _txHash, bool _status) internal {
                          boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))] = _status;
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/arbitrary_message/BasicForeignAMB.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  contract BasicForeignAMB is BasicAMB, MessageRelay, MessageDelivery {
                      /**
                      * @dev Validates provided signatures and relays a given message
                      * @param _data bytes to be relayed
                      * @param _signatures bytes blob with signatures to be validated
                      */
                      function executeSignatures(bytes _data, bytes _signatures) external {
                          Message.hasEnoughValidSignatures(_data, _signatures, validatorContract(), true);
                  
                          bytes32 messageId;
                          address sender;
                          address executor;
                          uint32 gasLimit;
                          bytes1 dataType;
                          uint256[2] memory chainIds;
                          uint256 gasPrice;
                          bytes memory data;
                  
                          (messageId, sender, executor, gasLimit, dataType, chainIds, gasPrice, data) = ArbitraryMessage.unpackData(
                              _data
                          );
                          require(_isMessageVersionValid(messageId));
                          require(_isDestinationChainIdValid(chainIds[1]));
                          require(!relayedMessages(messageId));
                          setRelayedMessages(messageId, true);
                          processMessage(sender, executor, messageId, gasLimit, dataType, gasPrice, chainIds[0], data);
                      }
                  
                      /**
                      * @dev Internal function for updating fallback gas price value.
                      * @param _gasPrice new value for the gas price, zero gas price is not allowed.
                      */
                      function _setGasPrice(uint256 _gasPrice) internal {
                          require(_gasPrice > 0);
                          super._setGasPrice(_gasPrice);
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/arbitrary_message/ForeignAMB.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract ForeignAMB is BasicForeignAMB {
                      event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
                      event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
                  
                      function emitEventOnMessageRequest(bytes32 messageId, bytes encodedData) internal {
                          emit UserRequestForAffirmation(messageId, encodedData);
                      }
                  
                      function emitEventOnMessageProcessed(address sender, address executor, bytes32 messageId, bool status) internal {
                          emit RelayedMessage(sender, executor, messageId, status);
                      }
                  }
                  

                  File 5 of 7: EternalStorageProxy
                  // File: contracts/upgradeability/EternalStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title EternalStorage
                   * @dev This contract holds all the necessary state variables to carry out the storage of any contract.
                   */
                  contract EternalStorage {
                      mapping(bytes32 => uint256) internal uintStorage;
                      mapping(bytes32 => string) internal stringStorage;
                      mapping(bytes32 => address) internal addressStorage;
                      mapping(bytes32 => bytes) internal bytesStorage;
                      mapping(bytes32 => bool) internal boolStorage;
                      mapping(bytes32 => int256) internal intStorage;
                  
                  }
                  
                  // File: openzeppelin-solidity/contracts/AddressUtils.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * Utility library of inline functions on addresses
                   */
                  library AddressUtils {
                  
                    /**
                     * Returns whether the target address is a contract
                     * @dev This function will return false if invoked during the constructor of a contract,
                     * as the code is not actually created until after the constructor finishes.
                     * @param _addr address to check
                     * @return whether the target address is a contract
                     */
                    function isContract(address _addr) internal view returns (bool) {
                      uint256 size;
                      // XXX Currently there is no better way to check if there is a contract in an address
                      // than to check the size of the code at that address.
                      // See https://ethereum.stackexchange.com/a/14016/36603
                      // for more details about how this works.
                      // TODO Check this again before the Serenity release, because all addresses will be
                      // contracts then.
                      // solium-disable-next-line security/no-inline-assembly
                      assembly { size := extcodesize(_addr) }
                      return size > 0;
                    }
                  
                  }
                  
                  // File: contracts/upgradeability/Proxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title Proxy
                   * @dev Gives the possibility to delegate any call to a foreign implementation.
                   */
                  contract Proxy {
                      /**
                      * @dev Tells the address of the implementation where every call will be delegated.
                      * @return address of the implementation to which it will be delegated
                      */
                      /* solcov ignore next */
                      function implementation() public view returns (address);
                  
                      /**
                      * @dev Fallback function allowing to perform a delegatecall to the given implementation.
                      * This function will return whatever the implementation call returns
                      */
                      function() public payable {
                          // solhint-disable-previous-line no-complex-fallback
                          address _impl = implementation();
                          require(_impl != address(0));
                          assembly {
                              /*
                                  0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
                                  loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
                                  memory. It's needed because we're going to write the return data of delegatecall to the
                                  free memory slot.
                              */
                              let ptr := mload(0x40)
                              /*
                                  `calldatacopy` is copy calldatasize bytes from calldata
                                  First argument is the destination to which data is copied(ptr)
                                  Second argument specifies the start position of the copied data.
                                      Since calldata is sort of its own unique location in memory,
                                      0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
                                      That's always going to be the zeroth byte of the function selector.
                                  Third argument, calldatasize, specifies how much data will be copied.
                                      calldata is naturally calldatasize bytes long (same thing as msg.data.length)
                              */
                              calldatacopy(ptr, 0, calldatasize)
                              /*
                                  delegatecall params explained:
                                  gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
                                      us the amount of gas still available to execution
                  
                                  _impl: address of the contract to delegate to
                  
                                  ptr: to pass copied data
                  
                                  calldatasize: loads the size of `bytes memory data`, same as msg.data.length
                  
                                  0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
                                          these are set to 0, 0 so the output data will not be written to memory. The output
                                          data will be read using `returndatasize` and `returdatacopy` instead.
                  
                                  result: This will be 0 if the call fails and 1 if it succeeds
                              */
                              let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
                              /*
                  
                              */
                              /*
                                  ptr current points to the value stored at 0x40,
                                  because we assigned it like ptr := mload(0x40).
                                  Because we use 0x40 as a free memory pointer,
                                  we want to make sure that the next time we want to allocate memory,
                                  we aren't overwriting anything important.
                                  So, by adding ptr and returndatasize,
                                  we get a memory location beyond the end of the data we will be copying to ptr.
                                  We place this in at 0x40, and any reads from 0x40 will now read from free memory
                              */
                              mstore(0x40, add(ptr, returndatasize))
                              /*
                                  `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
                                      slot it will copy to, 0 means copy from the beginning of the return data, and size is
                                      the amount of data to copy.
                                  `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
                              */
                              returndatacopy(ptr, 0, returndatasize)
                  
                              /*
                                  if `result` is 0, revert.
                                  if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
                                  copied to `ptr` from the delegatecall return data
                              */
                              switch result
                                  case 0 {
                                      revert(ptr, returndatasize)
                                  }
                                  default {
                                      return(ptr, returndatasize)
                                  }
                          }
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title UpgradeabilityStorage
                   * @dev This contract holds all the necessary state variables to support the upgrade functionality
                   */
                  contract UpgradeabilityStorage {
                      // Version name of the current implementation
                      uint256 internal _version;
                  
                      // Address of the current implementation
                      address internal _implementation;
                  
                      /**
                      * @dev Tells the version name of the current implementation
                      * @return uint256 representing the name of the current version
                      */
                      function version() external view returns (uint256) {
                          return _version;
                      }
                  
                      /**
                      * @dev Tells the address of the current implementation
                      * @return address of the current implementation
                      */
                      function implementation() public view returns (address) {
                          return _implementation;
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  /**
                   * @title UpgradeabilityProxy
                   * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
                   */
                  contract UpgradeabilityProxy is Proxy, UpgradeabilityStorage {
                      /**
                      * @dev This event will be emitted every time the implementation gets upgraded
                      * @param version representing the version name of the upgraded implementation
                      * @param implementation representing the address of the upgraded implementation
                      */
                      event Upgraded(uint256 version, address indexed implementation);
                  
                      /**
                      * @dev Upgrades the implementation address
                      * @param version representing the version name of the new implementation to be set
                      * @param implementation representing the address of the new implementation to be set
                      */
                      function _upgradeTo(uint256 version, address implementation) internal {
                          require(_implementation != implementation);
                  
                          // This additional check verifies that provided implementation is at least a contract
                          require(AddressUtils.isContract(implementation));
                  
                          // This additional check guarantees that new version will be at least greater than the privios one,
                          // so it is impossible to reuse old versions, or use the last version twice
                          require(version > _version);
                  
                          _version = version;
                          _implementation = implementation;
                          emit Upgraded(version, implementation);
                      }
                  }
                  
                  // File: contracts/upgradeability/UpgradeabilityOwnerStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title UpgradeabilityOwnerStorage
                   * @dev This contract keeps track of the upgradeability owner
                   */
                  contract UpgradeabilityOwnerStorage {
                      // Owner of the contract
                      address internal _upgradeabilityOwner;
                  
                      /**
                      * @dev Tells the address of the owner
                      * @return the address of the owner
                      */
                      function upgradeabilityOwner() public view returns (address) {
                          return _upgradeabilityOwner;
                      }
                  
                      /**
                      * @dev Sets the address of the owner
                      */
                      function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
                          _upgradeabilityOwner = newUpgradeabilityOwner;
                      }
                  }
                  
                  // File: contracts/upgradeability/OwnedUpgradeabilityProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title OwnedUpgradeabilityProxy
                   * @dev This contract combines an upgradeability proxy with basic authorization control functionalities
                   */
                  contract OwnedUpgradeabilityProxy is UpgradeabilityOwnerStorage, UpgradeabilityProxy {
                      /**
                      * @dev Event to show ownership has been transferred
                      * @param previousOwner representing the address of the previous owner
                      * @param newOwner representing the address of the new owner
                      */
                      event ProxyOwnershipTransferred(address previousOwner, address newOwner);
                  
                      /**
                      * @dev the constructor sets the original owner of the contract to the sender account.
                      */
                      constructor() public {
                          setUpgradeabilityOwner(msg.sender);
                      }
                  
                      /**
                      * @dev Throws if called by any account other than the owner.
                      */
                      modifier onlyUpgradeabilityOwner() {
                          require(msg.sender == upgradeabilityOwner());
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner The address to transfer ownership to.
                      */
                      function transferProxyOwnership(address newOwner) external onlyUpgradeabilityOwner {
                          require(newOwner != address(0));
                          emit ProxyOwnershipTransferred(upgradeabilityOwner(), newOwner);
                          setUpgradeabilityOwner(newOwner);
                      }
                  
                      /**
                      * @dev Allows the upgradeability owner to upgrade the current version of the proxy.
                      * @param version representing the version name of the new implementation to be set.
                      * @param implementation representing the address of the new implementation to be set.
                      */
                      function upgradeTo(uint256 version, address implementation) public onlyUpgradeabilityOwner {
                          _upgradeTo(version, implementation);
                      }
                  
                      /**
                      * @dev Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation
                      * to initialize whatever is needed through a low level call.
                      * @param version representing the version name of the new implementation to be set.
                      * @param implementation representing the address of the new implementation to be set.
                      * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
                      * signature of the implementation to be called with the needed payload
                      */
                      function upgradeToAndCall(uint256 version, address implementation, bytes data)
                          external
                          payable
                          onlyUpgradeabilityOwner
                      {
                          upgradeTo(version, implementation);
                          // solhint-disable-next-line avoid-call-value
                          require(address(this).call.value(msg.value)(data));
                      }
                  }
                  
                  // File: contracts/upgradeability/EternalStorageProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title EternalStorageProxy
                   * @dev This proxy holds the storage of the token contract and delegates every call to the current implementation set.
                   * Besides, it allows to upgrade the token's behaviour towards further implementations, and provides basic
                   * authorization control functionalities
                   */
                  // solhint-disable-next-line no-empty-blocks
                  contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {}
                  

                  File 6 of 7: BridgeValidators
                  // File: contracts/upgradeability/EternalStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title EternalStorage
                   * @dev This contract holds all the necessary state variables to carry out the storage of any contract.
                   */
                  contract EternalStorage {
                      mapping(bytes32 => uint256) internal uintStorage;
                      mapping(bytes32 => string) internal stringStorage;
                      mapping(bytes32 => address) internal addressStorage;
                      mapping(bytes32 => bytes) internal bytesStorage;
                      mapping(bytes32 => bool) internal boolStorage;
                      mapping(bytes32 => int256) internal intStorage;
                  
                  }
                  
                  // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  interface IUpgradeabilityOwnerStorage {
                      function upgradeabilityOwner() external view returns (address);
                  }
                  
                  // File: contracts/upgradeable_contracts/Ownable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title Ownable
                   * @dev This contract has an owner address providing basic authorization control
                   */
                  contract Ownable is EternalStorage {
                      bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
                  
                      /**
                      * @dev Event to show ownership has been transferred
                      * @param previousOwner representing the address of the previous owner
                      * @param newOwner representing the address of the new owner
                      */
                      event OwnershipTransferred(address previousOwner, address newOwner);
                  
                      /**
                      * @dev Throws if called by any account other than the owner.
                      */
                      modifier onlyOwner() {
                          require(msg.sender == owner());
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Throws if called by any account other than contract itself or owner.
                      */
                      modifier onlyRelevantSender() {
                          // proxy owner if used through proxy, address(0) otherwise
                          require(
                              !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
                                  msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
                                  msg.sender == address(this) // covers calls through upgradeAndCall proxy method
                          );
                          /* solcov ignore next */
                          _;
                      }
                  
                      bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
                  
                      /**
                      * @dev Tells the address of the owner
                      * @return the address of the owner
                      */
                      function owner() public view returns (address) {
                          return addressStorage[OWNER];
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner the address to transfer ownership to.
                      */
                      function transferOwnership(address newOwner) external onlyOwner {
                          require(newOwner != address(0));
                          setOwner(newOwner);
                      }
                  
                      /**
                      * @dev Sets a new owner address
                      */
                      function setOwner(address newOwner) internal {
                          emit OwnershipTransferred(owner(), newOwner);
                          addressStorage[OWNER] = newOwner;
                      }
                  }
                  
                  // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * @title SafeMath
                   * @dev Math operations with safety checks that throw on error
                   */
                  library SafeMath {
                  
                    /**
                    * @dev Multiplies two numbers, throws on overflow.
                    */
                    function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                      // Gas optimization: this is cheaper than asserting 'a' not being zero, but the
                      // benefit is lost if 'b' is also tested.
                      // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                      if (_a == 0) {
                        return 0;
                      }
                  
                      c = _a * _b;
                      assert(c / _a == _b);
                      return c;
                    }
                  
                    /**
                    * @dev Integer division of two numbers, truncating the quotient.
                    */
                    function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                      // assert(_b > 0); // Solidity automatically throws when dividing by 0
                      // uint256 c = _a / _b;
                      // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                      return _a / _b;
                    }
                  
                    /**
                    * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
                    */
                    function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                      assert(_b <= _a);
                      return _a - _b;
                    }
                  
                    /**
                    * @dev Adds two numbers, throws on overflow.
                    */
                    function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                      c = _a + _b;
                      assert(c >= _a);
                      return c;
                    }
                  }
                  
                  // File: contracts/upgradeable_contracts/Initializable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract Initializable is EternalStorage {
                      bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
                  
                      function setInitialize() internal {
                          boolStorage[INITIALIZED] = true;
                      }
                  
                      function isInitialized() public view returns (bool) {
                          return boolStorage[INITIALIZED];
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/InitializableBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract InitializableBridge is Initializable {
                      bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock"))
                  
                      function deployedAtBlock() external view returns (uint256) {
                          return uintStorage[DEPLOYED_AT_BLOCK];
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/BaseBridgeValidators.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  contract BaseBridgeValidators is InitializableBridge, Ownable {
                      using SafeMath for uint256;
                  
                      address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
                      uint256 internal constant MAX_VALIDATORS = 50;
                      bytes32 internal constant REQUIRED_SIGNATURES = 0xd18ea17c351d6834a0e568067fb71804d2a588d5e26d60f792b1c724b1bd53b1; // keccak256(abi.encodePacked("requiredSignatures"))
                      bytes32 internal constant VALIDATOR_COUNT = 0x8656d603d9f985c3483946a92789d52202f49736384ba131cb92f62c4c1aa082; // keccak256(abi.encodePacked("validatorCount"))
                  
                      event ValidatorAdded(address indexed validator);
                      event ValidatorRemoved(address indexed validator);
                      event RequiredSignaturesChanged(uint256 requiredSignatures);
                  
                      function setRequiredSignatures(uint256 _requiredSignatures) external onlyOwner {
                          require(validatorCount() >= _requiredSignatures);
                          require(_requiredSignatures != 0);
                          uintStorage[REQUIRED_SIGNATURES] = _requiredSignatures;
                          emit RequiredSignaturesChanged(_requiredSignatures);
                      }
                  
                      function getBridgeValidatorsInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
                          return (2, 3, 0);
                      }
                  
                      function validatorList() external view returns (address[]) {
                          address[] memory list = new address[](validatorCount());
                          uint256 counter = 0;
                          address nextValidator = getNextValidator(F_ADDR);
                          require(nextValidator != address(0));
                  
                          while (nextValidator != F_ADDR) {
                              list[counter] = nextValidator;
                              nextValidator = getNextValidator(nextValidator);
                              counter++;
                  
                              require(nextValidator != address(0));
                          }
                  
                          return list;
                      }
                  
                      function _addValidator(address _validator) internal {
                          require(_validator != address(0) && _validator != F_ADDR);
                          require(!isValidator(_validator));
                  
                          address firstValidator = getNextValidator(F_ADDR);
                          require(firstValidator != address(0));
                          setNextValidator(_validator, firstValidator);
                          setNextValidator(F_ADDR, _validator);
                          setValidatorCount(validatorCount().add(1));
                      }
                  
                      function _removeValidator(address _validator) internal {
                          require(validatorCount() > requiredSignatures());
                          require(isValidator(_validator));
                          address validatorsNext = getNextValidator(_validator);
                          address index = F_ADDR;
                          address next = getNextValidator(index);
                          require(next != address(0));
                  
                          while (next != _validator) {
                              index = next;
                              next = getNextValidator(index);
                  
                              require(next != F_ADDR && next != address(0));
                          }
                  
                          setNextValidator(index, validatorsNext);
                          deleteItemFromAddressStorage("validatorsList", _validator);
                          setValidatorCount(validatorCount().sub(1));
                      }
                  
                      function requiredSignatures() public view returns (uint256) {
                          return uintStorage[REQUIRED_SIGNATURES];
                      }
                  
                      function validatorCount() public view returns (uint256) {
                          return uintStorage[VALIDATOR_COUNT];
                      }
                  
                      function isValidator(address _validator) public view returns (bool) {
                          return _validator != F_ADDR && getNextValidator(_validator) != address(0);
                      }
                  
                      function getNextValidator(address _address) public view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("validatorsList", _address))];
                      }
                  
                      function deleteItemFromAddressStorage(string _mapName, address _address) internal {
                          delete addressStorage[keccak256(abi.encodePacked(_mapName, _address))];
                      }
                  
                      function setValidatorCount(uint256 _validatorCount) internal {
                          require(_validatorCount <= MAX_VALIDATORS);
                          uintStorage[VALIDATOR_COUNT] = _validatorCount;
                      }
                  
                      function setNextValidator(address _prevValidator, address _validator) internal {
                          addressStorage[keccak256(abi.encodePacked("validatorsList", _prevValidator))] = _validator;
                      }
                  
                      function isValidatorDuty(address _validator) external view returns (bool) {
                          uint256 counter = 0;
                          address next = getNextValidator(F_ADDR);
                          require(next != address(0));
                  
                          while (next != F_ADDR) {
                              if (next == _validator) {
                                  return (block.number % validatorCount() == counter);
                              }
                  
                              next = getNextValidator(next);
                              counter++;
                  
                              require(next != address(0));
                          }
                  
                          return false;
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/BridgeValidators.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract BridgeValidators is BaseBridgeValidators {
                      function initialize(uint256 _requiredSignatures, address[] _initialValidators, address _owner)
                          external
                          onlyRelevantSender
                          returns (bool)
                      {
                          require(!isInitialized());
                          require(_owner != address(0));
                          setOwner(_owner);
                          require(_requiredSignatures != 0);
                          require(_initialValidators.length >= _requiredSignatures);
                  
                          for (uint256 i = 0; i < _initialValidators.length; i++) {
                              require(_initialValidators[i] != address(0) && _initialValidators[i] != F_ADDR);
                              require(!isValidator(_initialValidators[i]));
                  
                              if (i == 0) {
                                  setNextValidator(F_ADDR, _initialValidators[i]);
                                  if (_initialValidators.length == 1) {
                                      setNextValidator(_initialValidators[i], F_ADDR);
                                  }
                              } else if (i == _initialValidators.length - 1) {
                                  setNextValidator(_initialValidators[i - 1], _initialValidators[i]);
                                  setNextValidator(_initialValidators[i], F_ADDR);
                              } else {
                                  setNextValidator(_initialValidators[i - 1], _initialValidators[i]);
                              }
                  
                              emit ValidatorAdded(_initialValidators[i]);
                          }
                  
                          setValidatorCount(_initialValidators.length);
                          uintStorage[REQUIRED_SIGNATURES] = _requiredSignatures;
                          uintStorage[DEPLOYED_AT_BLOCK] = block.number;
                          setInitialize();
                          emit RequiredSignaturesChanged(_requiredSignatures);
                  
                          return isInitialized();
                      }
                  
                      function addValidator(address _validator) external onlyOwner {
                          _addValidator(_validator);
                          emit ValidatorAdded(_validator);
                      }
                  
                      function removeValidator(address _validator) external onlyOwner {
                          _removeValidator(_validator);
                          emit ValidatorRemoved(_validator);
                      }
                  }
                  

                  File 7 of 7: ForeignMultiAMBErc20ToErc677
                  // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * @title ERC20Basic
                   * @dev Simpler version of ERC20 interface
                   * See https://github.com/ethereum/EIPs/issues/179
                   */
                  contract ERC20Basic {
                    function totalSupply() public view returns (uint256);
                    function balanceOf(address _who) public view returns (uint256);
                    function transfer(address _to, uint256 _value) public returns (bool);
                    event Transfer(address indexed from, address indexed to, uint256 value);
                  }
                  
                  // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  
                  /**
                   * @title ERC20 interface
                   * @dev see https://github.com/ethereum/EIPs/issues/20
                   */
                  contract ERC20 is ERC20Basic {
                    function allowance(address _owner, address _spender)
                      public view returns (uint256);
                  
                    function transferFrom(address _from, address _to, uint256 _value)
                      public returns (bool);
                  
                    function approve(address _spender, uint256 _value) public returns (bool);
                    event Approval(
                      address indexed owner,
                      address indexed spender,
                      uint256 value
                    );
                  }
                  
                  // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  
                  /**
                   * @title DetailedERC20 token
                   * @dev The decimals are only for visualization purposes.
                   * All the operations are done using the smallest and indivisible token unit,
                   * just as on Ethereum all the operations are done in wei.
                   */
                  contract DetailedERC20 is ERC20 {
                    string public name;
                    string public symbol;
                    uint8 public decimals;
                  
                    constructor(string _name, string _symbol, uint8 _decimals) public {
                      name = _name;
                      symbol = _symbol;
                      decimals = _decimals;
                    }
                  }
                  
                  // File: contracts/interfaces/IAMB.sol
                  
                  pragma solidity 0.4.24;
                  
                  interface IAMB {
                      function messageSender() external view returns (address);
                      function maxGasPerTx() external view returns (uint256);
                      function transactionHash() external view returns (bytes32);
                      function messageId() external view returns (bytes32);
                      function messageSourceChainId() external view returns (bytes32);
                      function messageCallStatus(bytes32 _messageId) external view returns (bool);
                      function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
                      function failedMessageReceiver(bytes32 _messageId) external view returns (address);
                      function failedMessageSender(bytes32 _messageId) external view returns (address);
                      function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
                      function sourceChainId() external view returns (uint256);
                      function destinationChainId() external view returns (uint256);
                  }
                  
                  // File: contracts/interfaces/ERC677.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract ERC677 is ERC20 {
                      event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
                  
                      function transferAndCall(address, uint256, bytes) external returns (bool);
                  
                      function increaseAllowance(address spender, uint256 addedValue) public returns (bool);
                      function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool);
                  }
                  
                  contract LegacyERC20 {
                      function transfer(address _spender, uint256 _value) public; // returns (bool);
                      function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool);
                  }
                  
                  // File: openzeppelin-solidity/contracts/math/SafeMath.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * @title SafeMath
                   * @dev Math operations with safety checks that throw on error
                   */
                  library SafeMath {
                  
                    /**
                    * @dev Multiplies two numbers, throws on overflow.
                    */
                    function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                      // Gas optimization: this is cheaper than asserting 'a' not being zero, but the
                      // benefit is lost if 'b' is also tested.
                      // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                      if (_a == 0) {
                        return 0;
                      }
                  
                      c = _a * _b;
                      assert(c / _a == _b);
                      return c;
                    }
                  
                    /**
                    * @dev Integer division of two numbers, truncating the quotient.
                    */
                    function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
                      // assert(_b > 0); // Solidity automatically throws when dividing by 0
                      // uint256 c = _a / _b;
                      // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
                      return _a / _b;
                    }
                  
                    /**
                    * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
                    */
                    function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
                      assert(_b <= _a);
                      return _a - _b;
                    }
                  
                    /**
                    * @dev Adds two numbers, throws on overflow.
                    */
                    function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
                      c = _a + _b;
                      assert(c >= _a);
                      return c;
                    }
                  }
                  
                  // File: contracts/upgradeability/EternalStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title EternalStorage
                   * @dev This contract holds all the necessary state variables to carry out the storage of any contract.
                   */
                  contract EternalStorage {
                      mapping(bytes32 => uint256) internal uintStorage;
                      mapping(bytes32 => string) internal stringStorage;
                      mapping(bytes32 => address) internal addressStorage;
                      mapping(bytes32 => bytes) internal bytesStorage;
                      mapping(bytes32 => bool) internal boolStorage;
                      mapping(bytes32 => int256) internal intStorage;
                  
                  }
                  
                  // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  interface IUpgradeabilityOwnerStorage {
                      function upgradeabilityOwner() external view returns (address);
                  }
                  
                  // File: contracts/upgradeable_contracts/Ownable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title Ownable
                   * @dev This contract has an owner address providing basic authorization control
                   */
                  contract Ownable is EternalStorage {
                      bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
                  
                      /**
                      * @dev Event to show ownership has been transferred
                      * @param previousOwner representing the address of the previous owner
                      * @param newOwner representing the address of the new owner
                      */
                      event OwnershipTransferred(address previousOwner, address newOwner);
                  
                      /**
                      * @dev Throws if called by any account other than the owner.
                      */
                      modifier onlyOwner() {
                          require(msg.sender == owner());
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Throws if called by any account other than contract itself or owner.
                      */
                      modifier onlyRelevantSender() {
                          // proxy owner if used through proxy, address(0) otherwise
                          require(
                              !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
                                  msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
                                  msg.sender == address(this) // covers calls through upgradeAndCall proxy method
                          );
                          /* solcov ignore next */
                          _;
                      }
                  
                      bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
                  
                      /**
                      * @dev Tells the address of the owner
                      * @return the address of the owner
                      */
                      function owner() public view returns (address) {
                          return addressStorage[OWNER];
                      }
                  
                      /**
                      * @dev Allows the current owner to transfer control of the contract to a newOwner.
                      * @param newOwner the address to transfer ownership to.
                      */
                      function transferOwnership(address newOwner) external onlyOwner {
                          require(newOwner != address(0));
                          setOwner(newOwner);
                      }
                  
                      /**
                      * @dev Sets a new owner address
                      */
                      function setOwner(address newOwner) internal {
                          emit OwnershipTransferred(owner(), newOwner);
                          addressStorage[OWNER] = newOwner;
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiTokenBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  contract BasicMultiTokenBridge is EternalStorage, Ownable {
                      using SafeMath for uint256;
                  
                      // token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens
                      event DailyLimitChanged(address indexed token, uint256 newLimit);
                      event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit);
                  
                      /**
                      * @dev Checks if specified token was already bridged at least once.
                      * @param _token address of the token contract.
                      * @return true, if token address is address(0) or token was already bridged.
                      */
                      function isTokenRegistered(address _token) public view returns (bool) {
                          return minPerTx(_token) > 0;
                      }
                  
                      /**
                      * @dev Retrieves the total spent amount for particular token during specific day.
                      * @param _token address of the token contract.
                      * @param _day day number for which spent amount if requested.
                      * @return amount of tokens sent through the bridge to the other side.
                      */
                      function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))];
                      }
                  
                      /**
                      * @dev Retrieves the total executed amount for particular token during specific day.
                      * @param _token address of the token contract.
                      * @param _day day number for which spent amount if requested.
                      * @return amount of tokens received from the bridge from the other side.
                      */
                      function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))];
                      }
                  
                      /**
                      * @dev Retrieves current daily limit for a particular token contract.
                      * @param _token address of the token contract.
                      * @return daily limit on tokens that can be sent through the bridge per day.
                      */
                      function dailyLimit(address _token) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))];
                      }
                  
                      /**
                      * @dev Retrieves current execution daily limit for a particular token contract.
                      * @param _token address of the token contract.
                      * @return daily limit on tokens that can be received from the bridge on the other side per day.
                      */
                      function executionDailyLimit(address _token) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))];
                      }
                  
                      /**
                      * @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract.
                      * @param _token address of the token contract.
                      * @return maximum amount on tokens that can be sent through the bridge in one transfer.
                      */
                      function maxPerTx(address _token) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))];
                      }
                  
                      /**
                      * @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract.
                      * @param _token address of the token contract.
                      * @return maximum amount on tokens that can received from the bridge on the other side in one transaction.
                      */
                      function executionMaxPerTx(address _token) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))];
                      }
                  
                      /**
                      * @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract.
                      * @param _token address of the token contract.
                      * @return minimum amount on tokens that can be sent through the bridge in one transfer.
                      */
                      function minPerTx(address _token) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))];
                      }
                  
                      /**
                      * @dev Checks that bridged amount of tokens conforms to the configured limits.
                      * @param _token address of the token contract.
                      * @param _amount amount of bridge tokens.
                      * @return true, if specified amount can be bridged.
                      */
                      function withinLimit(address _token, uint256 _amount) public view returns (bool) {
                          uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount);
                          return
                              dailyLimit(address(0)) > 0 &&
                                  dailyLimit(_token) >= nextLimit &&
                                  _amount <= maxPerTx(_token) &&
                                  _amount >= minPerTx(_token);
                      }
                  
                      /**
                      * @dev Checks that bridged amount of tokens conforms to the configured execution limits.
                      * @param _token address of the token contract.
                      * @param _amount amount of bridge tokens.
                      * @return true, if specified amount can be processed and executed.
                      */
                      function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) {
                          uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount);
                          return
                              executionDailyLimit(address(0)) > 0 &&
                                  executionDailyLimit(_token) >= nextLimit &&
                                  _amount <= executionMaxPerTx(_token);
                      }
                  
                      /**
                      * @dev Returns current day number.
                      * @return day number.
                      */
                      function getCurrentDay() public view returns (uint256) {
                          // solhint-disable-next-line not-rely-on-time
                          return now / 1 days;
                      }
                  
                      /**
                      * @dev Updates daily limit for the particular token. Only owner can call this method.
                      * @param _token address of the token contract, or address(0) for configuring the efault limit.
                      * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx.
                      * 0 value is also allowed, will stop the bridge operations in outgoing direction.
                      */
                      function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
                          require(isTokenRegistered(_token));
                          require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0);
                          uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit;
                          emit DailyLimitChanged(_token, _dailyLimit);
                      }
                  
                      /**
                      * @dev Updates execution daily limit for the particular token. Only owner can call this method.
                      * @param _token address of the token contract, or address(0) for configuring the default limit.
                      * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx.
                      * 0 value is also allowed, will stop the bridge operations in incoming direction.
                      */
                      function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
                          require(isTokenRegistered(_token));
                          require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0);
                          uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit;
                          emit ExecutionDailyLimitChanged(_token, _dailyLimit);
                      }
                  
                      /**
                      * @dev Updates execution maximum per transaction for the particular token. Only owner can call this method.
                      * @param _token address of the token contract, or address(0) for configuring the default limit.
                      * @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit.
                      * 0 value is also allowed, will stop the bridge operations in incoming direction.
                      */
                      function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
                          require(isTokenRegistered(_token));
                          require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token)));
                          uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx;
                      }
                  
                      /**
                      * @dev Updates maximum per transaction for the particular token. Only owner can call this method.
                      * @param _token address of the token contract, or address(0) for configuring the default limit.
                      * @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx.
                      * 0 value is also allowed, will stop the bridge operations in outgoing direction.
                      */
                      function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
                          require(isTokenRegistered(_token));
                          require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
                          uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
                      }
                  
                      /**
                      * @dev Updates minumum per transaction for the particular token. Only owner can call this method.
                      * @param _token address of the token contract, or address(0) for configuring the default limit.
                      * @param _minPerTx minumum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit.
                      */
                      function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner {
                          require(isTokenRegistered(_token));
                          require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token));
                          uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx;
                      }
                  
                      /**
                      * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
                      * @param _token address of the token contract, or address(0) for the default limit.
                      * @return minimum of maxPerTx parameter and remaining daily quota.
                      */
                      function maxAvailablePerTx(address _token) public view returns (uint256) {
                          uint256 _maxPerTx = maxPerTx(_token);
                          uint256 _dailyLimit = dailyLimit(_token);
                          uint256 _spent = totalSpentPerDay(_token, getCurrentDay());
                          uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
                          return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
                      }
                  
                      /**
                      * @dev Internal function for adding spent amount for some token.
                      * @param _token address of the token contract.
                      * @param _day day number, when tokens are processed.
                      * @param _value amount of bridge tokens.
                      */
                      function addTotalSpentPerDay(address _token, uint256 _day, uint256 _value) internal {
                          uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add(
                              _value
                          );
                      }
                  
                      /**
                      * @dev Internal function for adding execcuted amount for some token.
                      * @param _token address of the token contract.
                      * @param _day day number, when tokens are processed.
                      * @param _value amount of bridge tokens.
                      */
                      function addTotalExecutedPerDay(address _token, uint256 _day, uint256 _value) internal {
                          uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay(
                              _token,
                              _day
                          )
                              .add(_value);
                      }
                  
                      /**
                      * @dev Internal function for initializing limits for some token.
                      * @param _token address of the token contract.
                      * @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ].
                      */
                      function _setLimits(address _token, uint256[3] _limits) internal {
                          require(
                              _limits[2] > 0 && // minPerTx > 0
                                  _limits[1] > _limits[2] && // maxPerTx > minPerTx
                                  _limits[0] > _limits[1] // dailyLimit > maxPerTx
                          );
                  
                          uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0];
                          uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1];
                          uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2];
                  
                          emit DailyLimitChanged(_token, _limits[0]);
                      }
                  
                      /**
                      * @dev Internal function for initializing execution limits for some token.
                      * @param _token address of the token contract.
                      * @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ].
                      */
                      function _setExecutionLimits(address _token, uint256[2] _limits) internal {
                          require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
                  
                          uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0];
                          uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1];
                  
                          emit ExecutionDailyLimitChanged(_token, _limits[0]);
                      }
                  
                      /**
                      * @dev Internal function for initializing limits for some token relative to its decimals parameter.
                      * @param _token address of the token contract.
                      * @param _decimals token decimals parameter.
                      */
                      function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal {
                          uint256 factor;
                          if (_decimals < 18) {
                              factor = 10**(18 - _decimals);
                  
                              uint256 _minPerTx = minPerTx(address(0)).div(factor);
                              uint256 _maxPerTx = maxPerTx(address(0)).div(factor);
                              uint256 _dailyLimit = dailyLimit(address(0)).div(factor);
                              uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor);
                              uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor);
                  
                              // such situation can happen when calculated limits relative to the token decimals are too low
                              // e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed.
                              // in this case, limits are raised to the default values
                              if (_minPerTx == 0) {
                                  _minPerTx = 1;
                                  if (_maxPerTx <= _minPerTx) {
                                      _maxPerTx = 100;
                                      _executionMaxPerTx = 100;
                                      if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) {
                                          _dailyLimit = 10000;
                                          _executionDailyLimit = 10000;
                                      }
                                  }
                              }
                              _setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]);
                              _setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]);
                          } else {
                              factor = 10**(_decimals - 18);
                              _setLimits(
                                  _token,
                                  [dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)]
                              );
                              _setExecutionLimits(
                                  _token,
                                  [executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)]
                              );
                          }
                      }
                  }
                  
                  // File: contracts/libraries/Bytes.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title Bytes
                   * @dev Helper methods to transform bytes to other solidity types.
                   */
                  library Bytes {
                      /**
                      * @dev Converts bytes array to bytes32.
                      * Truncates bytes array if its size is more than 32 bytes.
                      * NOTE: This function does not perform any checks on the received parameter.
                      * Make sure that the _bytes argument has a correct length, not less than 32 bytes.
                      * A case when _bytes has length less than 32 will lead to the undefined behaviour,
                      * since assembly will read data from memory that is not related to the _bytes argument.
                      * @param _bytes to be converted to bytes32 type
                      * @return bytes32 type of the firsts 32 bytes array in parameter.
                      */
                      function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
                          assembly {
                              result := mload(add(_bytes, 32))
                          }
                      }
                  
                      /**
                      * @dev Truncate bytes array if its size is more than 20 bytes.
                      * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes.
                      * @param _bytes to be converted to address type
                      * @return address included in the firsts 20 bytes of the bytes array in parameter.
                      */
                      function bytesToAddress(bytes _bytes) internal pure returns (address addr) {
                          assembly {
                              addr := mload(add(_bytes, 20))
                          }
                      }
                  }
                  
                  // File: openzeppelin-solidity/contracts/AddressUtils.sol
                  
                  pragma solidity ^0.4.24;
                  
                  
                  /**
                   * Utility library of inline functions on addresses
                   */
                  library AddressUtils {
                  
                    /**
                     * Returns whether the target address is a contract
                     * @dev This function will return false if invoked during the constructor of a contract,
                     * as the code is not actually created until after the constructor finishes.
                     * @param _addr address to check
                     * @return whether the target address is a contract
                     */
                    function isContract(address _addr) internal view returns (bool) {
                      uint256 size;
                      // XXX Currently there is no better way to check if there is a contract in an address
                      // than to check the size of the code at that address.
                      // See https://ethereum.stackexchange.com/a/14016/36603
                      // for more details about how this works.
                      // TODO Check this again before the Serenity release, because all addresses will be
                      // contracts then.
                      // solium-disable-next-line security/no-inline-assembly
                      assembly { size := extcodesize(_addr) }
                      return size > 0;
                    }
                  
                  }
                  
                  // File: contracts/upgradeable_contracts/BasicAMBMediator.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  /**
                  * @title BasicAMBMediator
                  * @dev Basic storage and methods needed by mediators to interact with AMB bridge.
                  */
                  contract BasicAMBMediator is Ownable {
                      bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
                      bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
                      bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
                  
                      /**
                      * @dev Throws if caller on the other side is not an associated mediator.
                      */
                      modifier onlyMediator {
                          require(msg.sender == address(bridgeContract()));
                          require(messageSender() == mediatorContractOnOtherSide());
                          _;
                      }
                  
                      /**
                      * @dev Sets the AMB bridge contract address. Only the owner can call this method.
                      * @param _bridgeContract the address of the bridge contract.
                      */
                      function setBridgeContract(address _bridgeContract) external onlyOwner {
                          _setBridgeContract(_bridgeContract);
                      }
                  
                      /**
                      * @dev Sets the mediator contract address from the other network. Only the owner can call this method.
                      * @param _mediatorContract the address of the mediator contract.
                      */
                      function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
                          _setMediatorContractOnOtherSide(_mediatorContract);
                      }
                  
                      /**
                      * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network.
                      * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
                      * Only the owner can call this method.
                      * @param _requestGasLimit the gas limit for the message execution.
                      */
                      function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner {
                          _setRequestGasLimit(_requestGasLimit);
                      }
                  
                      /**
                      * @dev Get the AMB interface for the bridge contract address
                      * @return AMB interface for the bridge contract address
                      */
                      function bridgeContract() public view returns (IAMB) {
                          return IAMB(addressStorage[BRIDGE_CONTRACT]);
                      }
                  
                      /**
                      * @dev Tells the mediator contract address from the other network.
                      * @return the address of the mediator contract.
                      */
                      function mediatorContractOnOtherSide() public view returns (address) {
                          return addressStorage[MEDIATOR_CONTRACT];
                      }
                  
                      /**
                      * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network.
                      * @return the gas limit for the message execution.
                      */
                      function requestGasLimit() public view returns (uint256) {
                          return uintStorage[REQUEST_GAS_LIMIT];
                      }
                  
                      /**
                      * @dev Stores a valid AMB bridge contract address.
                      * @param _bridgeContract the address of the bridge contract.
                      */
                      function _setBridgeContract(address _bridgeContract) internal {
                          require(AddressUtils.isContract(_bridgeContract));
                          addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
                      }
                  
                      /**
                      * @dev Stores the mediator contract address from the other network.
                      * @param _mediatorContract the address of the mediator contract.
                      */
                      function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
                          addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
                      }
                  
                      /**
                      * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
                      * @param _requestGasLimit the gas limit for the message execution.
                      */
                      function _setRequestGasLimit(uint256 _requestGasLimit) internal {
                          require(_requestGasLimit <= maxGasPerTx());
                          uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit;
                      }
                  
                      /**
                      * @dev Tells the address that generated the message on the other network that is currently being executed by
                      * the AMB bridge.
                      * @return the address of the message sender.
                      */
                      function messageSender() internal view returns (address) {
                          return bridgeContract().messageSender();
                      }
                  
                      /**
                      * @dev Tells the id of the message originated on the other network.
                      * @return the id of the message originated on the other network.
                      */
                      function messageId() internal view returns (bytes32) {
                          return bridgeContract().messageId();
                      }
                  
                      /**
                      * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
                      * @return the maximum gas limit value.
                      */
                      function maxGasPerTx() internal view returns (uint256) {
                          return bridgeContract().maxGasPerTx();
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract ChooseReceiverHelper {
                      /**
                      * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data.
                      * @param _from address of tokens sender.
                      * @param _data passed data in the transfer message.
                      * @return address of the receiver on the other side.
                      */
                      function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) {
                          recipient = _from;
                          if (_data.length > 0) {
                              require(_data.length == 20);
                              recipient = Bytes.bytesToAddress(_data);
                              require(recipient != address(0));
                              require(recipient != bridgeContractOnOtherSide());
                          }
                      }
                  
                      /* solcov ignore next */
                      function bridgeContractOnOtherSide() internal view returns (address);
                  }
                  
                  // File: contracts/upgradeable_contracts/TransferInfoStorage.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract TransferInfoStorage is EternalStorage {
                      /**
                      * @dev Stores the value of a message sent to the AMB bridge.
                      * @param _messageId of the message sent to the bridge.
                      * @param _value amount of tokens bridged.
                      */
                      function setMessageValue(bytes32 _messageId, uint256 _value) internal {
                          uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
                      }
                  
                      /**
                      * @dev Tells the amount of tokens of a message sent to the AMB bridge.
                      * @return value representing amount of tokens.
                      */
                      function messageValue(bytes32 _messageId) internal view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
                      }
                  
                      /**
                      * @dev Stores the receiver of a message sent to the AMB bridge.
                      * @param _messageId of the message sent to the bridge.
                      * @param _recipient receiver of the tokens bridged.
                      */
                      function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
                          addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
                      }
                  
                      /**
                      * @dev Tells the receiver of a message sent to the AMB bridge.
                      * @return address of the receiver.
                      */
                      function messageRecipient(bytes32 _messageId) internal view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
                      }
                  
                      /**
                      * @dev Sets that the message sent to the AMB bridge has been fixed.
                      * @param _messageId of the message sent to the bridge.
                      */
                      function setMessageFixed(bytes32 _messageId) internal {
                          boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
                      }
                  
                      /**
                      * @dev Tells if a message sent to the AMB bridge has been fixed.
                      * @return bool indicating the status of the message.
                      */
                      function messageFixed(bytes32 _messageId) public view returns (bool) {
                          return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenBridgeMediator.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  /**
                  * @title MultiTokenBridgeMediator
                  * @dev Common mediator functionality to handle operations related to multi-token bridge messages sent to AMB bridge.
                  */
                  contract MultiTokenBridgeMediator is
                      BasicAMBMediator,
                      BasicMultiTokenBridge,
                      TransferInfoStorage,
                      ChooseReceiverHelper
                  {
                      event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value);
                      event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId);
                  
                      /**
                      * @dev Stores the bridged token of a message sent to the AMB bridge.
                      * @param _messageId of the message sent to the bridge.
                      * @param _token bridged token address.
                      */
                      function setMessageToken(bytes32 _messageId, address _token) internal {
                          addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
                      }
                  
                      /**
                      * @dev Tells the bridged token address of a message sent to the AMB bridge.
                      * @return address of a token contract.
                      */
                      function messageToken(bytes32 _messageId) internal view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))];
                      }
                  
                      /**
                      * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
                      * to execute the Mint or Unlock accordingly.
                      * @param _token bridged ERC20/ERC677 token
                      * @param _recipient address that will receive the tokens
                      * @param _value amount of tokens to be received
                      */
                      function _handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) internal {
                          if (withinExecutionLimit(_token, _value)) {
                              addTotalExecutedPerDay(_token, getCurrentDay(), _value);
                              executeActionOnBridgedTokens(_token, _recipient, _value);
                          } else {
                              executeActionOnBridgedTokensOutOfLimit(_token, _recipient, _value);
                          }
                      }
                  
                      /**
                      * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
                      * fix/roll back the transferred assets on the other network.
                      * @param _messageId id of the message which execution failed.
                      */
                      function requestFailedMessageFix(bytes32 _messageId) external {
                          require(!bridgeContract().messageCallStatus(_messageId));
                          require(bridgeContract().failedMessageReceiver(_messageId) == address(this));
                          require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide());
                  
                          bytes4 methodSelector = this.fixFailedMessage.selector;
                          bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
                          bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit());
                      }
                  
                      /**
                      * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
                      * It uses the information stored by passMessage method when the assets were initially transferred
                      * @param _messageId id of the message which execution failed on the other network.
                      */
                      function fixFailedMessage(bytes32 _messageId) public onlyMediator {
                          require(!messageFixed(_messageId));
                  
                          address token = messageToken(_messageId);
                          address recipient = messageRecipient(_messageId);
                          uint256 value = messageValue(_messageId);
                          setMessageFixed(_messageId);
                          executeActionOnFixedTokens(token, recipient, value);
                          emit FailedMessageFixed(_messageId, token, recipient, value);
                      }
                  
                      /**
                      * @dev Execute the action to be performed when the bridge tokens are out of execution limits.
                      */
                      function executeActionOnBridgedTokensOutOfLimit(address, address, uint256) internal {
                          revert();
                      }
                  
                      /* solcov ignore next */
                      function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal;
                  
                      /* solcov ignore next */
                      function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal;
                  }
                  
                  // File: contracts/upgradeable_contracts/Initializable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract Initializable is EternalStorage {
                      bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
                  
                      function setInitialize() internal {
                          boolStorage[INITIALIZED] = true;
                      }
                  
                      function isInitialized() public view returns (bool) {
                          return boolStorage[INITIALIZED];
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/ReentrancyGuard.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract ReentrancyGuard is EternalStorage {
                      bytes32 internal constant LOCK = 0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92; // keccak256(abi.encodePacked("lock"))
                  
                      function lock() internal returns (bool) {
                          return boolStorage[LOCK];
                      }
                  
                      function setLock(bool _lock) internal {
                          boolStorage[LOCK] = _lock;
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/Upgradeable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract Upgradeable {
                      // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
                      modifier onlyIfUpgradeabilityOwner() {
                          require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner());
                          /* solcov ignore next */
                          _;
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/Sacrifice.sol
                  
                  pragma solidity 0.4.24;
                  
                  contract Sacrifice {
                      constructor(address _recipient) public payable {
                          selfdestruct(_recipient);
                      }
                  }
                  
                  // File: contracts/libraries/Address.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  /**
                   * @title Address
                   * @dev Helper methods for Address type.
                   */
                  library Address {
                      /**
                      * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
                      * @param _receiver address that will receive the native tokens
                      * @param _value the amount of native tokens to send
                      */
                      function safeSendValue(address _receiver, uint256 _value) internal {
                          if (!_receiver.send(_value)) {
                              (new Sacrifice).value(_value)(_receiver);
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/Claimable.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  contract Claimable {
                      bytes4 internal constant TRANSFER = 0xa9059cbb; // transfer(address,uint256)
                  
                      modifier validAddress(address _to) {
                          require(_to != address(0));
                          /* solcov ignore next */
                          _;
                      }
                  
                      function claimValues(address _token, address _to) internal {
                          if (_token == address(0)) {
                              claimNativeCoins(_to);
                          } else {
                              claimErc20Tokens(_token, _to);
                          }
                      }
                  
                      function claimNativeCoins(address _to) internal {
                          uint256 value = address(this).balance;
                          Address.safeSendValue(_to, value);
                      }
                  
                      function claimErc20Tokens(address _token, address _to) internal {
                          ERC20Basic token = ERC20Basic(_token);
                          uint256 balance = token.balanceOf(this);
                          safeTransfer(_token, _to, balance);
                      }
                  
                      function safeTransfer(address _token, address _to, uint256 _value) internal {
                          bytes memory returnData;
                          bool returnDataResult;
                          bytes memory callData = abi.encodeWithSelector(TRANSFER, _to, _value);
                          assembly {
                              let result := call(gas, _token, 0x0, add(callData, 0x20), mload(callData), 0, 32)
                              returnData := mload(0)
                              returnDataResult := mload(0)
                  
                              switch result
                                  case 0 {
                                      revert(0, 0)
                                  }
                          }
                  
                          // Return data is optional
                          if (returnData.length > 0) {
                              require(returnDataResult);
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/VersionableBridge.sol
                  
                  pragma solidity 0.4.24;
                  
                  contract VersionableBridge {
                      function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
                          return (5, 1, 0);
                      }
                  
                      /* solcov ignore next */
                      function getBridgeMode() external pure returns (bytes4);
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiAMBErc20ToErc677.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  /**
                  * @title BasicMultiAMBErc20ToErc677
                  * @dev Common functionality for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge.
                  */
                  contract BasicMultiAMBErc20ToErc677 is
                      Initializable,
                      ReentrancyGuard,
                      Upgradeable,
                      Claimable,
                      VersionableBridge,
                      MultiTokenBridgeMediator
                  {
                      /**
                      * @dev Tells the address of the mediator contract on the other side, used by chooseReceiver method
                      * to avoid sending the native tokens to that address.
                      * @return address of the mediator contract con the other side
                      */
                      function bridgeContractOnOtherSide() internal view returns (address) {
                          return mediatorContractOnOtherSide();
                      }
                  
                      /**
                      * @dev Initiate the bridge operation for some amount of tokens from msg.sender.
                      * The user should first call Approve method of the ERC677 token.
                      * @param token bridged token contract address.
                      * @param _receiver address that will receive the native tokens on the other network.
                      * @param _value amount of tokens to be transferred to the other network.
                      */
                      function relayTokens(ERC677 token, address _receiver, uint256 _value) external {
                          _relayTokens(token, _receiver, _value);
                      }
                  
                      /**
                      * @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side.
                      * The user should first call Approve method of the ERC677 token.
                      * @param token bridged token contract address.
                      * @param _value amount of tokens to be transferred to the other network.
                      */
                      function relayTokens(ERC677 token, uint256 _value) external {
                          _relayTokens(token, msg.sender, _value);
                      }
                  
                      /**
                      * @dev Tells the bridge interface version that this contract supports.
                      * @return major value of the version
                      * @return minor value of the version
                      * @return patch value of the version
                      */
                      function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
                          return (1, 1, 1);
                      }
                  
                      /**
                      * @dev Tells the bridge mode that this contract supports.
                      * @return _data 4 bytes representing the bridge mode
                      */
                      function getBridgeMode() external pure returns (bytes4 _data) {
                          return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb")))
                      }
                  
                      /**
                      * @dev Claims stucked tokens. Only unsupported tokens can be claimed.
                      * When dealing with already supported tokens, fixMediatorBalance can be used instead.
                      * @param _token address of claimed token, address(0) for native
                      * @param _to address of tokens receiver
                      */
                      function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner validAddress(_to) {
                          require(_token == address(0) || !isTokenRegistered(_token)); // native coins or token not registered
                          claimValues(_token, _to);
                      }
                  
                      /* solcov ignore next */
                      function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool);
                  
                      /* solcov ignore next */
                      function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal;
                  
                      /* solcov ignore next */
                      function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal;
                  }
                  
                  // File: contracts/upgradeability/Proxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title Proxy
                   * @dev Gives the possibility to delegate any call to a foreign implementation.
                   */
                  contract Proxy {
                      /**
                      * @dev Tells the address of the implementation where every call will be delegated.
                      * @return address of the implementation to which it will be delegated
                      */
                      /* solcov ignore next */
                      function implementation() public view returns (address);
                  
                      /**
                      * @dev Fallback function allowing to perform a delegatecall to the given implementation.
                      * This function will return whatever the implementation call returns
                      */
                      function() public payable {
                          // solhint-disable-previous-line no-complex-fallback
                          address _impl = implementation();
                          require(_impl != address(0));
                          assembly {
                              /*
                                  0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
                                  loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
                                  memory. It's needed because we're going to write the return data of delegatecall to the
                                  free memory slot.
                              */
                              let ptr := mload(0x40)
                              /*
                                  `calldatacopy` is copy calldatasize bytes from calldata
                                  First argument is the destination to which data is copied(ptr)
                                  Second argument specifies the start position of the copied data.
                                      Since calldata is sort of its own unique location in memory,
                                      0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
                                      That's always going to be the zeroth byte of the function selector.
                                  Third argument, calldatasize, specifies how much data will be copied.
                                      calldata is naturally calldatasize bytes long (same thing as msg.data.length)
                              */
                              calldatacopy(ptr, 0, calldatasize)
                              /*
                                  delegatecall params explained:
                                  gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
                                      us the amount of gas still available to execution
                  
                                  _impl: address of the contract to delegate to
                  
                                  ptr: to pass copied data
                  
                                  calldatasize: loads the size of `bytes memory data`, same as msg.data.length
                  
                                  0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
                                          these are set to 0, 0 so the output data will not be written to memory. The output
                                          data will be read using `returndatasize` and `returdatacopy` instead.
                  
                                  result: This will be 0 if the call fails and 1 if it succeeds
                              */
                              let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
                              /*
                  
                              */
                              /*
                                  ptr current points to the value stored at 0x40,
                                  because we assigned it like ptr := mload(0x40).
                                  Because we use 0x40 as a free memory pointer,
                                  we want to make sure that the next time we want to allocate memory,
                                  we aren't overwriting anything important.
                                  So, by adding ptr and returndatasize,
                                  we get a memory location beyond the end of the data we will be copying to ptr.
                                  We place this in at 0x40, and any reads from 0x40 will now read from free memory
                              */
                              mstore(0x40, add(ptr, returndatasize))
                              /*
                                  `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
                                      slot it will copy to, 0 means copy from the beginning of the return data, and size is
                                      the amount of data to copy.
                                  `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
                              */
                              returndatacopy(ptr, 0, returndatasize)
                  
                              /*
                                  if `result` is 0, revert.
                                  if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
                                  copied to `ptr` from the delegatecall return data
                              */
                              switch result
                                  case 0 {
                                      revert(ptr, returndatasize)
                                  }
                                  default {
                                      return(ptr, returndatasize)
                                  }
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/TokenProxy.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  interface IPermittableTokenVersion {
                      function version() external pure returns (string);
                  }
                  
                  /**
                  * @title TokenProxy
                  * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract.
                  */
                  contract TokenProxy is Proxy {
                      // storage layout is copied from PermittableToken.sol
                      string internal name;
                      string internal symbol;
                      uint8 internal decimals;
                      mapping(address => uint256) internal balances;
                      uint256 internal totalSupply;
                      mapping(address => mapping(address => uint256)) internal allowed;
                      address internal owner;
                      bool internal mintingFinished;
                      address internal bridgeContractAddr;
                      // string public constant version = "1";
                      bytes32 internal DOMAIN_SEPARATOR;
                      // bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
                      mapping(address => uint256) internal nonces;
                      mapping(address => mapping(address => uint256)) internal expirations;
                  
                      /**
                      * @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage.
                      * @param _tokenImage address of the token image used for mirroring all functions.
                      * @param _name token name.
                      * @param _symbol token symbol.
                      * @param _decimals token decimals.
                      * @param _chainId chain id for current network.
                      */
                      constructor(address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId)
                          public
                      {
                          string memory version = IPermittableTokenVersion(_tokenImage).version();
                  
                          assembly {
                              // EIP 1967
                              // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
                              sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage)
                          }
                          name = _name;
                          symbol = _symbol;
                          decimals = _decimals;
                          owner = msg.sender; // msg.sender == HomeMultiAMBErc20ToErc677 mediator
                          bridgeContractAddr = msg.sender;
                          DOMAIN_SEPARATOR = keccak256(
                              abi.encode(
                                  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                  keccak256(bytes(_name)),
                                  keccak256(bytes(version)),
                                  _chainId,
                                  address(this)
                              )
                          );
                      }
                  
                      /**
                      * @dev Retrieves the implementation contract address, mirrored token image.
                      * @return token image address.
                      */
                      function implementation() public view returns (address impl) {
                          assembly {
                              impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/BaseRewardAddressList.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                  * @title BaseRewardAddressList
                  * @dev Implements the logic to store, add and remove reward account addresses. Works as a linked list.
                  */
                  contract BaseRewardAddressList is EternalStorage {
                      using SafeMath for uint256;
                  
                      address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
                      uint256 internal constant MAX_REWARD_ADDRESSES = 50;
                      bytes32 internal constant REWARD_ADDRESS_COUNT = 0xabc77c82721ced73eef2645facebe8c30249e6ac372cce6eb9d1fed31bd6648f; // keccak256(abi.encodePacked("rewardAddressCount"))
                  
                      event RewardAddressAdded(address indexed addr);
                      event RewardAddressRemoved(address indexed addr);
                  
                      /**
                      * @dev Retrieves all registered reward accounts.
                      * @return address list of the registered reward receivers.
                      */
                      function rewardAddressList() external view returns (address[]) {
                          address[] memory list = new address[](rewardAddressCount());
                          uint256 counter = 0;
                          address nextAddr = getNextRewardAddress(F_ADDR);
                  
                          while (nextAddr != F_ADDR) {
                              require(nextAddr != address(0));
                  
                              list[counter] = nextAddr;
                              nextAddr = getNextRewardAddress(nextAddr);
                              counter++;
                          }
                  
                          return list;
                      }
                  
                      /**
                      * @dev Retrieves amount of registered reward accounts.
                      * @return length of reward addresses list.
                      */
                      function rewardAddressCount() public view returns (uint256) {
                          return uintStorage[REWARD_ADDRESS_COUNT];
                      }
                  
                      /**
                      * @dev Checks if specified address is included into the registered rewards receivers list.
                      * @param _addr address to verify.
                      * @return true, if specified address is associated with one of the registered reward accounts.
                      */
                      function isRewardAddress(address _addr) public view returns (bool) {
                          return _addr != F_ADDR && getNextRewardAddress(_addr) != address(0);
                      }
                  
                      /**
                      * @dev Retrieves next reward address in the linked list, or F_ADDR if given address is the last one.
                      * @param _address address of some reward account.
                      * @return address of the next reward receiver.
                      */
                      function getNextRewardAddress(address _address) public view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("rewardAddressList", _address))];
                      }
                  
                      /**
                      * @dev Internal function for adding a new reward address to the linked list.
                      * @param _addr new reward account.
                      */
                      function _addRewardAddress(address _addr) internal {
                          require(_addr != address(0) && _addr != F_ADDR);
                          require(!isRewardAddress(_addr));
                  
                          address nextAddr = getNextRewardAddress(F_ADDR);
                  
                          require(nextAddr != address(0));
                  
                          _setNextRewardAddress(_addr, nextAddr);
                          _setNextRewardAddress(F_ADDR, _addr);
                          _setRewardAddressCount(rewardAddressCount().add(1));
                      }
                  
                      /**
                      * @dev Internal function for removing existing reward address from the linked list.
                      * @param _addr old reward account which should be removed.
                      */
                      function _removeRewardAddress(address _addr) internal {
                          require(isRewardAddress(_addr));
                          address nextAddr = getNextRewardAddress(_addr);
                          address index = F_ADDR;
                          address next = getNextRewardAddress(index);
                  
                          while (next != _addr) {
                              require(next != address(0));
                              index = next;
                              next = getNextRewardAddress(index);
                              require(next != F_ADDR);
                          }
                  
                          _setNextRewardAddress(index, nextAddr);
                          delete addressStorage[keccak256(abi.encodePacked("rewardAddressList", _addr))];
                          _setRewardAddressCount(rewardAddressCount().sub(1));
                      }
                  
                      /**
                      * @dev Internal function for initializing linked list with the array of the initial reward addresses.
                      * @param _rewardAddresses initial reward addresses list, should be non-empty.
                      */
                      function _setRewardAddressList(address[] _rewardAddresses) internal {
                          require(_rewardAddresses.length > 0);
                  
                          _setNextRewardAddress(F_ADDR, _rewardAddresses[0]);
                  
                          for (uint256 i = 0; i < _rewardAddresses.length; i++) {
                              require(_rewardAddresses[i] != address(0) && _rewardAddresses[i] != F_ADDR);
                              require(!isRewardAddress(_rewardAddresses[i]));
                  
                              if (i == _rewardAddresses.length - 1) {
                                  _setNextRewardAddress(_rewardAddresses[i], F_ADDR);
                              } else {
                                  _setNextRewardAddress(_rewardAddresses[i], _rewardAddresses[i + 1]);
                              }
                  
                              emit RewardAddressAdded(_rewardAddresses[i]);
                          }
                  
                          _setRewardAddressCount(_rewardAddresses.length);
                      }
                  
                      /**
                      * @dev Internal function for updating the length of the reward accounts list.
                      * @param _rewardAddressCount new linked list length.
                      */
                      function _setRewardAddressCount(uint256 _rewardAddressCount) internal {
                          require(_rewardAddressCount <= MAX_REWARD_ADDRESSES);
                          uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount;
                      }
                  
                      /**
                      * @dev Internal function for updating the pointer to the next reward receiver.
                      * @param _prevAddr address of some reward receiver.
                      * @param _addr address of the next receiver to which _prevAddr should point to.
                      */
                      function _setNextRewardAddress(address _prevAddr, address _addr) internal {
                          addressStorage[keccak256(abi.encodePacked("rewardAddressList", _prevAddr))] = _addr;
                      }
                  }
                  
                  // File: contracts/interfaces/IBurnableMintableERC677Token.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  contract IBurnableMintableERC677Token is ERC677 {
                      function mint(address _to, uint256 _amount) public returns (bool);
                      function burn(uint256 _value) public;
                      function claimTokens(address _token, address _to) public;
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeFeeManagerMultiAMBErc20ToErc677.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  /**
                  * @title HomeFeeManagerMultiAMBErc20ToErc677
                  * @dev Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations.
                  * The fees are distributed in the form of native tokens to the list of reward accounts.
                  */
                  contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge {
                      using SafeMath for uint256;
                  
                      event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee);
                      event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId);
                  
                      // This is not a real fee value but a relative value used to calculate the fee percentage
                      uint256 internal constant MAX_FEE = 1 ether;
                      bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee"))
                      bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee"))
                  
                      /**
                      * @dev Throws if given fee percentage is >= 100%.
                      */
                      modifier validFee(uint256 _fee) {
                          require(_fee < MAX_FEE);
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Throws if given fee type is unknown.
                      */
                      modifier validFeeType(bytes32 _feeType) {
                          require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE);
                          /* solcov ignore next */
                          _;
                      }
                  
                      /**
                      * @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations.
                      * Only the owner can call this method.
                      * @param _addr new reward account.
                      */
                      function addRewardAddress(address _addr) external onlyOwner {
                          _addRewardAddress(_addr);
                      }
                  
                      /**
                      * @dev Removes a reward address from the rewards list.
                      * Only the owner can call this method.
                      * @param _addr old reward account, that should be removed.
                      */
                      function removeRewardAddress(address _addr) external onlyOwner {
                          _removeRewardAddress(_addr);
                      }
                  
                      /**
                      * @dev Updates the value for the particular fee type.
                      * Only the owner can call this method.
                      * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
                      * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
                      * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
                      */
                      function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner {
                          _setFee(_feeType, _token, _fee);
                      }
                  
                      /**
                      * @dev Retrieves the value for the particular fee type.
                      * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
                      * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
                      * @return fee value associated with the requested fee type.
                      */
                      function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked(_feeType, _token))];
                      }
                  
                      /**
                      * @dev Calculates the amount of fee to pay for the value of the particular fee type.
                      * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
                      * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
                      * @param _value bridged value, for which fee should be evaluated.
                      * @return amount of fee to be subtracted from the transferred value.
                      */
                      function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) {
                          uint256 _fee = getFee(_feeType, _token);
                          return _value.mul(_fee).div(MAX_FEE);
                      }
                  
                      /**
                      * @dev Internal function for updating the fee value for the given fee type.
                      * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
                      * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
                      * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
                      */
                      function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) {
                          require(isTokenRegistered(_token));
                          uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee;
                          emit FeeUpdated(_feeType, _token, _fee);
                      }
                  
                      /**
                      * @dev Calculates a random number based on the block number.
                      * @param _count the max value for the random number.
                      * @return a number between 0 and _count.
                      */
                      function random(uint256 _count) internal view returns (uint256) {
                          return uint256(blockhash(block.number.sub(1))) % _count;
                      }
                  
                      /**
                      * @dev Calculates and distributes the amount of fee proportionally between registered reward addresses.
                      * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
                      * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
                      * @param _value bridged value, for which fee should be evaluated.
                      * @return total amount of fee subtracted from the transferred value and distributed between the reward accounts.
                      */
                      function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) {
                          uint256 numOfAccounts = rewardAddressCount();
                          uint256 _fee = calculateFee(_feeType, _token, _value);
                          if (numOfAccounts == 0 || _fee == 0) {
                              return 0;
                          }
                          uint256 feePerAccount = _fee.div(numOfAccounts);
                          uint256 randomAccountIndex;
                          uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts));
                          if (diff > 0) {
                              randomAccountIndex = random(numOfAccounts);
                          }
                  
                          address nextAddr = getNextRewardAddress(F_ADDR);
                          require(nextAddr != F_ADDR && nextAddr != address(0));
                  
                          uint256 i = 0;
                          while (nextAddr != F_ADDR) {
                              uint256 feeToDistribute = feePerAccount;
                              if (diff > 0 && randomAccountIndex == i) {
                                  feeToDistribute = feeToDistribute.add(diff);
                              }
                  
                              if (_feeType == HOME_TO_FOREIGN_FEE) {
                                  ERC677(_token).transfer(nextAddr, feeToDistribute);
                              } else {
                                  IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute);
                              }
                  
                              nextAddr = getNextRewardAddress(nextAddr);
                              require(nextAddr != address(0));
                              i = i + 1;
                          }
                          return _fee;
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeMultiAMBErc20ToErc677.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  /**
                  * @title HomeMultiAMBErc20ToErc677
                  * @dev Home side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge.
                  * It is designed to be used as an implementation contract of EternalStorageProxy contract.
                  */
                  contract HomeMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677, HomeFeeManagerMultiAMBErc20ToErc677 {
                      bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract"))
                  
                      event NewTokenRegistered(address indexed foreignToken, address indexed homeToken);
                  
                      /**
                      * @dev Stores the initial parameters of the mediator.
                      * @param _bridgeContract the address of the AMB bridge contract.
                      * @param _mediatorContract the address of the mediator contract on the other network.
                      * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
                      *   [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
                      * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
                      *   [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
                      * @param _requestGasLimit the gas limit for the message execution.
                      * @param _owner address of the owner of the mediator contract.
                      * @param _tokenImage address of the PermittableToken contract that will be used for deploying of new tokens.
                      * @param _rewardAddreses list of reward addresses, between whom fees will be distributed.
                      * @param _fees array with initial fees for both bridge firections.
                      *   [ 0 = homeToForeignFee, 1 = foreignToHomeFee ]
                      */
                      function initialize(
                          address _bridgeContract,
                          address _mediatorContract,
                          uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
                          uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
                          uint256 _requestGasLimit,
                          address _owner,
                          address _tokenImage,
                          address[] _rewardAddreses,
                          uint256[2] _fees // [ 0 = homeToForeignFee, 1 = foreignToHomeFee ]
                      ) external onlyRelevantSender returns (bool) {
                          require(!isInitialized());
                          require(_owner != address(0));
                  
                          _setBridgeContract(_bridgeContract);
                          _setMediatorContractOnOtherSide(_mediatorContract);
                          _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
                          _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
                          _setRequestGasLimit(_requestGasLimit);
                          setOwner(_owner);
                          _setTokenImage(_tokenImage);
                          if (_rewardAddreses.length > 0) {
                              _setRewardAddressList(_rewardAddreses);
                          }
                          _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]);
                          _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]);
                  
                          setInitialize();
                  
                          return isInitialized();
                      }
                  
                      /**
                      * @dev Updates an address of the token image contract used for proxifying newly created tokens.
                      * @param _tokenImage address of PermittableToken contract.
                      */
                      function setTokenImage(address _tokenImage) external onlyOwner {
                          _setTokenImage(_tokenImage);
                      }
                  
                      /**
                      * @dev Retrieves address of the token image contract.
                      * @return address of block reward contract.
                      */
                      function tokenImage() public view returns (address) {
                          return addressStorage[TOKEN_IMAGE_CONTRACT];
                      }
                  
                      /**
                      * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
                      * Checks that the value is inside the execution limits and invokes the method
                      * to execute the Mint or Unlock accordingly.
                      * @param _token address of the bridged ERC20/ERC677 token on the foreign side.
                      * @param _name name of the bridged token, "x" will be appended, if empty, symbol will be used instead.
                      * @param _symbol symbol of the bridged token, "x" will be appended, if empty, name will be used instead.
                      * @param _decimals decimals of the bridge foreign token.
                      * @param _recipient address that will receive the tokens.
                      * @param _value amount of tokens to be received.
                      */
                      function deployAndHandleBridgedTokens(
                          address _token,
                          string _name,
                          string _symbol,
                          uint8 _decimals,
                          address _recipient,
                          uint256 _value
                      ) external onlyMediator {
                          string memory name = _name;
                          string memory symbol = _symbol;
                          if (bytes(name).length == 0) {
                              name = symbol;
                          } else if (bytes(symbol).length == 0) {
                              symbol = name;
                          }
                          name = string(abi.encodePacked(name, " on Fuse"));
                          address homeToken = new TokenProxy(tokenImage(), name, symbol, _decimals, bridgeContract().sourceChainId());
                          _setTokenAddressPair(_token, homeToken);
                          _initializeTokenBridgeLimits(homeToken, _decimals);
                          _setFee(HOME_TO_FOREIGN_FEE, homeToken, getFee(HOME_TO_FOREIGN_FEE, address(0)));
                          _setFee(FOREIGN_TO_HOME_FEE, homeToken, getFee(FOREIGN_TO_HOME_FEE, address(0)));
                          _handleBridgedTokens(ERC677(homeToken), _recipient, _value);
                  
                          emit NewTokenRegistered(_token, homeToken);
                      }
                  
                      /**
                      * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
                      * to execute the Mint or Unlock accordingly.
                      * @param _token bridged ERC20 token.
                      * @param _recipient address that will receive the tokens.
                      * @param _value amount of tokens to be received.
                      */
                      function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator {
                          ERC677 homeToken = ERC677(homeTokenAddress(_token));
                          require(isTokenRegistered(homeToken));
                          _handleBridgedTokens(homeToken, _recipient, _value);
                      }
                  
                      /**
                      * @dev ERC677 transfer callback function.
                      * @param _from address of tokens sender.
                      * @param _value amount of transferred tokens.
                      * @param _data additional transfer data, can be used for passing alternative receiver address.
                      */
                      function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) {
                          // if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing
                          if (!lock()) {
                              ERC677 token = ERC677(msg.sender);
                              // if msg.sender if not a valid token contract, this check will fail, since limits are zeros
                              // so the following check is not needed
                              // require(isTokenRegistered(token));
                              require(withinLimit(token, _value));
                              addTotalSpentPerDay(token, getCurrentDay(), _value);
                              bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data);
                          }
                          return true;
                      }
                  
                      /**
                      * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
                      * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
                      * The user should first call Approve method of the ERC677 token.
                      * @param token bridge token contract address.
                      * @param _receiver address that will receive the native tokens on the other network.
                      * @param _value amount of tokens to be transferred to the other network.
                      */
                      function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal {
                          // This lock is to prevent calling passMessage twice if a ERC677 token is used.
                          // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
                          // which will call passMessage.
                          require(!lock());
                          address to = address(this);
                          // if msg.sender if not a valid token contract, this check will fail, since limits are zeros
                          // so the following check is not needed
                          // require(isTokenRegistered(token));
                          require(withinLimit(token, _value));
                          addTotalSpentPerDay(token, getCurrentDay(), _value);
                  
                          setLock(true);
                          token.transferFrom(msg.sender, to, _value);
                          setLock(false);
                          bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver));
                      }
                  
                      /**
                       * @dev Executes action on the request to deposit tokens relayed from the other network
                       * @param _recipient address of tokens receiver
                       * @param _value amount of bridged tokens
                       */
                      function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal {
                          bytes32 _messageId = messageId();
                          uint256 valueToMint = _value;
                          uint256 fee = _distributeFee(FOREIGN_TO_HOME_FEE, _token, valueToMint);
                          if (fee > 0) {
                              emit FeeDistributed(fee, _token, _messageId);
                              valueToMint = valueToMint.sub(fee);
                          }
                          IBurnableMintableERC677Token(_token).mint(_recipient, valueToMint);
                          emit TokensBridged(_token, _recipient, valueToMint, _messageId);
                      }
                  
                      /**
                      * @dev Mints back the amount of tokens that were bridged to the other network but failed.
                      * @param _token address that bridged token contract.
                      * @param _recipient address that will receive the tokens.
                      * @param _value amount of tokens to be received.
                      */
                      function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
                          IBurnableMintableERC677Token(_token).mint(_recipient, _value);
                      }
                  
                      /**
                      * @dev Retrieves address of the home bridged token contract associated with a specific foreign token contract.
                      * @param _foreignToken address of the created home token contract.
                      * @return address of the home token contract.
                      */
                      function homeTokenAddress(address _foreignToken) public view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))];
                      }
                  
                      /**
                      * @dev Retrieves address of the foreign bridged token contract associated with a specific home token contract.
                      * @param _homeToken address of the created home token contract.
                      * @return address of the foreign token contract.
                      */
                      function foreignTokenAddress(address _homeToken) public view returns (address) {
                          return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))];
                      }
                  
                      /**
                      * @dev Internal function for updating an address of the token image contract.
                      * @param _foreignToken address of bridged foreign token contract.
                      * @param _foreignToken address of created home token contract.
                      */
                      function _setTokenAddressPair(address _foreignToken, address _homeToken) internal {
                          addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))] = _homeToken;
                          addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))] = _foreignToken;
                      }
                  
                      /**
                      * @dev Internal function for updating an address of the token image contract.
                      * @param _tokenImage address of deployed PermittableToken contract.
                      */
                      function _setTokenImage(address _tokenImage) internal {
                          require(AddressUtils.isContract(_tokenImage));
                          addressStorage[TOKEN_IMAGE_CONTRACT] = _tokenImage;
                      }
                  
                      /**
                       * @dev Executes action on withdrawal of bridged tokens
                       * @param _token address of token contract
                       * @param _from address of tokens sender
                       * @param _value requsted amount of bridged tokens
                       * @param _data alternative receiver, if specified
                       */
                      function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal {
                          if (!lock()) {
                              bytes32 _messageId = messageId();
                              uint256 valueToBridge = _value;
                              uint256 fee = _distributeFee(HOME_TO_FOREIGN_FEE, _token, valueToBridge);
                              if (fee > 0) {
                                  emit FeeDistributed(fee, _token, _messageId);
                                  valueToBridge = valueToBridge.sub(fee);
                              }
                              IBurnableMintableERC677Token(_token).burn(valueToBridge);
                              passMessage(_token, _from, chooseReceiver(_from, _data), valueToBridge);
                          }
                      }
                  
                      /**
                      * @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network.
                      * Store information related to the bridged tokens in case the message execution fails on the other network
                      * and the action needs to be fixed/rolled back.
                      * @param _token bridged ERC20 token
                      * @param _from address of sender, if bridge operation fails, tokens will be returned to this address
                      * @param _receiver address of receiver on the other side, will eventually receive bridged tokens
                      * @param _value bridged amount of tokens
                      */
                      function passMessage(ERC677 _token, address _from, address _receiver, uint256 _value) internal {
                          bytes4 methodSelector = this.handleBridgedTokens.selector;
                          address foreignToken = foreignTokenAddress(_token);
                          bytes memory data = abi.encodeWithSelector(methodSelector, foreignToken, _receiver, _value);
                  
                          bytes32 _messageId = bridgeContract().requireToPassMessage(
                              mediatorContractOnOtherSide(),
                              data,
                              requestGasLimit()
                          );
                  
                          setMessageToken(_messageId, _token);
                          setMessageValue(_messageId, _value);
                          setMessageRecipient(_messageId, _from);
                      }
                  }
                  
                  // File: contracts/libraries/TokenReader.sol
                  
                  pragma solidity 0.4.24;
                  
                  /**
                   * @title TokenReader
                   * @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts.
                   */
                  library TokenReader {
                      /**
                      * @dev Reads the name property of the provided token.
                      * Either name() or NAME() method is used.
                      * Both, string and bytes32 types are supported.
                      * @param _token address of the token contract.
                      * @return token name as a string or an empty string if none of the methods succeeded.
                      */
                      function readName(address _token) internal view returns (string) {
                          uint256 ptr;
                          uint256 size;
                          assembly {
                              ptr := mload(0x40)
                              mstore(ptr, 0x06fdde0300000000000000000000000000000000000000000000000000000000) // name()
                              if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
                                  mstore(ptr, 0xa3f4df7e00000000000000000000000000000000000000000000000000000000) // NAME()
                                  staticcall(gas, _token, ptr, 4, ptr, 32)
                                  pop
                              }
                  
                              mstore(0x40, add(ptr, returndatasize))
                  
                              switch gt(returndatasize, 32)
                                  case 1 {
                                      returndatacopy(mload(0x40), 32, 32) // string length
                                      size := mload(mload(0x40))
                                  }
                                  default {
                                      size := returndatasize // 32 or 0
                                  }
                          }
                          string memory res = new string(size);
                          assembly {
                              if gt(returndatasize, 32) {
                                  // load as string
                                  returndatacopy(add(res, 32), 64, size)
                                  jump(exit)
                              }
                              /* solhint-disable */
                              if gt(returndatasize, 0) {
                                  let i := 0
                                  ptr := mload(ptr) // load bytes32 value
                                  mstore(add(res, 32), ptr) // save value in result string
                  
                                  for { } gt(ptr, 0) { i := add(i, 1) } { // until string is empty
                                      ptr := shl(8, ptr) // shift left by one symbol
                                  }
                                  mstore(res, i) // save result string length
                              }
                              exit:
                              /* solhint-enable */
                          }
                          return res;
                      }
                  
                      /**
                      * @dev Reads the symbol property of the provided token.
                      * Either symbol() or SYMBOL() method is used.
                      * Both, string and bytes32 types are supported.
                      * @param _token address of the token contract.
                      * @return token symbol as a string or an empty string if none of the methods succeeded.
                      */
                      function readSymbol(address _token) internal view returns (string) {
                          uint256 ptr;
                          uint256 size;
                          assembly {
                              ptr := mload(0x40)
                              mstore(ptr, 0x95d89b4100000000000000000000000000000000000000000000000000000000) // symbol()
                              if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
                                  mstore(ptr, 0xf76f8d7800000000000000000000000000000000000000000000000000000000) // SYMBOl()
                                  staticcall(gas, _token, ptr, 4, ptr, 32)
                                  pop
                              }
                  
                              mstore(0x40, add(ptr, returndatasize))
                  
                              switch gt(returndatasize, 32)
                                  case 1 {
                                      returndatacopy(mload(0x40), 32, 32) // string length
                                      size := mload(mload(0x40))
                                  }
                                  default {
                                      size := returndatasize // 32 or 0
                                  }
                          }
                          string memory res = new string(size);
                          assembly {
                              if gt(returndatasize, 32) {
                                  // load as string
                                  returndatacopy(add(res, 32), 64, size)
                                  jump(exit)
                              }
                              /* solhint-disable */
                              if gt(returndatasize, 0) {
                                  let i := 0
                                  ptr := mload(ptr) // load bytes32 value
                                  mstore(add(res, 32), ptr) // save value in result string
                  
                                  for { } gt(ptr, 0) { i := add(i, 1) } { // until string is empty
                                      ptr := shl(8, ptr) // shift left by one symbol
                                  }
                                  mstore(res, i) // save result string length
                              }
                              exit:
                              /* solhint-enable */
                          }
                          return res;
                      }
                  
                      /**
                      * @dev Reads the decimals property of the provided token.
                      * Either decimals() or DECIMALS() method is used.
                      * @param _token address of the token contract.
                      * @return token decimals or 0 if none of the methods succeeded.
                      */
                      function readDecimals(address _token) internal view returns (uint256) {
                          uint256 decimals;
                          assembly {
                              let ptr := mload(0x40)
                              mstore(0x40, add(ptr, 32))
                              mstore(ptr, 0x313ce56700000000000000000000000000000000000000000000000000000000) // decimals()
                              if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
                                  mstore(ptr, 0x2e0f262500000000000000000000000000000000000000000000000000000000) // DECIMALS()
                                  if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
                                      mstore(ptr, 0)
                                  }
                              }
                              decimals := mload(ptr)
                          }
                          return decimals;
                      }
                  }
                  
                  // File: contracts/libraries/SafeERC20.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  /**
                   * @title SafeERC20
                   * @dev Helper methods for safe token transfers.
                   * Functions perform additional checks to be sure that token transfer really happened.
                   */
                  library SafeERC20 {
                      using SafeMath for uint256;
                  
                      /**
                      * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks.
                      * @param _token address of the token contract
                      * @param _to address of the receiver
                      * @param _value amount of tokens to send
                      */
                      function safeTransfer(address _token, address _to, uint256 _value) internal {
                          LegacyERC20(_token).transfer(_to, _value);
                          assembly {
                              if returndatasize {
                                  returndatacopy(0, 0, 32)
                                  if iszero(mload(0)) {
                                      revert(0, 0)
                                  }
                              }
                          }
                      }
                  
                      /**
                      * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks.
                      * @param _token address of the token contract
                      * @param _from address of the sender
                      * @param _value amount of tokens to send
                      */
                      function safeTransferFrom(address _token, address _from, uint256 _value) internal {
                          LegacyERC20(_token).transferFrom(_from, address(this), _value);
                          assembly {
                              if returndatasize {
                                  returndatacopy(0, 0, 32)
                                  if iszero(mload(0)) {
                                      revert(0, 0)
                                  }
                              }
                          }
                      }
                  }
                  
                  // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/ForeignMultiAMBErc20ToErc677.sol
                  
                  pragma solidity 0.4.24;
                  
                  
                  
                  
                  
                  
                  /**
                   * @title ForeignMultiAMBErc20ToErc677
                   * @dev Foreign side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge.
                   * It is designed to be used as an implementation contract of EternalStorageProxy contract.
                   */
                  contract ForeignMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677 {
                      using SafeERC20 for address;
                      using SafeERC20 for ERC677;
                  
                      /**
                      * @dev Stores the initial parameters of the mediator.
                      * @param _bridgeContract the address of the AMB bridge contract.
                      * @param _mediatorContract the address of the mediator contract on the other network.
                      * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
                      *   [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
                      * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
                      *   [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
                      * @param _requestGasLimit the gas limit for the message execution.
                      * @param _owner address of the owner of the mediator contract.
                      */
                      function initialize(
                          address _bridgeContract,
                          address _mediatorContract,
                          uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
                          uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
                          uint256 _requestGasLimit,
                          address _owner
                      ) external onlyRelevantSender returns (bool) {
                          require(!isInitialized());
                          require(_owner != address(0));
                  
                          _setBridgeContract(_bridgeContract);
                          _setMediatorContractOnOtherSide(_mediatorContract);
                          _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
                          _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
                          _setRequestGasLimit(_requestGasLimit);
                          setOwner(_owner);
                  
                          setInitialize();
                  
                          return isInitialized();
                      }
                  
                      /**
                       * @dev Executes action on the request to withdraw tokens relayed from the other network
                       * @param _token address of the token contract
                       * @param _recipient address of tokens receiver
                       * @param _value amount of bridged tokens
                       */
                      function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal {
                          bytes32 _messageId = messageId();
                          _token.safeTransfer(_recipient, _value);
                          _setMediatorBalance(_token, mediatorBalance(_token).sub(_value));
                          emit TokensBridged(_token, _recipient, _value, _messageId);
                      }
                  
                      /**
                      * @dev ERC677 transfer callback function.
                      * @param _from address of tokens sender.
                      * @param _value amount of transferred tokens.
                      * @param _data additional transfer data, can be used for passing alternative receiver address.
                      */
                      function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) {
                          if (!lock()) {
                              ERC677 token = ERC677(msg.sender);
                              bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data);
                          }
                          return true;
                      }
                  
                      /**
                      * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
                      * to execute the Mint or Unlock accordingly.
                      * @param _token bridged ERC20 token.
                      * @param _recipient address that will receive the tokens.
                      * @param _value amount of tokens to be received.
                      */
                      function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator {
                          require(isTokenRegistered(_token));
                          _handleBridgedTokens(_token, _recipient, _value);
                      }
                  
                      /**
                      * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
                      * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
                      * The user should first call Approve method of the ERC677 token.
                      * @param token bridge token contract address.
                      * @param _receiver address that will receive the native tokens on the other network.
                      * @param _value amount of tokens to be transferred to the other network.
                      */
                      function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal {
                          // This lock is to prevent calling passMessage twice if a ERC677 token is used.
                          // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
                          // which will call passMessage.
                          require(!lock());
                  
                          setLock(true);
                          token.safeTransferFrom(msg.sender, _value);
                          setLock(false);
                          bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver));
                      }
                  
                      /**
                       * @dev Executes action on deposit of bridged tokens
                       * @param _token address of the token contract
                       * @param _from address of tokens sender
                       * @param _value requsted amount of bridged tokens
                       * @param _data alternative receiver, if specified
                       */
                      function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal {
                          if (lock()) return;
                  
                          bool isKnownToken = isTokenRegistered(_token);
                          if (!isKnownToken) {
                              string memory name = TokenReader.readName(_token);
                              string memory symbol = TokenReader.readSymbol(_token);
                              uint8 decimals = uint8(TokenReader.readDecimals(_token));
                  
                              require(bytes(name).length > 0 || bytes(symbol).length > 0);
                  
                              _initializeTokenBridgeLimits(_token, decimals);
                          }
                  
                          require(withinLimit(_token, _value));
                          addTotalSpentPerDay(_token, getCurrentDay(), _value);
                  
                          bytes memory data;
                          address receiver = chooseReceiver(_from, _data);
                  
                          if (isKnownToken) {
                              data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, receiver, _value);
                          } else {
                              data = abi.encodeWithSelector(
                                  HomeMultiAMBErc20ToErc677(this).deployAndHandleBridgedTokens.selector,
                                  _token,
                                  name,
                                  symbol,
                                  decimals,
                                  receiver,
                                  _value
                              );
                          }
                  
                          _setMediatorBalance(_token, mediatorBalance(_token).add(_value));
                  
                          bytes32 _messageId = bridgeContract().requireToPassMessage(
                              mediatorContractOnOtherSide(),
                              data,
                              requestGasLimit()
                          );
                  
                          setMessageToken(_messageId, _token);
                          setMessageValue(_messageId, _value);
                          setMessageRecipient(_messageId, _from);
                  
                          if (!isKnownToken) {
                              _setTokenRegistrationMessageId(_token, _messageId);
                          }
                      }
                  
                      /**
                      * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
                      * It uses the information stored by passMessage method when the assets were initially transferred
                      * @param _messageId id of the message which execution failed on the other network.
                      */
                      function fixFailedMessage(bytes32 _messageId) public {
                          super.fixFailedMessage(_messageId);
                          address token = messageToken(_messageId);
                          if (_messageId == tokenRegistrationMessageId(token)) {
                              delete uintStorage[keccak256(abi.encodePacked("dailyLimit", token))];
                              delete uintStorage[keccak256(abi.encodePacked("maxPerTx", token))];
                              delete uintStorage[keccak256(abi.encodePacked("minPerTx", token))];
                              delete uintStorage[keccak256(abi.encodePacked("executionDailyLimit", token))];
                              delete uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", token))];
                              _setTokenRegistrationMessageId(token, bytes32(0));
                          }
                      }
                  
                      /**
                      * @dev Unlock back the amount of tokens that were bridged to the other network but failed.
                      * @param _token address that bridged token contract.
                      * @param _recipient address that will receive the tokens.
                      * @param _value amount of tokens to be received.
                      */
                      function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
                          _setMediatorBalance(_token, mediatorBalance(_token).sub(_value));
                          _token.safeTransfer(_recipient, _value);
                      }
                  
                      /**
                      * @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
                      * without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
                      * @param _token address of the token contract.
                      * @param _receiver the address that will receive the tokens on the other network.
                      */
                      function fixMediatorBalance(address _token, address _receiver) public onlyIfUpgradeabilityOwner {
                          require(isTokenRegistered(_token));
                          uint256 balance = ERC677(_token).balanceOf(address(this));
                          uint256 expectedBalance = mediatorBalance(_token);
                          require(balance > expectedBalance);
                          uint256 diff = balance - expectedBalance;
                          uint256 available = maxAvailablePerTx(_token);
                          require(available > 0);
                          if (diff > available) {
                              diff = available;
                          }
                          addTotalSpentPerDay(_token, getCurrentDay(), diff);
                          _setMediatorBalance(_token, expectedBalance.add(diff));
                  
                          bytes memory data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, diff);
                  
                          bytes32 _messageId = bridgeContract().requireToPassMessage(
                              mediatorContractOnOtherSide(),
                              data,
                              requestGasLimit()
                          );
                  
                          setMessageToken(_messageId, _token);
                          setMessageValue(_messageId, diff);
                          setMessageRecipient(_messageId, _receiver);
                      }
                  
                      /**
                      * @dev Tells the expected token balance of the contract.
                      * @param _token address of token contract.
                      * @return the current tracked token balance of the contract.
                      */
                      function mediatorBalance(address _token) public view returns (uint256) {
                          return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))];
                      }
                  
                      /**
                      * @dev Returns message id where specified token was first seen and deploy on the other side was requested.
                      * @param _token address of token contract.
                      * @return message id of the send message.
                      */
                      function tokenRegistrationMessageId(address _token) public view returns (bytes32) {
                          return bytes32(uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))]);
                      }
                  
                      /**
                      * @dev Updates expected token balance of the contract.
                      * @param _token address of token contract.
                      * @param _balance the new token balance of the contract.
                      */
                      function _setMediatorBalance(address _token, uint256 _balance) internal {
                          uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance;
                      }
                  
                      /**
                      * @dev Updates message id where specified token was first seen and deploy on the other side was requested.
                      * @param _token address of token contract.
                      * @param _messageId message id of the send message.
                      */
                      function _setTokenRegistrationMessageId(address _token, bytes32 _messageId) internal {
                          uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))] = uint256(_messageId);
                      }
                  }