Contract Source Code:
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { MessagingFee, MessagingParams, MessagingReceipt, Origin, ILayerZeroEndpointV2 } from "./interfaces/ILayerZeroEndpointV2.sol";
import { ISendLib, Packet } from "./interfaces/ISendLib.sol";
import { ILayerZeroReceiver } from "./interfaces/ILayerZeroReceiver.sol";
import { Errors } from "./libs/Errors.sol";
import { GUID } from "./libs/GUID.sol";
import { Transfer } from "./libs/Transfer.sol";
import { MessagingChannel } from "./MessagingChannel.sol";
import { MessagingComposer } from "./MessagingComposer.sol";
import { MessageLibManager } from "./MessageLibManager.sol";
import { MessagingContext } from "./MessagingContext.sol";
// LayerZero EndpointV2 is fully backward compatible with LayerZero Endpoint(V1), but it also supports additional
// features that Endpoint(V1) does not support now and may not in the future. We have also changed some terminology
// to clarify pre-existing language that might have been confusing.
//
// The following is a list of terminology changes:
// -chainId -> eid
// - Rationale: chainId was a term we initially used to describe an endpoint on a specific chain. Since
// LayerZero supports non-EVMs we could not map the classic EVM chainIds to the LayerZero chainIds, making it
// confusing for developers. With the addition of EndpointV2 and its backward compatible nature, we would have
// two chainIds per chain that has Endpoint(V1), further confusing developers. We have decided to change the
// name to Endpoint Id, or eid, for simplicity and clarity.
// -adapterParams -> options
// -userApplication -> oapp. Omnichain Application
// -srcAddress -> sender
// -dstAddress -> receiver
// - Rationale: The sender/receiver on EVM is the address. However, on non-EVM chains, the sender/receiver could
// represented as a public key, or some other identifier. The term sender/receiver is more generic
// -payload -> message.
// - Rationale: The term payload is used in the context of a packet, which is a combination of the message and GUID
contract EndpointV2 is ILayerZeroEndpointV2, MessagingChannel, MessageLibManager, MessagingComposer, MessagingContext {
address public lzToken;
mapping(address oapp => address delegate) public delegates;
/// @param _eid the unique Endpoint Id for this deploy that all other Endpoints can use to send to it
constructor(uint32 _eid, address _owner) MessagingChannel(_eid) {
_transferOwnership(_owner);
}
/// @dev MESSAGING STEP 0
/// @notice This view function gives the application built on top of LayerZero the ability to requests a quote
/// with the same parameters as they would to send their message. Since the quotes are given on chain there is a
/// race condition in which the prices could change between the time the user gets their quote and the time they
/// submit their message. If the price moves up and the user doesn't send enough funds the transaction will revert,
/// if the price goes down the _refundAddress provided by the app will be refunded the difference.
/// @param _params the messaging parameters
/// @param _sender the sender of the message
function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory) {
// lzToken must be set to support payInLzToken
if (_params.payInLzToken && lzToken == address(0x0)) revert Errors.LZ_LzTokenUnavailable();
// get the correct outbound nonce
uint64 nonce = outboundNonce[_sender][_params.dstEid][_params.receiver] + 1;
// construct the packet with a GUID
Packet memory packet = Packet({
nonce: nonce,
srcEid: eid,
sender: _sender,
dstEid: _params.dstEid,
receiver: _params.receiver,
guid: GUID.generate(nonce, eid, _sender, _params.dstEid, _params.receiver),
message: _params.message
});
// get the send library by sender and dst eid
// use _ to avoid variable shadowing
address _sendLibrary = getSendLibrary(_sender, _params.dstEid);
return ISendLib(_sendLibrary).quote(packet, _params.options, _params.payInLzToken);
}
/// @dev MESSAGING STEP 1 - OApp need to transfer the fees to the endpoint before sending the message
/// @param _params the messaging parameters
/// @param _refundAddress the address to refund both the native and lzToken
function send(
MessagingParams calldata _params,
address _refundAddress
) external payable sendContext(_params.dstEid, msg.sender) returns (MessagingReceipt memory) {
if (_params.payInLzToken && lzToken == address(0x0)) revert Errors.LZ_LzTokenUnavailable();
// send message
(MessagingReceipt memory receipt, address _sendLibrary) = _send(msg.sender, _params);
// OApp can simulate with 0 native value it will fail with error including the required fee, which can be provided in the actual call
// this trick can be used to avoid the need to write the quote() function
// however, without the quote view function it will be hard to compose an oapp on chain
uint256 suppliedNative = _suppliedNative();
uint256 suppliedLzToken = _suppliedLzToken(_params.payInLzToken);
_assertMessagingFee(receipt.fee, suppliedNative, suppliedLzToken);
// handle lz token fees
_payToken(lzToken, receipt.fee.lzTokenFee, suppliedLzToken, _sendLibrary, _refundAddress);
// handle native fees
_payNative(receipt.fee.nativeFee, suppliedNative, _sendLibrary, _refundAddress);
return receipt;
}
/// @dev internal function for sending the messages used by all external send methods
/// @param _sender the address of the application sending the message to the destination chain
/// @param _params the messaging parameters
function _send(
address _sender,
MessagingParams calldata _params
) internal returns (MessagingReceipt memory, address) {
// get the correct outbound nonce
uint64 latestNonce = _outbound(_sender, _params.dstEid, _params.receiver);
// construct the packet with a GUID
Packet memory packet = Packet({
nonce: latestNonce,
srcEid: eid,
sender: _sender,
dstEid: _params.dstEid,
receiver: _params.receiver,
guid: GUID.generate(latestNonce, eid, _sender, _params.dstEid, _params.receiver),
message: _params.message
});
// get the send library by sender and dst eid
address _sendLibrary = getSendLibrary(_sender, _params.dstEid);
// messageLib always returns encodedPacket with guid
(MessagingFee memory fee, bytes memory encodedPacket) = ISendLib(_sendLibrary).send(
packet,
_params.options,
_params.payInLzToken
);
// Emit packet information for DVNs, Executors, and any other offchain infrastructure to only listen
// for this one event to perform their actions.
emit PacketSent(encodedPacket, _params.options, _sendLibrary);
return (MessagingReceipt(packet.guid, latestNonce, fee), _sendLibrary);
}
/// @dev MESSAGING STEP 2 - on the destination chain
/// @dev configured receive library verifies a message
/// @param _origin a struct holding the srcEid, nonce, and sender of the message
/// @param _receiver the receiver of the message
/// @param _payloadHash the payload hash of the message
function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external {
if (!isValidReceiveLibrary(_receiver, _origin.srcEid, msg.sender)) revert Errors.LZ_InvalidReceiveLibrary();
uint64 lazyNonce = lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender];
if (!_initializable(_origin, _receiver, lazyNonce)) revert Errors.LZ_PathNotInitializable();
if (!_verifiable(_origin, _receiver, lazyNonce)) revert Errors.LZ_PathNotVerifiable();
// insert the message into the message channel
_inbound(_receiver, _origin.srcEid, _origin.sender, _origin.nonce, _payloadHash);
emit PacketVerified(_origin, _receiver, _payloadHash);
}
/// @dev MESSAGING STEP 3 - the last step
/// @dev execute a verified message to the designated receiver
/// @dev the execution provides the execution context (caller, extraData) to the receiver. the receiver can optionally assert the caller and validate the untrusted extraData
/// @dev cant reentrant because the payload is cleared before execution
/// @param _origin the origin of the message
/// @param _receiver the receiver of the message
/// @param _guid the guid of the message
/// @param _message the message
/// @param _extraData the extra data provided by the executor. this data is untrusted and should be validated.
function lzReceive(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
bytes calldata _message,
bytes calldata _extraData
) external payable {
// clear the payload first to prevent reentrancy, and then execute the message
_clearPayload(_receiver, _origin.srcEid, _origin.sender, _origin.nonce, abi.encodePacked(_guid, _message));
ILayerZeroReceiver(_receiver).lzReceive{ value: msg.value }(_origin, _guid, _message, msg.sender, _extraData);
emit PacketDelivered(_origin, _receiver);
}
/// @param _origin the origin of the message
/// @param _receiver the receiver of the message
/// @param _guid the guid of the message
/// @param _message the message
/// @param _extraData the extra data provided by the executor.
/// @param _reason the reason for failure
function lzReceiveAlert(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
uint256 _gas,
uint256 _value,
bytes calldata _message,
bytes calldata _extraData,
bytes calldata _reason
) external {
emit LzReceiveAlert(_receiver, msg.sender, _origin, _guid, _gas, _value, _message, _extraData, _reason);
}
/// @dev Oapp uses this interface to clear a message.
/// @dev this is a PULL mode versus the PUSH mode of lzReceive
/// @dev the cleared message can be ignored by the app (effectively burnt)
/// @dev authenticated by oapp
/// @param _origin the origin of the message
/// @param _guid the guid of the message
/// @param _message the message
function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external {
_assertAuthorized(_oapp);
bytes memory payload = abi.encodePacked(_guid, _message);
_clearPayload(_oapp, _origin.srcEid, _origin.sender, _origin.nonce, payload);
emit PacketDelivered(_origin, _oapp);
}
/// @dev allows reconfiguration to recover from wrong configurations
/// @dev users should never approve the EndpointV2 contract to spend their non-layerzero tokens
/// @dev override this function if the endpoint is charging ERC20 tokens as native
/// @dev only owner
/// @param _lzToken the new layer zero token address
function setLzToken(address _lzToken) public virtual onlyOwner {
lzToken = _lzToken;
emit LzTokenSet(_lzToken);
}
/// @dev recover the token sent to this contract by mistake
/// @dev only owner
/// @param _token the token to recover. if 0x0 then it is native token
/// @param _to the address to send the token to
/// @param _amount the amount to send
function recoverToken(address _token, address _to, uint256 _amount) external onlyOwner {
Transfer.nativeOrToken(_token, _to, _amount);
}
/// @dev handling token payments on endpoint. the sender must approve the endpoint to spend the token
/// @dev internal function
/// @param _token the token to pay
/// @param _required the amount required
/// @param _supplied the amount supplied
/// @param _receiver the receiver of the token
function _payToken(
address _token,
uint256 _required,
uint256 _supplied,
address _receiver,
address _refundAddress
) internal {
if (_required > 0) {
Transfer.token(_token, _receiver, _required);
}
if (_required < _supplied) {
unchecked {
// refund the excess
Transfer.token(_token, _refundAddress, _supplied - _required);
}
}
}
/// @dev handling native token payments on endpoint
/// @dev override this if the endpoint is charging ERC20 tokens as native
/// @dev internal function
/// @param _required the amount required
/// @param _supplied the amount supplied
/// @param _receiver the receiver of the native token
/// @param _refundAddress the address to refund the excess to
function _payNative(
uint256 _required,
uint256 _supplied,
address _receiver,
address _refundAddress
) internal virtual {
if (_required > 0) {
Transfer.native(_receiver, _required);
}
if (_required < _supplied) {
unchecked {
// refund the excess
Transfer.native(_refundAddress, _supplied - _required);
}
}
}
/// @dev get the balance of the lzToken as the supplied lzToken fee if payInLzToken is true
function _suppliedLzToken(bool _payInLzToken) internal view returns (uint256 supplied) {
if (_payInLzToken) {
supplied = IERC20(lzToken).balanceOf(address(this));
// if payInLzToken is true, the supplied fee must be greater than 0 to prevent a race condition
// in which an oapp sending a message with lz token and the lz token is set to a new token between the tx
// being sent and the tx being mined. if the required lz token fee is 0 and the old lz token would be
// locked in the contract instead of being refunded
if (supplied == 0) revert Errors.LZ_ZeroLzTokenFee();
}
}
/// @dev override this if the endpoint is charging ERC20 tokens as native
function _suppliedNative() internal view virtual returns (uint256) {
return msg.value;
}
/// @dev Assert the required fees and the supplied fees are enough
function _assertMessagingFee(
MessagingFee memory _required,
uint256 _suppliedNativeFee,
uint256 _suppliedLzTokenFee
) internal pure {
if (_required.nativeFee > _suppliedNativeFee || _required.lzTokenFee > _suppliedLzTokenFee) {
revert Errors.LZ_InsufficientFee(
_required.nativeFee,
_suppliedNativeFee,
_required.lzTokenFee,
_suppliedLzTokenFee
);
}
}
/// @dev override this if the endpoint is charging ERC20 tokens as native
/// @return 0x0 if using native. otherwise the address of the native ERC20 token
function nativeToken() external view virtual returns (address) {
return address(0x0);
}
/// @notice delegate is authorized by the oapp to configure anything in layerzero
function setDelegate(address _delegate) external {
delegates[msg.sender] = _delegate;
emit DelegateSet(msg.sender, _delegate);
}
// ========================= Internal =========================
function _initializable(
Origin calldata _origin,
address _receiver,
uint64 _lazyInboundNonce
) internal view returns (bool) {
return
_lazyInboundNonce > 0 || // allowInitializePath already checked
ILayerZeroReceiver(_receiver).allowInitializePath(_origin);
}
/// @dev bytes(0) payloadHash can never be submitted
function _verifiable(
Origin calldata _origin,
address _receiver,
uint64 _lazyInboundNonce
) internal view returns (bool) {
return
_origin.nonce > _lazyInboundNonce || // either initializing an empty slot or reverifying
inboundPayloadHash[_receiver][_origin.srcEid][_origin.sender][_origin.nonce] != EMPTY_PAYLOAD_HASH; // only allow reverifying if it hasn't been executed
}
/// @dev assert the caller to either be the oapp or the delegate
function _assertAuthorized(address _oapp) internal view override(MessagingChannel, MessageLibManager) {
if (msg.sender != _oapp && msg.sender != delegates[_oapp]) revert Errors.LZ_Unauthorized();
}
// ========================= VIEW FUNCTIONS FOR OFFCHAIN ONLY =========================
// Not involved in any state transition function.
// ====================================================================================
function initializable(Origin calldata _origin, address _receiver) external view returns (bool) {
return _initializable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
}
function verifiable(Origin calldata _origin, address _receiver) external view returns (bool) {
return _verifiable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
}
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IMessageLib, MessageLibType } from "./interfaces/IMessageLib.sol";
import { IMessageLibManager, SetConfigParam } from "./interfaces/IMessageLibManager.sol";
import { Errors } from "./libs/Errors.sol";
import { BlockedMessageLib } from "./messagelib/BlockedMessageLib.sol";
abstract contract MessageLibManager is Ownable, IMessageLibManager {
address private constant DEFAULT_LIB = address(0);
// the library that reverts both on send and quote
// must be configured on construction and be immutable
address public immutable blockedLibrary;
// only registered libraries all valid libraries
// the blockedLibrary will be registered on construction
address[] internal registeredLibraries;
mapping(address lib => bool) public isRegisteredLibrary;
// both sendLibrary and receiveLibrary config can be lazily resolved
mapping(address sender => mapping(uint32 dstEid => address lib)) internal sendLibrary;
mapping(address receiver => mapping(uint32 srcEid => address lib)) internal receiveLibrary;
mapping(address receiver => mapping(uint32 srcEid => Timeout)) public receiveLibraryTimeout;
mapping(uint32 dstEid => address lib) public defaultSendLibrary;
mapping(uint32 srcEid => address lib) public defaultReceiveLibrary;
mapping(uint32 srcEid => Timeout) public defaultReceiveLibraryTimeout;
constructor() {
blockedLibrary = address(new BlockedMessageLib());
registerLibrary(blockedLibrary);
}
modifier onlyRegistered(address _lib) {
if (!isRegisteredLibrary[_lib]) revert Errors.LZ_OnlyRegisteredLib();
_;
}
modifier isSendLib(address _lib) {
if (_lib != DEFAULT_LIB) {
if (IMessageLib(_lib).messageLibType() == MessageLibType.Receive) revert Errors.LZ_OnlySendLib();
}
_;
}
modifier isReceiveLib(address _lib) {
if (_lib != DEFAULT_LIB) {
if (IMessageLib(_lib).messageLibType() == MessageLibType.Send) revert Errors.LZ_OnlyReceiveLib();
}
_;
}
modifier onlyRegisteredOrDefault(address _lib) {
if (!isRegisteredLibrary[_lib] && _lib != DEFAULT_LIB) revert Errors.LZ_OnlyRegisteredOrDefaultLib();
_;
}
/// @dev check if the library supported the eid.
modifier onlySupportedEid(address _lib, uint32 _eid) {
/// @dev doesnt need to check for default lib, because when they are initially added they get passed through this modifier
if (_lib != DEFAULT_LIB) {
if (!IMessageLib(_lib).isSupportedEid(_eid)) revert Errors.LZ_UnsupportedEid();
}
_;
}
function getRegisteredLibraries() external view returns (address[] memory) {
return registeredLibraries;
}
/// @notice The Send Library is the Oapp specified library that will be used to send the message to the destination
/// endpoint. If the Oapp does not specify a Send Library, the default Send Library will be used.
/// @dev If the Oapp does not have a selected Send Library, this function will resolve to the default library
/// configured by LayerZero
/// @return lib address of the Send Library
/// @param _sender The address of the Oapp that is sending the message
/// @param _dstEid The destination endpoint id
function getSendLibrary(address _sender, uint32 _dstEid) public view returns (address lib) {
lib = sendLibrary[_sender][_dstEid];
if (lib == DEFAULT_LIB) {
lib = defaultSendLibrary[_dstEid];
if (lib == address(0x0)) revert Errors.LZ_DefaultSendLibUnavailable();
}
}
function isDefaultSendLibrary(address _sender, uint32 _dstEid) public view returns (bool) {
return sendLibrary[_sender][_dstEid] == DEFAULT_LIB;
}
/// @dev the receiveLibrary can be lazily resolved that if not set it will point to the default configured by LayerZero
function getReceiveLibrary(address _receiver, uint32 _srcEid) public view returns (address lib, bool isDefault) {
lib = receiveLibrary[_receiver][_srcEid];
if (lib == DEFAULT_LIB) {
lib = defaultReceiveLibrary[_srcEid];
if (lib == address(0x0)) revert Errors.LZ_DefaultReceiveLibUnavailable();
isDefault = true;
}
}
/// @dev called when the endpoint checks if the msgLib attempting to verify the msg is the configured msgLib of the Oapp
/// @dev this check provides the ability for Oapp to lock in a trusted msgLib
/// @dev it will fist check if the msgLib is the currently configured one. then check if the msgLib is the one in grace period of msgLib versioning upgrade
function isValidReceiveLibrary(
address _receiver,
uint32 _srcEid,
address _actualReceiveLib
) public view returns (bool) {
// early return true if the _actualReceiveLib is the currently configured one
(address expectedReceiveLib, bool isDefault) = getReceiveLibrary(_receiver, _srcEid);
if (_actualReceiveLib == expectedReceiveLib) {
return true;
}
// check the timeout condition otherwise
// if the Oapp is using defaultReceiveLibrary, use the default Timeout config
// otherwise, use the Timeout configured by the Oapp
Timeout memory timeout = isDefault
? defaultReceiveLibraryTimeout[_srcEid]
: receiveLibraryTimeout[_receiver][_srcEid];
// requires the _actualReceiveLib to be the same as the one in grace period and the grace period has not expired
// block.number is uint256 so timeout.expiry must > 0, which implies a non-ZERO value
if (timeout.lib == _actualReceiveLib && timeout.expiry > block.number) {
// timeout lib set and has not expired
return true;
}
// returns false by default
return false;
}
//------- Owner interfaces
/// @dev all libraries have to implement the erc165 interface to prevent wrong configurations
/// @dev only owner
function registerLibrary(address _lib) public onlyOwner {
// must have the right interface
if (!IERC165(_lib).supportsInterface(type(IMessageLib).interfaceId)) revert Errors.LZ_UnsupportedInterface();
// must have not been registered
if (isRegisteredLibrary[_lib]) revert Errors.LZ_AlreadyRegistered();
// insert into both the map and the list
isRegisteredLibrary[_lib] = true;
registeredLibraries.push(_lib);
emit LibraryRegistered(_lib);
}
/// @dev owner setting the defaultSendLibrary
/// @dev can set to the blockedLibrary, which is a registered library
/// @dev the msgLib must enable the support before they can be registered to the endpoint as the default
/// @dev only owner
function setDefaultSendLibrary(
uint32 _eid,
address _newLib
) external onlyOwner onlyRegistered(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
// must provide a different value
if (defaultSendLibrary[_eid] == _newLib) revert Errors.LZ_SameValue();
defaultSendLibrary[_eid] = _newLib;
emit DefaultSendLibrarySet(_eid, _newLib);
}
/// @dev owner setting the defaultSendLibrary
/// @dev must be a registered library (including blockLibrary) with the eid support enabled
/// @dev in version migration, it can add a grace period to the old library. if the grace period is 0, it will delete the timeout configuration.
/// @dev only owner
function setDefaultReceiveLibrary(
uint32 _eid,
address _newLib,
uint256 _gracePeriod
) external onlyOwner onlyRegistered(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
address oldLib = defaultReceiveLibrary[_eid];
// must provide a different value
if (oldLib == _newLib) revert Errors.LZ_SameValue();
defaultReceiveLibrary[_eid] = _newLib;
emit DefaultReceiveLibrarySet(_eid, _newLib);
if (_gracePeriod > 0) {
// override the current default timeout to the [old_lib + new expiry]
Timeout storage timeout = defaultReceiveLibraryTimeout[_eid];
timeout.lib = oldLib;
timeout.expiry = block.number + _gracePeriod;
emit DefaultReceiveLibraryTimeoutSet(_eid, oldLib, timeout.expiry);
} else {
// otherwise, remove the old configuration.
delete defaultReceiveLibraryTimeout[_eid];
emit DefaultReceiveLibraryTimeoutSet(_eid, oldLib, 0);
}
}
/// @dev owner setting the defaultSendLibrary
/// @dev must be a registered library (including blockLibrary) with the eid support enabled
/// @dev can used to (1) extend the current configuration (2) force remove the current configuration (3) change to a new configuration
/// @param _expiry the block number when lib expires
function setDefaultReceiveLibraryTimeout(
uint32 _eid,
address _lib,
uint256 _expiry
) external onlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) onlyOwner {
if (_expiry == 0) {
// force remove the current configuration
delete defaultReceiveLibraryTimeout[_eid];
} else {
// override it with new configuration
if (_expiry <= block.number) revert Errors.LZ_InvalidExpiry();
Timeout storage timeout = defaultReceiveLibraryTimeout[_eid];
timeout.lib = _lib;
timeout.expiry = _expiry;
}
emit DefaultReceiveLibraryTimeoutSet(_eid, _lib, _expiry);
}
/// @dev returns true only if both the default send/receive libraries are set
function isSupportedEid(uint32 _eid) external view returns (bool) {
return defaultSendLibrary[_eid] != address(0) && defaultReceiveLibrary[_eid] != address(0);
}
//------- OApp interfaces
/// @dev Oapp setting the sendLibrary
/// @dev must be a registered library (including blockLibrary) with the eid support enabled
/// @dev authenticated by the Oapp
function setSendLibrary(
address _oapp,
uint32 _eid,
address _newLib
) external onlyRegisteredOrDefault(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
_assertAuthorized(_oapp);
// must provide a different value
if (sendLibrary[_oapp][_eid] == _newLib) revert Errors.LZ_SameValue();
sendLibrary[_oapp][_eid] = _newLib;
emit SendLibrarySet(_oapp, _eid, _newLib);
}
/// @dev Oapp setting the receiveLibrary
/// @dev must be a registered library (including blockLibrary) with the eid support enabled
/// @dev in version migration, it can add a grace period to the old library. if the grace period is 0, it will delete the timeout configuration.
/// @dev authenticated by the Oapp
/// @param _gracePeriod the number of blocks from now until oldLib expires
function setReceiveLibrary(
address _oapp,
uint32 _eid,
address _newLib,
uint256 _gracePeriod
) external onlyRegisteredOrDefault(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
_assertAuthorized(_oapp);
address oldLib = receiveLibrary[_oapp][_eid];
// must provide new values
if (oldLib == _newLib) revert Errors.LZ_SameValue();
receiveLibrary[_oapp][_eid] = _newLib;
emit ReceiveLibrarySet(_oapp, _eid, _newLib);
if (_gracePeriod > 0) {
// to simplify the logic, we only allow to set timeout if neither the new lib nor old lib is DEFAULT_LIB, which would should read the default timeout configurations
// (1) if the Oapp wants to fall back to the DEFAULT, then set the newLib to DEFAULT with grace period == 0
// (2) if the Oapp wants to change to a non DEFAULT from DEFAULT, then set the newLib to 'non-default' with _gracePeriod == 0, then use setReceiveLibraryTimeout() interface
if (oldLib == DEFAULT_LIB || _newLib == DEFAULT_LIB) revert Errors.LZ_OnlyNonDefaultLib();
// write to storage
Timeout memory timeout = Timeout({ lib: oldLib, expiry: block.number + _gracePeriod });
receiveLibraryTimeout[_oapp][_eid] = timeout;
emit ReceiveLibraryTimeoutSet(_oapp, _eid, oldLib, timeout.expiry);
} else {
delete receiveLibraryTimeout[_oapp][_eid];
emit ReceiveLibraryTimeoutSet(_oapp, _eid, oldLib, 0);
}
}
/// @dev Oapp setting the defaultSendLibrary
/// @dev must be a registered library (including blockLibrary) with the eid support enabled
/// @dev can used to (1) extend the current configuration (2) force remove the current configuration (3) change to a new configuration
/// @param _expiry the block number when lib expires
function setReceiveLibraryTimeout(
address _oapp,
uint32 _eid,
address _lib,
uint256 _expiry
) external onlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) {
_assertAuthorized(_oapp);
(, bool isDefault) = getReceiveLibrary(_oapp, _eid);
// if current library is DEFAULT, Oapp cant set the timeout
if (isDefault) revert Errors.LZ_OnlyNonDefaultLib();
if (_expiry == 0) {
// force remove the current configuration
delete receiveLibraryTimeout[_oapp][_eid];
} else {
// override it with new configuration
if (_expiry <= block.number) revert Errors.LZ_InvalidExpiry();
Timeout storage timeout = receiveLibraryTimeout[_oapp][_eid];
timeout.lib = _lib;
timeout.expiry = _expiry;
}
emit ReceiveLibraryTimeoutSet(_oapp, _eid, _lib, _expiry);
}
//------- library config setter/getter. all pass-through functions to the msgLib
/// @dev authenticated by the _oapp
function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external onlyRegistered(_lib) {
_assertAuthorized(_oapp);
IMessageLib(_lib).setConfig(_oapp, _params);
}
/// @dev a view function to query the current configuration of the OApp
function getConfig(
address _oapp,
address _lib,
uint32 _eid,
uint32 _configType
) external view onlyRegistered(_lib) returns (bytes memory config) {
return IMessageLib(_lib).getConfig(_eid, _oapp, _configType);
}
function _assertAuthorized(address _oapp) internal virtual;
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { IMessagingChannel } from "./interfaces/IMessagingChannel.sol";
import { Errors } from "./libs/Errors.sol";
import { GUID } from "./libs/GUID.sol";
abstract contract MessagingChannel is IMessagingChannel {
bytes32 public constant EMPTY_PAYLOAD_HASH = bytes32(0);
bytes32 public constant NIL_PAYLOAD_HASH = bytes32(type(uint256).max);
// The universally unique id (UUID) of this deployed Endpoint
uint32 public immutable eid;
mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => uint64 nonce)))
public lazyInboundNonce;
mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => mapping(uint64 inboundNonce => bytes32 payloadHash))))
public inboundPayloadHash;
mapping(address sender => mapping(uint32 dstEid => mapping(bytes32 receiver => uint64 nonce))) public outboundNonce;
/// @param _eid is the universally unique id (UUID) of this deployed Endpoint
constructor(uint32 _eid) {
eid = _eid;
}
/// @dev increase and return the next outbound nonce
function _outbound(address _sender, uint32 _dstEid, bytes32 _receiver) internal returns (uint64 nonce) {
unchecked {
nonce = ++outboundNonce[_sender][_dstEid][_receiver];
}
}
/// @dev inbound won't update the nonce eagerly to allow unordered verification
/// @dev instead, it will update the nonce lazily when the message is received
/// @dev messages can only be cleared in order to preserve censorship-resistance
function _inbound(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce,
bytes32 _payloadHash
) internal {
if (_payloadHash == EMPTY_PAYLOAD_HASH) revert Errors.LZ_InvalidPayloadHash();
inboundPayloadHash[_receiver][_srcEid][_sender][_nonce] = _payloadHash;
}
/// @dev returns the max index of the longest gapless sequence of verified msg nonces.
/// @dev the uninitialized value is 0. the first nonce is always 1
/// @dev it starts from the lazyInboundNonce (last checkpoint) and iteratively check if the next nonce has been verified
/// @dev this function can OOG if too many backlogs, but it can be trivially fixed by just clearing some prior messages
/// @dev NOTE: Oapp explicitly skipped nonces count as "verified" for these purposes
/// @dev eg. [1,2,3,4,6,7] => 4, [1,2,6,8,10] => 2, [1,3,4,5,6] => 1
function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) public view returns (uint64) {
uint64 nonceCursor = lazyInboundNonce[_receiver][_srcEid][_sender];
// find the effective inbound currentNonce
unchecked {
while (_hasPayloadHash(_receiver, _srcEid, _sender, nonceCursor + 1)) {
++nonceCursor;
}
}
return nonceCursor;
}
/// @dev checks if the storage slot is not initialized. Assumes computationally infeasible that payload can hash to 0
function _hasPayloadHash(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce
) internal view returns (bool) {
return inboundPayloadHash[_receiver][_srcEid][_sender][_nonce] != EMPTY_PAYLOAD_HASH;
}
/// @dev the caller must provide _nonce to prevent skipping the unintended nonce
/// @dev it could happen in some race conditions, e.g. to skip nonce 3, but nonce 3 was consumed first
/// @dev usage: skipping the next nonce to prevent message verification, e.g. skip a message when Precrime throws alerts
/// @dev if the Oapp wants to skip a verified message, it should call the clear() function instead
/// @dev after skipping, the lazyInboundNonce is set to the provided nonce, which makes the inboundNonce also the provided nonce
/// @dev ie. allows the Oapp to increment the lazyInboundNonce without having had that corresponding msg be verified
function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external {
_assertAuthorized(_oapp);
if (_nonce != inboundNonce(_oapp, _srcEid, _sender) + 1) revert Errors.LZ_InvalidNonce(_nonce);
lazyInboundNonce[_oapp][_srcEid][_sender] = _nonce;
emit InboundNonceSkipped(_srcEid, _sender, _oapp, _nonce);
}
/// @dev Marks a packet as verified, but disallows execution until it is re-verified.
/// @dev Reverts if the provided _payloadHash does not match the currently verified payload hash.
/// @dev A non-verified nonce can be nilified by passing EMPTY_PAYLOAD_HASH for _payloadHash.
/// @dev Assumes the computational intractability of finding a payload that hashes to bytes32.max.
/// @dev Authenticated by the caller
function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {
_assertAuthorized(_oapp);
bytes32 curPayloadHash = inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
if (curPayloadHash != _payloadHash) revert Errors.LZ_PayloadHashNotFound(curPayloadHash, _payloadHash);
if (_nonce <= lazyInboundNonce[_oapp][_srcEid][_sender] && curPayloadHash == EMPTY_PAYLOAD_HASH)
revert Errors.LZ_InvalidNonce(_nonce);
// set it to nil
inboundPayloadHash[_oapp][_srcEid][_sender][_nonce] = NIL_PAYLOAD_HASH;
emit PacketNilified(_srcEid, _sender, _oapp, _nonce, _payloadHash);
}
/// @dev Marks a nonce as unexecutable and un-verifiable. The nonce can never be re-verified or executed.
/// @dev Reverts if the provided _payloadHash does not match the currently verified payload hash.
/// @dev Only packets with nonces less than or equal to the lazy inbound nonce can be burned.
/// @dev Reverts if the nonce has already been executed.
/// @dev Authenticated by the caller
function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {
_assertAuthorized(_oapp);
bytes32 curPayloadHash = inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
if (curPayloadHash != _payloadHash) revert Errors.LZ_PayloadHashNotFound(curPayloadHash, _payloadHash);
if (curPayloadHash == EMPTY_PAYLOAD_HASH || _nonce > lazyInboundNonce[_oapp][_srcEid][_sender])
revert Errors.LZ_InvalidNonce(_nonce);
delete inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
emit PacketBurnt(_srcEid, _sender, _oapp, _nonce, _payloadHash);
}
/// @dev calling this function will clear the stored message and increment the lazyInboundNonce to the provided nonce
/// @dev if a lot of messages are queued, the messages can be cleared with a smaller step size to prevent OOG
/// @dev NOTE: this function does not change inboundNonce, it only changes the lazyInboundNonce up to the provided nonce
function _clearPayload(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce,
bytes memory _payload
) internal returns (bytes32 actualHash) {
uint64 currentNonce = lazyInboundNonce[_receiver][_srcEid][_sender];
if (_nonce > currentNonce) {
unchecked {
// try to lazily update the inboundNonce till the _nonce
for (uint64 i = currentNonce + 1; i <= _nonce; ++i) {
if (!_hasPayloadHash(_receiver, _srcEid, _sender, i)) revert Errors.LZ_InvalidNonce(i);
}
lazyInboundNonce[_receiver][_srcEid][_sender] = _nonce;
}
}
// check the hash of the payload to verify the executor has given the proper payload that has been verified
actualHash = keccak256(_payload);
bytes32 expectedHash = inboundPayloadHash[_receiver][_srcEid][_sender][_nonce];
if (expectedHash != actualHash) revert Errors.LZ_PayloadHashNotFound(expectedHash, actualHash);
// remove it from the storage
delete inboundPayloadHash[_receiver][_srcEid][_sender][_nonce];
}
/// @dev returns the GUID for the next message given the path
/// @dev the Oapp might want to include the GUID into the message in some cases
function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32) {
uint64 nextNonce = outboundNonce[_sender][_dstEid][_receiver] + 1;
return GUID.generate(nextNonce, eid, _sender, _dstEid, _receiver);
}
function _assertAuthorized(address _oapp) internal virtual;
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { IMessagingComposer } from "./interfaces/IMessagingComposer.sol";
import { ILayerZeroComposer } from "./interfaces/ILayerZeroComposer.sol";
import { Errors } from "./libs/Errors.sol";
abstract contract MessagingComposer is IMessagingComposer {
bytes32 private constant NO_MESSAGE_HASH = bytes32(0);
bytes32 private constant RECEIVED_MESSAGE_HASH = bytes32(uint256(1));
mapping(address from => mapping(address to => mapping(bytes32 guid => mapping(uint16 index => bytes32 messageHash))))
public composeQueue;
/// @dev the Oapp sends the lzCompose message to the endpoint
/// @dev the composer MUST assert the sender because anyone can send compose msg with this function
/// @dev with the same GUID, the Oapp can send compose to multiple _composer at the same time
/// @dev authenticated by the msg.sender
/// @param _to the address which will receive the composed message
/// @param _guid the message guid
/// @param _message the message
function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external {
// must have not been sent before
if (composeQueue[msg.sender][_to][_guid][_index] != NO_MESSAGE_HASH) revert Errors.LZ_ComposeExists();
composeQueue[msg.sender][_to][_guid][_index] = keccak256(_message);
emit ComposeSent(msg.sender, _to, _guid, _index, _message);
}
/// @dev execute a composed messages from the sender to the composer (receiver)
/// @dev the execution provides the execution context (caller, extraData) to the receiver.
/// the receiver can optionally assert the caller and validate the untrusted extraData
/// @dev can not re-entrant
/// @param _from the address which sends the composed message. in most cases, it is the Oapp's address.
/// @param _to the address which receives the composed message
/// @param _guid the message guid
/// @param _message the message
/// @param _extraData the extra data provided by the executor. this data is untrusted and should be validated.
function lzCompose(
address _from,
address _to,
bytes32 _guid,
uint16 _index,
bytes calldata _message,
bytes calldata _extraData
) external payable {
// assert the validity
bytes32 expectedHash = composeQueue[_from][_to][_guid][_index];
bytes32 actualHash = keccak256(_message);
if (expectedHash != actualHash) revert Errors.LZ_ComposeNotFound(expectedHash, actualHash);
// marks the message as received to prevent reentrancy
// cannot just delete the value, otherwise the message can be sent again and could result in some undefined behaviour
// even though the sender(composing Oapp) is implicitly fully trusted by the composer.
// eg. sender may not even realize it has such a bug
composeQueue[_from][_to][_guid][_index] = RECEIVED_MESSAGE_HASH;
ILayerZeroComposer(_to).lzCompose{ value: msg.value }(_from, _guid, _message, msg.sender, _extraData);
emit ComposeDelivered(_from, _to, _guid, _index);
}
/// @param _from the address which sends the composed message
/// @param _to the address which receives the composed message
/// @param _guid the message guid
/// @param _message the message
/// @param _extraData the extra data provided by the executor
/// @param _reason the reason why the message is not received
function lzComposeAlert(
address _from,
address _to,
bytes32 _guid,
uint16 _index,
uint256 _gas,
uint256 _value,
bytes calldata _message,
bytes calldata _extraData,
bytes calldata _reason
) external {
emit LzComposeAlert(_from, _to, msg.sender, _guid, _index, _gas, _value, _message, _extraData, _reason);
}
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { IMessagingContext } from "./interfaces/IMessagingContext.sol";
import { Errors } from "./libs/Errors.sol";
/// this contract acts as a non-reentrancy guard and a source of messaging context
/// the context includes the remote eid and the sender address
/// it separates the send and receive context to allow messaging receipts (send back on receive())
abstract contract MessagingContext is IMessagingContext {
uint256 private constant NOT_ENTERED = 1;
uint256 private _sendContext = NOT_ENTERED;
/// @dev the sendContext is set to 8 bytes 0s + 4 bytes eid + 20 bytes sender
modifier sendContext(uint32 _dstEid, address _sender) {
if (_sendContext != NOT_ENTERED) revert Errors.LZ_SendReentrancy();
_sendContext = (uint256(_dstEid) << 160) | uint160(_sender);
_;
_sendContext = NOT_ENTERED;
}
/// @dev returns true if sending message
function isSendingMessage() public view returns (bool) {
return _sendContext != NOT_ENTERED;
}
/// @dev returns (eid, sender) if sending message, (0, 0) otherwise
function getSendContext() external view returns (uint32, address) {
return isSendingMessage() ? _getSendContext(_sendContext) : (0, address(0));
}
function _getSendContext(uint256 _context) internal pure returns (uint32, address) {
return (uint32(_context >> 160), address(uint160(_context)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/**
* @title ILayerZeroComposer
*/
interface ILayerZeroComposer {
/**
* @notice Composes a LayerZero message from an OApp.
* @dev To ensure non-reentrancy, implementers of this interface MUST assert msg.sender is the corresponding EndpointV2 contract (i.e., onlyEndpointV2).
* @param _from The address initiating the composition, typically the OApp where the lzReceive was called.
* @param _guid The unique identifier for the corresponding LayerZero src/dst tx.
* @param _message The composed message payload in bytes. NOT necessarily the same payload passed via lzReceive.
* @param _executor The address of the executor for the composed message.
* @param _extraData Additional arbitrary data in bytes passed by the entity who executes the lzCompose.
*/
function lzCompose(
address _from,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IMessageLibManager } from "./IMessageLibManager.sol";
import { IMessagingComposer } from "./IMessagingComposer.sol";
import { IMessagingChannel } from "./IMessagingChannel.sol";
import { IMessagingContext } from "./IMessagingContext.sol";
struct MessagingParams {
uint32 dstEid;
bytes32 receiver;
bytes message;
bytes options;
bool payInLzToken;
}
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
struct Origin {
uint32 srcEid;
bytes32 sender;
uint64 nonce;
}
interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
event PacketDelivered(Origin origin, address receiver);
event LzReceiveAlert(
address indexed receiver,
address indexed executor,
Origin origin,
bytes32 guid,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
event LzTokenSet(address token);
event DelegateSet(address sender, address delegate);
function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
function send(
MessagingParams calldata _params,
address _refundAddress
) external payable returns (MessagingReceipt memory);
function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
function lzReceive(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
bytes calldata _message,
bytes calldata _extraData
) external payable;
// oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
function setLzToken(address _lzToken) external;
function lzToken() external view returns (address);
function nativeToken() external view returns (address);
function setDelegate(address _delegate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { Origin } from "./ILayerZeroEndpointV2.sol";
interface ILayerZeroReceiver {
function allowInitializePath(Origin calldata _origin) external view returns (bool);
function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);
function lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import { SetConfigParam } from "./IMessageLibManager.sol";
enum MessageLibType {
Send,
Receive,
SendAndReceive
}
interface IMessageLib is IERC165 {
function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
function isSupportedEid(uint32 _eid) external view returns (bool);
// message libs of same major version are compatible
function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
function messageLibType() external view returns (MessageLibType);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
struct SetConfigParam {
uint32 eid;
uint32 configType;
bytes config;
}
interface IMessageLibManager {
struct Timeout {
address lib;
uint256 expiry;
}
event LibraryRegistered(address newLib);
event DefaultSendLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
event SendLibrarySet(address sender, uint32 eid, address newLib);
event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
function registerLibrary(address _lib) external;
function isRegisteredLibrary(address _lib) external view returns (bool);
function getRegisteredLibraries() external view returns (address[] memory);
function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
function defaultSendLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function defaultReceiveLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
function isSupportedEid(uint32 _eid) external view returns (bool);
function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
/// ------------------- OApp interfaces -------------------
function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;
function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
function getConfig(
address _oapp,
address _lib,
uint32 _eid,
uint32 _configType
) external view returns (bytes memory config);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingChannel {
event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
function eid() external view returns (uint32);
// this is an emergency function if a message cannot be verified for some reasons
// required to provide _nextNonce to avoid race condition
function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
function inboundPayloadHash(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce
) external view returns (bytes32);
function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingComposer {
event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
event LzComposeAlert(
address indexed from,
address indexed to,
address indexed executor,
bytes32 guid,
uint16 index,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
function composeQueue(
address _from,
address _to,
bytes32 _guid,
uint16 _index
) external view returns (bytes32 messageHash);
function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
function lzCompose(
address _from,
address _to,
bytes32 _guid,
uint16 _index,
bytes calldata _message,
bytes calldata _extraData
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingContext {
function isSendingMessage() external view returns (bool);
function getSendContext() external view returns (uint32 dstEid, address sender);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
import { IMessageLib } from "./IMessageLib.sol";
struct Packet {
uint64 nonce;
uint32 srcEid;
address sender;
uint32 dstEid;
bytes32 receiver;
bytes32 guid;
bytes message;
}
interface ISendLib is IMessageLib {
function send(
Packet calldata _packet,
bytes calldata _options,
bool _payInLzToken
) external returns (MessagingFee memory, bytes memory encodedPacket);
function quote(
Packet calldata _packet,
bytes calldata _options,
bool _payInLzToken
) external view returns (MessagingFee memory);
function setTreasury(address _treasury) external;
function withdrawFee(address _to, uint256 _amount) external;
function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
library AddressCast {
error AddressCast_InvalidSizeForAddress();
error AddressCast_InvalidAddress();
function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
result = bytes32(_addressBytes);
unchecked {
uint256 offset = 32 - _addressBytes.length;
result = result >> (offset * 8);
}
}
function toBytes32(address _address) internal pure returns (bytes32 result) {
result = bytes32(uint256(uint160(_address)));
}
function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
result = new bytes(_size);
unchecked {
uint256 offset = 256 - _size * 8;
assembly {
mstore(add(result, 32), shl(offset, _addressBytes32))
}
}
}
function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
result = address(uint160(uint256(_addressBytes32)));
}
function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
result = address(bytes20(_addressBytes));
}
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
library Errors {
error LZ_LzTokenUnavailable();
error LZ_InvalidReceiveLibrary();
error LZ_InvalidNonce(uint64 nonce);
error LZ_InvalidArgument();
error LZ_InvalidExpiry();
error LZ_InvalidAmount(uint256 required, uint256 supplied);
error LZ_OnlyRegisteredOrDefaultLib();
error LZ_OnlyRegisteredLib();
error LZ_OnlyNonDefaultLib();
error LZ_Unauthorized();
error LZ_DefaultSendLibUnavailable();
error LZ_DefaultReceiveLibUnavailable();
error LZ_PathNotInitializable();
error LZ_PathNotVerifiable();
error LZ_OnlySendLib();
error LZ_OnlyReceiveLib();
error LZ_UnsupportedEid();
error LZ_UnsupportedInterface();
error LZ_AlreadyRegistered();
error LZ_SameValue();
error LZ_InvalidPayloadHash();
error LZ_PayloadHashNotFound(bytes32 expected, bytes32 actual);
error LZ_ComposeNotFound(bytes32 expected, bytes32 actual);
error LZ_ComposeExists();
error LZ_SendReentrancy();
error LZ_NotImplemented();
error LZ_InsufficientFee(
uint256 requiredNative,
uint256 suppliedNative,
uint256 requiredLzToken,
uint256 suppliedLzToken
);
error LZ_ZeroLzTokenFee();
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { AddressCast } from "./AddressCast.sol";
library GUID {
using AddressCast for address;
function generate(
uint64 _nonce,
uint32 _srcEid,
address _sender,
uint32 _dstEid,
bytes32 _receiver
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_nonce, _srcEid, _sender.toBytes32(), _dstEid, _receiver));
}
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library Transfer {
using SafeERC20 for IERC20;
address internal constant ADDRESS_ZERO = address(0);
error Transfer_NativeFailed(address _to, uint256 _value);
error Transfer_ToAddressIsZero();
function native(address _to, uint256 _value) internal {
if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
(bool success, ) = _to.call{ value: _value }("");
if (!success) revert Transfer_NativeFailed(_to, _value);
}
function token(address _token, address _to, uint256 _value) internal {
if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
IERC20(_token).safeTransfer(_to, _value);
}
function nativeOrToken(address _token, address _to, uint256 _value) internal {
if (_token == ADDRESS_ZERO) {
native(_to, _value);
} else {
token(_token, _to, _value);
}
}
}
// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import { IMessageLib, MessageLibType } from "../interfaces/IMessageLib.sol";
import { Errors } from "../libs/Errors.sol";
contract BlockedMessageLib is ERC165 {
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return interfaceId == type(IMessageLib).interfaceId || super.supportsInterface(interfaceId);
}
function version() external pure returns (uint64 major, uint8 minor, uint8 endpointVersion) {
return (type(uint64).max, type(uint8).max, 2);
}
function messageLibType() external pure returns (MessageLibType) {
return MessageLibType.SendAndReceive;
}
function isSupportedEid(uint32) external pure returns (bool) {
return true;
}
fallback() external {
revert Errors.LZ_NotImplemented();
}
}