// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @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.
* ====
*/functionisContract(address account) internalviewreturns (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].
*/functionsendValue(addresspayable 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._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory 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._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
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._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory 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._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory 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._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
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 contractrequire(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._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 27: AddressCast.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;libraryAddressCast{
errorAddressCast_InvalidSizeForAddress();
errorAddressCast_InvalidAddress();
functiontoBytes32(bytescalldata _addressBytes) internalpurereturns (bytes32 result) {
if (_addressBytes.length>32) revert AddressCast_InvalidAddress();
result =bytes32(_addressBytes);
unchecked {
uint256 offset =32- _addressBytes.length;
result = result >> (offset *8);
}
}
functiontoBytes32(address _address) internalpurereturns (bytes32 result) {
result =bytes32(uint256(uint160(_address)));
}
functiontoBytes(bytes32 _addressBytes32, uint256 _size) internalpurereturns (bytesmemory result) {
if (_size ==0|| _size >32) revert AddressCast_InvalidSizeForAddress();
result =newbytes(_size);
unchecked {
uint256 offset =256- _size *8;
assembly {
mstore(add(result, 32), shl(offset, _addressBytes32))
}
}
}
functiontoAddress(bytes32 _addressBytes32) internalpurereturns (address result) {
result =address(uint160(uint256(_addressBytes32)));
}
functiontoAddress(bytescalldata _addressBytes) internalpurereturns (address result) {
if (_addressBytes.length!=20) revert AddressCast_InvalidAddress();
result =address(bytes20(_addressBytes));
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)pragmasolidity ^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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
function_contextSuffixLength() internalviewvirtualreturns (uint256) {
return0;
}
}
Contract Source Code
File 5 of 27: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^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.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 6 of 27: EndpointV2.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^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 GUIDcontractEndpointV2isILayerZeroEndpointV2, MessagingChannel, MessageLibManager, MessagingComposer, MessagingContext{
addresspublic 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 itconstructor(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 messagefunctionquote(MessagingParams calldata _params, address _sender) externalviewreturns (MessagingFee memory) {
// lzToken must be set to support payInLzTokenif (_params.payInLzToken && lzToken ==address(0x0)) revert Errors.LZ_LzTokenUnavailable();
// get the correct outbound nonceuint64 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 shadowingaddress _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 lzTokenfunctionsend(
MessagingParams calldata _params,
address _refundAddress
) externalpayablesendContext(_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 chainuint256 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 parametersfunction_send(address _sender,
MessagingParams calldata _params
) internalreturns (MessagingReceipt memory, address) {
// get the correct outbound nonceuint64 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 eidaddress _sendLibrary = getSendLibrary(_sender, _params.dstEid);
// messageLib always returns encodedPacket with guid
(MessagingFee memory fee, bytesmemory 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 messagefunctionverify(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.functionlzReceive(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
bytescalldata _message,
bytescalldata _extraData
) externalpayable{
// 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 failurefunctionlzReceiveAlert(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
uint256 _gas,
uint256 _value,
bytescalldata _message,
bytescalldata _extraData,
bytescalldata _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 messagefunctionclear(address _oapp, Origin calldata _origin, bytes32 _guid, bytescalldata _message) external{
_assertAuthorized(_oapp);
bytesmemory 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 addressfunctionsetLzToken(address _lzToken) publicvirtualonlyOwner{
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 sendfunctionrecoverToken(address _token, address _to, uint256 _amount) externalonlyOwner{
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 tokenfunction_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 tofunction_payNative(uint256 _required,
uint256 _supplied,
address _receiver,
address _refundAddress
) internalvirtual{
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 truefunction_suppliedLzToken(bool _payInLzToken) internalviewreturns (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 refundedif (supplied ==0) revert Errors.LZ_ZeroLzTokenFee();
}
}
/// @dev override this if the endpoint is charging ERC20 tokens as nativefunction_suppliedNative() internalviewvirtualreturns (uint256) {
returnmsg.value;
}
/// @dev Assert the required fees and the supplied fees are enoughfunction_assertMessagingFee(
MessagingFee memory _required,
uint256 _suppliedNativeFee,
uint256 _suppliedLzTokenFee
) internalpure{
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 tokenfunctionnativeToken() externalviewvirtualreturns (address) {
returnaddress(0x0);
}
/// @notice delegate is authorized by the oapp to configure anything in layerzerofunctionsetDelegate(address _delegate) external{
delegates[msg.sender] = _delegate;
emit DelegateSet(msg.sender, _delegate);
}
// ========================= Internal =========================function_initializable(
Origin calldata _origin,
address _receiver,
uint64 _lazyInboundNonce
) internalviewreturns (bool) {
return
_lazyInboundNonce >0||// allowInitializePath already checked
ILayerZeroReceiver(_receiver).allowInitializePath(_origin);
}
/// @dev bytes(0) payloadHash can never be submittedfunction_verifiable(
Origin calldata _origin,
address _receiver,
uint64 _lazyInboundNonce
) internalviewreturns (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 delegatefunction_assertAuthorized(address _oapp) internalviewoverride(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.// ====================================================================================functioninitializable(Origin calldata _origin, address _receiver) externalviewreturns (bool) {
return _initializable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
}
functionverifiable(Origin calldata _origin, address _receiver) externalviewreturns (bool) {
return _verifiable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^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}.
*/interfaceIERC165{
/**
* @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.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 10 of 27: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (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.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (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.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
Contract Source Code
File 11 of 27: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^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.
*/interfaceIERC20Permit{
/**
* @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.
*/functionpermit(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.
*/functionnonces(address owner) externalviewreturns (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-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
Contract Source Code
File 12 of 27: ILayerZeroComposer.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.8.0;/**
* @title ILayerZeroComposer
*/interfaceILayerZeroComposer{
/**
* @notice Composes a LayerZero message from an OApp.
* @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.
*/functionlzCompose(address _from,
bytes32 _guid,
bytescalldata _message,
address _executor,
bytescalldata _extraData
) externalpayable;
}
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^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";
abstractcontractMessageLibManagerisOwnable, IMessageLibManager{
addressprivateconstant DEFAULT_LIB =address(0);
// the library that reverts both on send and quote// must be configured on construction and be immutableaddresspublicimmutable blockedLibrary;
// only registered libraries all valid libraries// the blockedLibrary will be registered on constructionaddress[] internal registeredLibraries;
mapping(address lib =>bool) public isRegisteredLibrary;
// both sendLibrary and receiveLibrary config can be lazily resolvedmapping(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);
}
modifieronlyRegistered(address _lib) {
if (!isRegisteredLibrary[_lib]) revert Errors.LZ_OnlyRegisteredLib();
_;
}
modifierisSendLib(address _lib) {
if (_lib != DEFAULT_LIB) {
if (IMessageLib(_lib).messageLibType() == MessageLibType.Receive) revert Errors.LZ_OnlySendLib();
}
_;
}
modifierisReceiveLib(address _lib) {
if (_lib != DEFAULT_LIB) {
if (IMessageLib(_lib).messageLibType() == MessageLibType.Send) revert Errors.LZ_OnlyReceiveLib();
}
_;
}
modifieronlyRegisteredOrDefault(address _lib) {
if (!isRegisteredLibrary[_lib] && _lib != DEFAULT_LIB) revert Errors.LZ_OnlyRegisteredOrDefaultLib();
_;
}
/// @dev check if the library supported the eid.modifieronlySupportedEid(address _lib, uint32 _eid) {
/// @dev doesnt need to check for default lib, because when they are initially added they get passed through this modifierif (_lib != DEFAULT_LIB) {
if (!IMessageLib(_lib).isSupportedEid(_eid)) revert Errors.LZ_UnsupportedEid();
}
_;
}
functiongetRegisteredLibraries() externalviewreturns (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 idfunctiongetSendLibrary(address _sender, uint32 _dstEid) publicviewreturns (address lib) {
lib = sendLibrary[_sender][_dstEid];
if (lib == DEFAULT_LIB) {
lib = defaultSendLibrary[_dstEid];
if (lib ==address(0x0)) revert Errors.LZ_DefaultSendLibUnavailable();
}
}
functionisDefaultSendLibrary(address _sender, uint32 _dstEid) publicviewreturns (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 LayerZerofunctiongetReceiveLibrary(address _receiver, uint32 _srcEid) publicviewreturns (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 upgradefunctionisValidReceiveLibrary(address _receiver,
uint32 _srcEid,
address _actualReceiveLib
) publicviewreturns (bool) {
// early return true if the _actualReceiveLib is the currently configured one
(address expectedReceiveLib, bool isDefault) = getReceiveLibrary(_receiver, _srcEid);
if (_actualReceiveLib == expectedReceiveLib) {
returntrue;
}
// 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 valueif (timeout.lib == _actualReceiveLib && timeout.expiry >block.number) {
// timeout lib set and has not expiredreturntrue;
}
// returns false by defaultreturnfalse;
}
//------- Owner interfaces/// @dev all libraries have to implement the erc165 interface to prevent wrong configurations/// @dev only ownerfunctionregisterLibrary(address _lib) publiconlyOwner{
// must have the right interfaceif (!IERC165(_lib).supportsInterface(type(IMessageLib).interfaceId)) revert Errors.LZ_UnsupportedInterface();
// must have not been registeredif (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 ownerfunctionsetDefaultSendLibrary(uint32 _eid,
address _newLib
) externalonlyOwneronlyRegistered(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
// must provide a different valueif (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 ownerfunctionsetDefaultReceiveLibrary(uint32 _eid,
address _newLib,
uint256 _gracePeriod
) externalonlyOwneronlyRegistered(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
address oldLib = defaultReceiveLibrary[_eid];
// must provide a different valueif (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 expiresfunctionsetDefaultReceiveLibraryTimeout(uint32 _eid,
address _lib,
uint256 _expiry
) externalonlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) onlyOwner{
if (_expiry ==0) {
// force remove the current configurationdelete defaultReceiveLibraryTimeout[_eid];
} else {
// override it with new configurationif (_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 setfunctionisSupportedEid(uint32 _eid) externalviewreturns (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 OappfunctionsetSendLibrary(address _oapp,
uint32 _eid,
address _newLib
) externalonlyRegisteredOrDefault(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
_assertAuthorized(_oapp);
// must provide a different valueif (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 expiresfunctionsetReceiveLibrary(address _oapp,
uint32 _eid,
address _newLib,
uint256 _gracePeriod
) externalonlyRegisteredOrDefault(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
_assertAuthorized(_oapp);
address oldLib = receiveLibrary[_oapp][_eid];
// must provide new valuesif (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() interfaceif (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 expiresfunctionsetReceiveLibraryTimeout(address _oapp,
uint32 _eid,
address _lib,
uint256 _expiry
) externalonlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) {
_assertAuthorized(_oapp);
(, bool isDefault) = getReceiveLibrary(_oapp, _eid);
// if current library is DEFAULT, Oapp cant set the timeoutif (isDefault) revert Errors.LZ_OnlyNonDefaultLib();
if (_expiry ==0) {
// force remove the current configurationdelete receiveLibraryTimeout[_oapp][_eid];
} else {
// override it with new configurationif (_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 _oappfunctionsetConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) externalonlyRegistered(_lib) {
_assertAuthorized(_oapp);
IMessageLib(_lib).setConfig(_oapp, _params);
}
/// @dev a view function to query the current configuration of the OAppfunctiongetConfig(address _oapp,
address _lib,
uint32 _eid,
uint32 _configType
) externalviewonlyRegistered(_lib) returns (bytesmemory config) {
return IMessageLib(_lib).getConfig(_eid, _oapp, _configType);
}
function_assertAuthorized(address _oapp) internalvirtual;
}
Contract Source Code
File 22 of 27: MessagingChannel.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { IMessagingChannel } from"./interfaces/IMessagingChannel.sol";
import { Errors } from"./libs/Errors.sol";
import { GUID } from"./libs/GUID.sol";
abstractcontractMessagingChannelisIMessagingChannel{
bytes32publicconstant EMPTY_PAYLOAD_HASH =bytes32(0);
bytes32publicconstant NIL_PAYLOAD_HASH =bytes32(type(uint256).max);
// The universally unique id (UUID) of this deployed Endpointuint32publicimmutable 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 Endpointconstructor(uint32 _eid) {
eid = _eid;
}
/// @dev increase and return the next outbound noncefunction_outbound(address _sender, uint32 _dstEid, bytes32 _receiver) internalreturns (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-resistancefunction_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] => 1functioninboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) publicviewreturns (uint64) {
uint64 nonceCursor = lazyInboundNonce[_receiver][_srcEid][_sender];
// find the effective inbound currentNonceunchecked {
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 0function_hasPayloadHash(address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce
) internalviewreturns (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 verifiedfunctionskip(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 callerfunctionnilify(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 callerfunctionburn(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 noncefunction_clearPayload(address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce,
bytesmemory _payload
) internalreturns (bytes32 actualHash) {
uint64 currentNonce = lazyInboundNonce[_receiver][_srcEid][_sender];
if (_nonce > currentNonce) {
unchecked {
// try to lazily update the inboundNonce till the _noncefor (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 storagedelete 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 casesfunctionnextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) externalviewreturns (bytes32) {
uint64 nextNonce = outboundNonce[_sender][_dstEid][_receiver] +1;
return GUID.generate(nextNonce, eid, _sender, _dstEid, _receiver);
}
function_assertAuthorized(address _oapp) internalvirtual;
}
Contract Source Code
File 23 of 27: MessagingComposer.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { IMessagingComposer } from"./interfaces/IMessagingComposer.sol";
import { ILayerZeroComposer } from"./interfaces/ILayerZeroComposer.sol";
import { Errors } from"./libs/Errors.sol";
abstractcontractMessagingComposerisIMessagingComposer{
bytes32privateconstant NO_MESSAGE_HASH =bytes32(0);
bytes32privateconstant RECEIVED_MESSAGE_HASH =bytes32(uint256(1));
mapping(addressfrom=>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 messagefunctionsendCompose(address _to, bytes32 _guid, uint16 _index, bytescalldata _message) external{
// must have not been sent beforeif (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.functionlzCompose(address _from,
address _to,
bytes32 _guid,
uint16 _index,
bytescalldata _message,
bytescalldata _extraData
) externalpayable{
// assert the validitybytes32 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 receivedfunctionlzComposeAlert(address _from,
address _to,
bytes32 _guid,
uint16 _index,
uint256 _gas,
uint256 _value,
bytescalldata _message,
bytescalldata _extraData,
bytescalldata _reason
) external{
emit LzComposeAlert(_from, _to, msg.sender, _guid, _index, _gas, _value, _message, _extraData, _reason);
}
}
Contract Source Code
File 24 of 27: MessagingContext.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^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())abstractcontractMessagingContextisIMessagingContext{
uint256privateconstant NOT_ENTERED =1;
uint256private _sendContext = NOT_ENTERED;
/// @dev the sendContext is set to 8 bytes 0s + 4 bytes eid + 20 bytes sendermodifiersendContext(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 messagefunctionisSendingMessage() publicviewreturns (bool) {
return _sendContext != NOT_ENTERED;
}
/// @dev returns (eid, sender) if sending message, (0, 0) otherwisefunctiongetSendContext() externalviewreturns (uint32, address) {
return isSendingMessage() ? _getSendContext(_sendContext) : (0, address(0));
}
function_getSendContext(uint256 _context) internalpurereturns (uint32, address) {
return (uint32(_context >>160), address(uint160(_context)));
}
}
Contract Source Code
File 25 of 27: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)pragmasolidity ^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.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed 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.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
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.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
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) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 26 of 27: SafeERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^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.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @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.
*/functionsafeTransfer(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.
*/functionsafeTransferFrom(IERC20 token, addressfrom, 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.
*/functionsafeApprove(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.
*/functionsafeIncreaseAllowance(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.
*/functionsafeDecreaseAllowance(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.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory 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.
*/functionsafePermit(
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, bytesmemory 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.bytesmemory 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, bytesmemory data) privatereturns (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, bytesmemory returndata) =address(token).call(data);
return
success && (returndata.length==0||abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}