// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.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
* ====
*
* [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// 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 39: 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));
}
}
Contract Source Code
File 3 of 39: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (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;
}
}
Contract Source Code
File 4 of 39: DoubleEndedQueue.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*/// slither-disable-next-line unused-statelibraryPanic{
/// @dev generic / unspecified erroruint256internalconstant GENERIC =0x00;
/// @dev used by the assert() builtinuint256internalconstant ASSERT =0x01;
/// @dev arithmetic underflow or overflowuint256internalconstant UNDER_OVERFLOW =0x11;
/// @dev division or modulo by zerouint256internalconstant DIVISION_BY_ZERO =0x12;
/// @dev enum conversion erroruint256internalconstant ENUM_CONVERSION_ERROR =0x21;
/// @dev invalid encoding in storageuint256internalconstant STORAGE_ENCODING_ERROR =0x22;
/// @dev empty array popuint256internalconstant EMPTY_ARRAY_POP =0x31;
/// @dev array out of bounds accessuint256internalconstant ARRAY_OUT_OF_BOUNDS =0x32;
/// @dev resource error (too large allocation or too large array)uint256internalconstant RESOURCE_ERROR =0x41;
/// @dev calling invalid internal functionuint256internalconstant INVALID_INTERNAL_FUNCTION =0x51;
/// @dev Reverts with a panic code. Recommended to use with/// the internal constants with predefined codes.functionpanic(uint256 code) internalpure{
/// @solidity memory-safe-assemblyassembly {
mstore(0x00, shl(0xe0, 0x4e487b71))
mstore(0x04, code)
revert(0x00, 0x24)
}
}
}
/**
* @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of
* the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and
* FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that
* the existing queue contents are left in storage.
*
* The struct is called `Bytes32Deque`. Other types can be cast to and from `bytes32`. This data structure can only be
* used in storage, and not in memory.
* ```solidity
* DoubleEndedQueue.Bytes32Deque queue;
* ```
*/libraryDoubleEndedQueue{
/**
* @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access.
*
* Struct members have an underscore prefix indicating that they are "private" and should not be read or written to
* directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and
* lead to unexpected behavior.
*
* The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around.
*/structBytes32Deque {
uint128 _begin;
uint128 _end;
mapping(uint128 index =>bytes32) _data;
}
/**
* @dev Inserts an item at the end of the queue.
*
* Reverts with {Panic-RESOURCE_ERROR} if the queue is full.
*/functionpushBack(Bytes32Deque storage deque, bytes32 value) internal{
unchecked {
uint128 backIndex = deque._end;
if (backIndex +1== deque._begin) Panic.panic(Panic.RESOURCE_ERROR);
deque._data[backIndex] = value;
deque._end = backIndex +1;
}
}
/**
* @dev Removes the item at the end of the queue and returns it.
*
* Reverts with {Panic-EMPTY_ARRAY_POP} if the queue is empty.
*/functionpopBack(Bytes32Deque storage deque) internalreturns (bytes32 value) {
unchecked {
uint128 backIndex = deque._end;
if (backIndex == deque._begin) Panic.panic(Panic.EMPTY_ARRAY_POP);
--backIndex;
value = deque._data[backIndex];
delete deque._data[backIndex];
deque._end = backIndex;
}
}
/**
* @dev Inserts an item at the beginning of the queue.
*
* Reverts with {Panic-RESOURCE_ERROR} if the queue is full.
*/functionpushFront(Bytes32Deque storage deque, bytes32 value) internal{
unchecked {
uint128 frontIndex = deque._begin -1;
if (frontIndex == deque._end) Panic.panic(Panic.RESOURCE_ERROR);
deque._data[frontIndex] = value;
deque._begin = frontIndex;
}
}
/**
* @dev Removes the item at the beginning of the queue and returns it.
*
* Reverts with {Panic-EMPTY_ARRAY_POP} if the queue is empty.
*/functionpopFront(Bytes32Deque storage deque) internalreturns (bytes32 value) {
unchecked {
uint128 frontIndex = deque._begin;
if (frontIndex == deque._end) Panic.panic(Panic.EMPTY_ARRAY_POP);
value = deque._data[frontIndex];
delete deque._data[frontIndex];
deque._begin = frontIndex +1;
}
}
/**
* @dev Returns the item at the beginning of the queue.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the queue is empty.
*/functionfront(Bytes32Deque storage deque) internalviewreturns (bytes32 value) {
if (empty(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
return deque._data[deque._begin];
}
/**
* @dev Returns the item at the end of the queue.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the queue is empty.
*/functionback(Bytes32Deque storage deque) internalviewreturns (bytes32 value) {
if (empty(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
unchecked {
return deque._data[deque._end -1];
}
}
/**
* @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at
* `length(deque) - 1`.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the index is out of bounds.
*/functionat(Bytes32Deque storage deque, uint256 index) internalviewreturns (bytes32 value) {
if (index >= length(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
// By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128unchecked {
return deque._data[deque._begin +uint128(index)];
}
}
/**
* @dev Resets the queue back to being empty.
*
* NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses
* out on potential gas refunds.
*/functionclear(Bytes32Deque storage deque) internal{
deque._begin =0;
deque._end =0;
}
/**
* @dev Returns the number of items in the queue.
*/functionlength(Bytes32Deque storage deque) internalviewreturns (uint256) {
unchecked {
returnuint256(deque._end - deque._begin);
}
}
/**
* @dev Returns true if the queue is empty.
*/functionempty(Bytes32Deque storage deque) internalviewreturns (bool) {
return deque._end == deque._begin;
}
}
Contract Source Code
File 5 of 39: IERC165.sol
// 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 6 of 39: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.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);
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { ILayerZeroEndpointV2 } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
/**
* @title IOAppCore
*/interfaceIOAppCore{
// Custom error messageserrorOnlyPeer(uint32 eid, bytes32 sender);
errorNoPeer(uint32 eid);
errorInvalidEndpointCall();
errorInvalidDelegate();
// Event emitted when a peer (OApp) is set for a corresponding endpointeventPeerSet(uint32 eid, bytes32 peer);
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*/functionoAppVersion() externalviewreturns (uint64 senderVersion, uint64 receiverVersion);
/**
* @notice Retrieves the LayerZero endpoint associated with the OApp.
* @return iEndpoint The LayerZero endpoint as an interface.
*/functionendpoint() externalviewreturns (ILayerZeroEndpointV2 iEndpoint);
/**
* @notice Retrieves the peer (OApp) associated with a corresponding endpoint.
* @param _eid The endpoint ID.
* @return peer The peer address (OApp instance) associated with the corresponding endpoint.
*/functionpeers(uint32 _eid) externalviewreturns (bytes32 peer);
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*/functionsetPeer(uint32 _eid, bytes32 _peer) external;
/**
* @notice Sets the delegate address for the OApp Core.
* @param _delegate The address of the delegate to be set.
*/functionsetDelegate(address _delegate) external;
}
Contract Source Code
File 16 of 39: IOAppMsgInspector.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;/**
* @title IOAppMsgInspector
* @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.
*/interfaceIOAppMsgInspector{
// Custom error message for inspection failureerrorInspectionFailed(bytes message, bytes options);
/**
* @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.
* @param _message The message payload to be inspected.
* @param _options Additional options or parameters for inspection.
* @return valid A boolean indicating whether the inspection passed (true) or failed (false).
*
* @dev Optionally done as a revert, OR use the boolean provided to handle the failure.
*/functioninspect(bytescalldata _message, bytescalldata _options) externalviewreturns (bool valid);
}
Contract Source Code
File 17 of 39: IOAppOptionsType3.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;/**
* @dev Struct representing enforced option parameters.
*/structEnforcedOptionParam {
uint32 eid; // Endpoint IDuint16 msgType; // Message Typebytes options; // Additional options
}
/**
* @title IOAppOptionsType3
* @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.
*/interfaceIOAppOptionsType3{
// Custom error message for invalid optionserrorInvalidOptions(bytes options);
// Event emitted when enforced options are seteventEnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);
/**
* @notice Sets enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*/functionsetEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OApp message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*/functioncombineOptions(uint32 _eid,
uint16 _msgType,
bytescalldata _extraOptions
) externalviewreturns (bytesmemory options);
}
Contract Source Code
File 18 of 39: IOAppPreCrimeSimulator.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;// @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.// solhint-disable-next-line no-unused-importimport { InboundPacket, Origin } from"../libs/Packet.sol";
/**
* @title IOAppPreCrimeSimulator Interface
* @dev Interface for the preCrime simulation functionality in an OApp.
*/interfaceIOAppPreCrimeSimulator{
// @dev simulation result used in PreCrime implementationerrorSimulationResult(bytes result);
errorOnlySelf();
/**
* @dev Emitted when the preCrime contract address is set.
* @param preCrimeAddress The address of the preCrime contract.
*/eventPreCrimeSet(address preCrimeAddress);
/**
* @dev Retrieves the address of the preCrime contract implementation.
* @return The address of the preCrime contract.
*/functionpreCrime() externalviewreturns (address);
/**
* @dev Retrieves the address of the OApp contract.
* @return The address of the OApp contract.
*/functionoApp() externalviewreturns (address);
/**
* @dev Sets the preCrime contract address.
* @param _preCrime The address of the preCrime contract.
*/functionsetPreCrime(address _preCrime) external;
/**
* @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.
* @param _packets An array of LayerZero InboundPacket objects representing received packets.
*/functionlzReceiveAndRevert(InboundPacket[] calldata _packets) externalpayable;
/**
* @dev checks if the specified peer is considered 'trusted' by the OApp.
* @param _eid The endpoint Id to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*/functionisPeer(uint32 _eid, bytes32 _peer) externalviewreturns (bool);
}
Contract Source Code
File 19 of 39: IOAppReceiver.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { ILayerZeroReceiver, Origin } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol";
interfaceIOAppReceiverisILayerZeroReceiver{
/**
* @notice Retrieves the address responsible for 'sending' composeMsg's to the Endpoint.
* @return sender The address responsible for 'sending' composeMsg's to the Endpoint.
*
* @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.
* @dev The default sender IS the OApp implementer.
*/functioncomposeMsgSender() externalviewreturns (address sender);
}
Contract Source Code
File 20 of 39: IOFT.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { MessagingReceipt, MessagingFee } from"../../oapp/OAppSender.sol";
/**
* @dev Struct representing token parameters for the OFT send() operation.
*/structSendParam {
uint32 dstEid; // Destination endpoint ID.bytes32 to; // Recipient address.uint256 amountLD; // Amount to send in local decimals.uint256 minAmountLD; // Minimum amount to send in local decimals.bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.bytes composeMsg; // The composed message for the send() operation.bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
/**
* @dev Struct representing OFT limit information.
* @dev These amounts can change dynamically and are up the the specific oft implementation.
*/structOFTLimit {
uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}
/**
* @dev Struct representing OFT receipt information.
*/structOFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
/**
* @dev Struct representing OFT fee details.
* @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.
*/structOFTFeeDetail {
int256 feeAmountLD; // Amount of the fee in local decimals.string description; // Description of the fee.
}
/**
* @title IOFT
* @dev Interface for the OftChain (OFT) token.
* @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
* @dev This specific interface ID is '0x02e49c2c'.
*/interfaceIOFT{
// Custom error messageserrorInvalidLocalDecimals();
errorSlippageExceeded(uint256 amountLD, uint256 minAmountLD);
// EventseventOFTSent(bytes32indexed guid, // GUID of the OFT message.uint32 dstEid, // Destination Endpoint ID.addressindexed fromAddress, // Address of the sender on the src chain.uint256 amountSentLD, // Amount of tokens sent in local decimals.uint256 amountReceivedLD // Amount of tokens received in local decimals.);
eventOFTReceived(bytes32indexed guid, // GUID of the OFT message.uint32 srcEid, // Source Endpoint ID.addressindexed toAddress, // Address of the recipient on the dst chain.uint256 amountReceivedLD // Amount of tokens received in local decimals.);
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/functionoftVersion() externalviewreturns (bytes4 interfaceId, uint64 version);
/**
* @notice Retrieves the address of the token associated with the OFT.
* @return token The address of the ERC20 token implementation.
*/functiontoken() externalviewreturns (address);
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev Allows things like wallet implementers to determine integration requirements,
* without understanding the underlying token implementation.
*/functionapprovalRequired() externalviewreturns (bool);
/**
* @notice Retrieves the shared decimals of the OFT.
* @return sharedDecimals The shared decimals of the OFT.
*/functionsharedDecimals() externalviewreturns (uint8);
/**
* @notice Provides a quote for OFT-related operations.
* @param _sendParam The parameters for the send operation.
* @return limit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return receipt The OFT receipt information.
*/functionquoteOFT(
SendParam calldata _sendParam
) externalviewreturns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return fee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/functionquoteSend(SendParam calldata _sendParam, bool _payInLzToken) externalviewreturns (MessagingFee memory);
/**
* @notice Executes the send() operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The fee information supplied by the caller.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds from fees etc. on the src.
* @return receipt The LayerZero messaging receipt from the send() operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/functionsend(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) externalpayablereturns (MessagingReceipt memory, OFTReceipt memory);
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import {DoubleEndedQueue} from"./utils/DoubleEndedQueue.sol";
import {IERC404} from"./interfaces/IERC404.sol";
import {IOFT, OFTCore} from"LayerZero-v2/oapp/contracts/oft/OFTCore.sol";
abstractcontractERC721Receiver{
functiononERC721Received(address, address, uint256, bytescalldata) externalvirtualreturns (bytes4) {
return ERC721Receiver.onERC721Received.selector;
}
}
/**
* @title O404 Contract
* @dev O404 is an ERC-404 token that extends the functionality of the OFTCore contract.
*/abstractcontractO404isOFTCore, IERC404{
usingDoubleEndedQueueforDoubleEndedQueue.Bytes32Deque;
/// @dev The queue of ERC-721 tokens stored in the contract.
DoubleEndedQueue.Bytes32Deque private _storedERC721Ids;
// //////// Events ////////// event ERC20Transfer(address indexed from, address indexed to, uint256 amount);// event Approval(address indexed owner, address indexed spender, uint256 amount);// event Transfer(address indexed from, address indexed to, uint256 indexed id);// event ERC721Approval(address indexed owner, address indexed spender, uint256 indexed id);// event ApprovalForAll(address indexed owner, address indexed operator, bool approved);// //////// Errors ////////// error NotFound();// error AlreadyExists();// error InvalidRecipient();// error InvalidSender();// error UnsafeRecipient();//////// Metadata /////////// @dev Token namestringpublic name;
/// @dev Token symbolstringpublic symbol;
/// @dev Decimals for ERC-20 representation: fixed at 18uint8publicimmutable decimals =18;
/// @dev Units for ERC-20 representation: fixed at 10^18uint256publicimmutable units =10** decimals;
/// @dev Max supply for ERC-20 representationuint256publicimmutable maxTotalSupplyERC20;
/// @dev Max supply for ERC-721 representationuint256publicimmutable maxTotalSupplyERC721;
/// @dev Total supply in ERC-20 representationuint256public totalSupply;
/// @dev Current mint counter which also represents the highest minted id, monotonically increasing to ensure accurate ownershipuint256public minted;
//////// Mappings /////////// @dev Balance of user in ERC-20 representationmapping(address=>uint256) public balanceOf;
/// @dev Allowance of user in ERC-20 representationmapping(address=>mapping(address=>uint256)) public allowance;
/// @dev Approval in ERC-721 representaionmapping(uint256=>address) public getApproved;
/// @dev Approval for all in ERC-721 representationmapping(address=>mapping(address=>bool)) public isApprovedForAll;
/// @dev Owner of id in ERC-721 representationmapping(uint256=>address) internal _ownerOf; // TODO: check/// @dev Array of owned ids in ERC-721 representationmapping(address=>uint256[]) internal _owned; // TODO: check/// @dev Tracks indices for the _owned mappingmapping(uint256=>uint256) internal _ownedIndex; // TODO: check/// @dev Addresses whitelisted from minting / burning for gas savings (pairs, routers, etc)mapping(address=>bool) public whitelist;
/**
* @dev Constructor for the OFT contract.
* @param _name The name of the OFT.
* @param _symbol The symbol of the OFT.
* @param _maxTotalSupplyERC721 Max supply for ERC-721 representation
* @param _lzEndpoint The LayerZero endpoint address.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/constructor(stringmemory _name,
stringmemory _symbol,
uint256 _maxTotalSupplyERC721,
address _lzEndpoint,
address _delegate
) OFTCore(decimals, _lzEndpoint, _delegate) {
name = _name;
symbol = _symbol;
maxTotalSupplyERC721 = _maxTotalSupplyERC721;
maxTotalSupplyERC20 = maxTotalSupplyERC721 * units;
}
//////////////////////////////////////////////////////////////////////////////////////// OFT FUNCTIONS/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/functionoftVersion() externalpurevirtualreturns (bytes4 interfaceId, uint64 version) {
return (type(IOFT).interfaceId, 1);
}
/**
* @dev Retrieves the address of the underlying ERC20 implementation.
* @return The address of the OFT token.
*
* @dev In the case of OFT, address(this) and erc20 are the same contract.
*/functiontoken() externalviewreturns (address) {
returnaddress(this);
}
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev In the case of OFT where the contract IS the token, approval is NOT required.
*/functionapprovalRequired() externalpurevirtualreturns (bool) {
returnfalse;
}
/**
* @dev Burns tokens from the sender's specified balance.
* @param _amountLD The amount of tokens to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination chain ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*/function_debit(uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid)
internalvirtualoverridereturns (uint256 amountSentLD, uint256 amountReceivedLD)
{
(amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);
// @dev In NON-default OFT, amountSentLD could be 100, with a 10% fee, the amountReceivedLD amount is 90,// therefore amountSentLD CAN differ from amountReceivedLD.// @dev Default OFT burns on src.
_burnERC20(msg.sender, amountSentLD);
}
/**
* @dev Credits tokens to the specified address.
* @param _to The address to credit the tokens to.
* @param _amountLD The amount of tokens to credit in local decimals.
* @dev _srcEid The source chain ID.
* @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals.
*/function_credit(address _to, uint256 _amountLD, uint32/*_srcEid*/)
internalvirtualoverridereturns (uint256 amountReceivedLD)
{
// @dev Default OFT mints on dst.
_mintERC20(_to, _amountLD);
// @dev In the case of NON-default OFT, the _amountLD MIGHT not be == amountReceivedLD.return _amountLD;
}
//////////////////////////////////////////////////////////////////////////////////////// ERC404 FUNCTIONS/// @notice Function to find owner of a given ERC-721 tokenfunctionownerOf(uint256 id_) publicviewvirtualreturns (address nftOwner) {
nftOwner = _ownerOf[id_];
// If the id_ is beyond the range of ERC-721 supply, is 0, or the token is not owned by anyone, revert.if (id_ > maxTotalSupplyERC721 || id_ ==0|| nftOwner ==address(0)) {
revert NotFound();
}
}
functionerc721BalanceOf(address owner_) publicviewvirtualreturns (uint256) {
return _owned[owner_].length;
}
functionerc20BalanceOf(address owner_) publicviewvirtualreturns (uint256) {
return balanceOf[owner_];
}
/// @notice Function for token approvals/// @dev This function assumes the operator is attempting to approve an ERC-721 if valueOrId is less than the minted count. Note: Unlike setApprovalForAll, spender_ must be allowed to be 0x0 so that approval can be revoked.functionapprove(address spender_, uint256 valueOrId_) publicvirtualreturns (bool) {
// The ERC-721 tokens are 1-indexed, so 0 is not a valid id and indicates that operator is attempting to set the ERC-20 allowance to 0.if (valueOrId_ <= maxTotalSupplyERC721 && valueOrId_ >0) {
// Intention is to approve as ERC-721 token (id).uint256 id = valueOrId_;
address nftOwner = _ownerOf[id];
if (msg.sender!= nftOwner &&!isApprovedForAll[nftOwner][msg.sender]) {
revert Unauthorized();
}
getApproved[id] = spender_;
emit Approval(nftOwner, spender_, id);
emit ERC721Approval(nftOwner, spender_, id);
} else {
// Intention is to approve as ERC-20 token (value).uint256 value = valueOrId_;
allowance[msg.sender][spender_] = value;
emit Approval(msg.sender, spender_, value);
emit ERC20Approval(msg.sender, spender_, value);
}
returntrue;
}
/// @notice Function for ERC-721 approvalsfunctionsetApprovalForAll(address operator_, bool approved_) publicvirtual{
// Prevent approvals to 0x0.if (operator_ ==address(0)) {
revert InvalidOperator();
}
isApprovedForAll[msg.sender][operator_] = approved_;
emit ApprovalForAll(msg.sender, operator_, approved_);
}
/// @notice Function for mixed transfers from an operator that may be different than 'from'./// @dev This function assumes the operator is attempting to transfer an ERC-721 if valueOrId is less than or equal to current max id.functiontransferFrom(address from_, address to_, uint256 valueOrId_) publicvirtualreturns (bool) {
// Prevent burning tokens to the 0 address.// TODO: removeif (to_ ==address(0)) {
revert InvalidRecipient();
}
if (valueOrId_ <= maxTotalSupplyERC721) {
// Intention is to transfer as ERC-721 token (id).uint256 id = valueOrId_;
if (from_ != _ownerOf[id]) {
revert InvalidSender();
}
// Check that the operator is approved for the transfer.if (msg.sender!= from_ &&!isApprovedForAll[from_][msg.sender] &&msg.sender!= getApproved[id]) {
revert Unauthorized();
}
// Transfer 1 * units ERC-20 and 1 ERC-721 token.
_transferERC20(from_, to_, units);
_transferERC721(from_, to_, id);
} else {
// Intention is to transfer as ERC-20 token (value).uint256 value = valueOrId_;
uint256 allowed = allowance[from_][msg.sender];
// Check that the operator has sufficient allowance.if (allowed !=type(uint256).max) {
if (allowed < value) {
revert InsufficientAllowance();
}
allowance[from_][msg.sender] = allowed - value;
}
// Transferring ERC-20s directly requires the _transfer function.
_transfer(from_, to_, value);
}
returntrue;
}
/// @notice Function for mixed transfers./// @dev This function assumes the operator is attempting to transfer an ERC-721 if valueOrId is lte the highest minted ERC-721 id.functiontransfer(address to_, uint256 valueOrId_) publicvirtualreturns (bool) {
// Prevent burning tokens to the 0 address.if (to_ ==address(0)) {
revert InvalidRecipient();
}
if (valueOrId_ <= maxTotalSupplyERC721) {
// Intention is to transfer as ERC-721 token (id).uint256 id = valueOrId_;
if (msg.sender!= _ownerOf[id]) {
revert Unauthorized();
}
// Transfer 1 * units ERC-20 and 1 ERC-721 token.// This this path is used to ensure the exact ERC-721 specified is transferred.
_transferERC20(msg.sender, to_, units);
_transferERC721(msg.sender, to_, id);
} else {
// Intention is to transfer as ERC-20 token (value).uint256 value = valueOrId_;
// Transferring ERC-20s directly requires the _transfer function.
_transfer(msg.sender, to_, value);
}
returntrue;
}
/// @notice Function for ERC-721 transfers with contract support.functionsafeTransferFrom(address from_, address to_, uint256 id_) publicvirtual{
transferFrom(from_, to_, id_);
if (
to_.code.length!=0&& ERC721Receiver(to_).onERC721Received(msg.sender, from_, id_, "")
!= ERC721Receiver.onERC721Received.selector
) {
revert UnsafeRecipient();
}
}
/// @notice Function for ERC-721 transfers with contract support and callback data.functionsafeTransferFrom(address from_, address to_, uint256 id_, bytescalldata data_) publicvirtual{
transferFrom(from_, to_, id_);
if (
to_.code.length!=0&& ERC721Receiver(to_).onERC721Received(msg.sender, from_, id_, data_)
!= ERC721Receiver.onERC721Received.selector
) {
revert UnsafeRecipient();
}
}
/// @notice This is the lowest level ERC-20 transfer function, which should be used for both normal ERC-20 transfers as well as minting./// Note that this function allows transfers to and from 0x0.function_transferERC20(address from_, address to_, uint256 value_) internalvirtual{
// Minting is a special case for which we should not check the balance of the sender, and we should increase the total supply.if (from_ ==address(0)) {
if (totalSupply + value_ > maxTotalSupplyERC20) {
revert MaxERC20SupplyReached();
}
unchecked {
totalSupply += value_;
}
} else {
// For transfers not from the 0x0 address, check for insufficient balance.if (balanceOf[from_] < value_) {
revert InsufficientBalance();
}
// Deduct value from sender's balance.
balanceOf[from_] -= value_;
// If the recipient is the 0x0 address, burn the tokens.if (to_ ==address(0)) {
// Burning is a special case for which we should decrease the total supply.unchecked {
totalSupply -= value_;
}
}
}
// If this is not a burnif (to_ !=address(0)) {
// Update the recipient's balance.unchecked {
balanceOf[to_] += value_;
}
}
emit Transfer(from_, to_, value_);
emit ERC20Transfer(from_, to_, value_);
}
/// @notice Consolidated record keeping function for transferring ERC-721s./// @dev Assign the token to the new owner, and remove from the old owner./// Note that this function allows transfers to and from 0x0.function_transferERC721(address from_, address to_, uint256 id_) internalvirtual{
// If this is not a mint, handle record keeping for transfer from previous owner.if (from_ !=address(0)) {
// On transfer of an NFT, any previous approval is reset.delete getApproved[id_];
// update _owned for senderuint256 updatedId = _owned[from_][_owned[from_].length-1];
_owned[from_][_ownedIndex[id_]] = updatedId;
// pop
_owned[from_].pop();
// update index for the moved id
_ownedIndex[updatedId] = _ownedIndex[id_];
}
// Update owner of the token to the new owner.
_ownerOf[id_] = to_;
// Push token onto the new owner's stack.
_owned[to_].push(id_);
// Update index for new owner's stack.
_ownedIndex[id_] = _owned[to_].length-1;
emit Transfer(from_, to_, id_);
emit ERC721Transfer(from_, to_, id_);
}
/// @notice Internal function for ERC-20 transfers./// Also handles any ERC-721 transfers that may be required.function_transfer(addressfrom, address to, uint256 amount) internalreturns (bool) {
uint256 erc20BalanceOfSenderBefore = erc20BalanceOf(from);
uint256 erc20BalanceOfReceiverBefore = erc20BalanceOf(to);
_transferERC20(from, to, amount);
// Skip burn for certain addresses to save gasif (!whitelist[from]) {
uint256 num721ToBurn = (erc20BalanceOfSenderBefore / units) - (balanceOf[from] / units);
for (uint256 i =0; i < num721ToBurn; i++) {
_burnERC721(from);
}
}
// Skip minting for certain addresses to save gasif (!whitelist[to]) {
uint256 num721ToMint = (balanceOf[to] / units) - (erc20BalanceOfReceiverBefore / units);
for (uint256 i =0; i < num721ToMint; i++) {
_mintERC721(to);
}
}
returntrue;
}
/// @notice Internal function for ERC20 minting/// @dev This function will allow minting of new ERC20s up to the maxTotalSupplyERC20.function_mintERC20(address to_, uint256 value_) internalvirtual{
/// You cannot mint to the zero address (you can't mint and immediately burn in the same transfer).if (to_ ==address(0)) {
revert InvalidRecipient();
}
uint256 erc20BalanceOfReceiverBefore = erc20BalanceOf(to_);
_transferERC20(address(0), to_, value_);
if (!whitelist[to_]) {
uint256 num721ToMint = (balanceOf[to_] / units) - (erc20BalanceOfReceiverBefore / units);
for (uint256 i =0; i < num721ToMint; i++) {
_mintERC721(to_);
}
}
}
function_burnERC20(address from_, uint256 value_) internalvirtual{
/// You cannot mint to the zero address (you can't mint and immediately burn in the same transfer).if (from_ ==address(0)) {
revert InvalidSender();
}
uint256 erc20BalanceOfSenderBefore = erc20BalanceOf(from_);
_transferERC20(from_, address(0), value_);
// Skip burn for certain addresses to save gasif (!whitelist[from_]) {
uint256 num721ToBurn = (erc20BalanceOfSenderBefore / units) - (balanceOf[from_] / units);
for (uint256 i =0; i < num721ToBurn; i++) {
_burnERC721(from_);
}
}
}
/// @notice Internal function for ERC-721 minting and retrieval from the bank./// @dev This function will allow minting of new ERC-721s up to the maxTotalSupplyERC20. It will first try to pull from the bank, and if the bank is empty, it will mint a new token.function_mintERC721(address to_) internalvirtual{
if (to_ ==address(0) || to_ ==address(this)) {
revert InvalidRecipient();
}
uint256 id;
if (!DoubleEndedQueue.empty(_storedERC721Ids)) {
// If there are any tokens in the bank, use those.
id =uint256(_storedERC721Ids.popBack());
} else {
// Otherwise, mint a new token.
minted++;
id = minted;
if (minted > maxTotalSupplyERC721) {
revert MaxERC721SupplyReached();
}
}
address nftOwner = _ownerOf[id];
// The token should not already belong to anyone besides 0x0 or this contract. If it does, something is wrong, as this should never happen.if (nftOwner !=address(0) && nftOwner !=address(this)) {
revert AlreadyExists();
}
// Transfer the token to the recipient, either transferring from the contract's bank or minting.
_transferERC721(nftOwner, to_, id);
}
/// @notice Internal function for ERC-721 deposits to bank (this contract)./// @dev This function will allow depositing of ERC-721s to the bank, which can be retrieved by future minters.function_burnERC721(address from_) internalvirtual{
if (from_ ==address(0) || from_ ==address(this)) {
revert InvalidSender();
}
// Retrieve the latest token added to the owner's stack (LIFO).uint256 id = _owned[from_][_owned[from_].length-1];
// Transfer the token to the contract.
_transferERC721(from_, address(this), id); // TODO: should this be set to address(0) ?// Record the token in the contract's bank queue.
_storedERC721Ids.pushFront(bytes32(id));
}
/// @notice Initialization function to set pairs / etc, saving gas by avoiding mint / burn on unnecessary targetsfunction_setWhitelist(address target_, bool state_) internalvirtual{
// If the target has at least 1 full ERC-20 token, they should not be removed from the whitelist because if they were and then they attempted to transfer, it would revert as they would not necessarily have ehough ERC-721s to bank.if (erc20BalanceOf(target_) >= units &&!state_) {
revert CannotRemoveFromWhitelist();
}
whitelist[target_] = state_;
}
}
Contract Source Code
File 24 of 39: OApp.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers// solhint-disable-next-line no-unused-importimport { OAppSender, MessagingFee, MessagingReceipt } from"./OAppSender.sol";
// @dev Import the 'Origin' so it's exposed to OApp implementers// solhint-disable-next-line no-unused-importimport { OAppReceiver, Origin } from"./OAppReceiver.sol";
import { OAppCore } from"./OAppCore.sol";
/**
* @title OApp
* @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.
*/abstractcontractOAppisOAppSender, OAppReceiver{
/**
* @dev Constructor to initialize the OApp with the provided endpoint and owner.
* @param _endpoint The address of the LOCAL LayerZero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol implementation.
* @return receiverVersion The version of the OAppReceiver.sol implementation.
*/functionoAppVersion()
publicpurevirtualoverride(OAppSender, OAppReceiver)
returns (uint64 senderVersion, uint64 receiverVersion)
{
return (SENDER_VERSION, RECEIVER_VERSION);
}
}
Contract Source Code
File 25 of 39: OAppCore.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { Ownable } from"@openzeppelin/contracts/access/Ownable.sol";
import { IOAppCore, ILayerZeroEndpointV2 } from"./interfaces/IOAppCore.sol";
/**
* @title OAppCore
* @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
*/abstractcontractOAppCoreisIOAppCore, Ownable{
// The LayerZero endpoint associated with the given OApp
ILayerZeroEndpointV2 publicimmutable endpoint;
// Mapping to store peers associated with corresponding endpointsmapping(uint32 eid =>bytes32 peer) public peers;
/**
* @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
* @param _endpoint The address of the LOCAL Layer Zero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
*/constructor(address _endpoint, address _delegate) {
endpoint = ILayerZeroEndpointV2(_endpoint);
if (_delegate ==address(0)) revert InvalidDelegate();
endpoint.setDelegate(_delegate);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/functionsetPeer(uint32 _eid, bytes32 _peer) publicvirtualonlyOwner{
peers[_eid] = _peer;
emit PeerSet(_eid, _peer);
}
/**
* @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
* ie. the peer is set to bytes32(0).
* @param _eid The endpoint ID.
* @return peer The address of the peer associated with the specified endpoint.
*/function_getPeerOrRevert(uint32 _eid) internalviewvirtualreturns (bytes32) {
bytes32 peer = peers[_eid];
if (peer ==bytes32(0)) revert NoPeer(_eid);
return peer;
}
/**
* @notice Sets the delegate address for the OApp.
* @param _delegate The address of the delegate to be set.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
*/functionsetDelegate(address _delegate) publiconlyOwner{
endpoint.setDelegate(_delegate);
}
}
Contract Source Code
File 26 of 39: OAppOptionsType3.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { Ownable } from"@openzeppelin/contracts/access/Ownable.sol";
import { IOAppOptionsType3, EnforcedOptionParam } from"../interfaces/IOAppOptionsType3.sol";
/**
* @title OAppOptionsType3
* @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.
*/abstractcontractOAppOptionsType3isIOAppOptionsType3, Ownable{
uint16internalconstant OPTION_TYPE_3 =3;
// @dev The "msgType" should be defined in the child contract.mapping(uint32 eid =>mapping(uint16 msgType =>bytes enforcedOption)) public enforcedOptions;
/**
* @dev Sets the enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
* @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
* eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
* if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
*/functionsetEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) publicvirtualonlyOwner{
for (uint256 i =0; i < _enforcedOptions.length; i++) {
// @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.
_assertOptionsType3(_enforcedOptions[i].options);
enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;
}
emit EnforcedOptionSet(_enforcedOptions);
}
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OAPP message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*
* @dev If there is an enforced lzReceive option:
* - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}
* - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.
* @dev This presence of duplicated options is handled off-chain in the verifier/executor.
*/functioncombineOptions(uint32 _eid,
uint16 _msgType,
bytescalldata _extraOptions
) publicviewvirtualreturns (bytesmemory) {
bytesmemory enforced = enforcedOptions[_eid][_msgType];
// No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.if (enforced.length==0) return _extraOptions;
// No caller options, return enforcedif (_extraOptions.length==0) return enforced;
// @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.if (_extraOptions.length>=2) {
_assertOptionsType3(_extraOptions);
// @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.returnbytes.concat(enforced, _extraOptions[2:]);
}
// No valid set of options was found.revert InvalidOptions(_extraOptions);
}
/**
* @dev Internal function to assert that options are of type 3.
* @param _options The options to be checked.
*/function_assertOptionsType3(bytescalldata _options) internalpurevirtual{
uint16 optionsType =uint16(bytes2(_options[0:2]));
if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);
}
}
Contract Source Code
File 27 of 39: OAppPreCrimeSimulator.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { Ownable } from"@openzeppelin/contracts/access/Ownable.sol";
import { IPreCrime } from"./interfaces/IPreCrime.sol";
import { IOAppPreCrimeSimulator, InboundPacket, Origin } from"./interfaces/IOAppPreCrimeSimulator.sol";
/**
* @title OAppPreCrimeSimulator
* @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.
*/abstractcontractOAppPreCrimeSimulatorisIOAppPreCrimeSimulator, Ownable{
// The address of the preCrime implementation.addresspublic preCrime;
/**
* @dev Retrieves the address of the OApp contract.
* @return The address of the OApp contract.
*
* @dev The simulator contract is the base contract for the OApp by default.
* @dev If the simulator is a separate contract, override this function.
*/functionoApp() externalviewvirtualreturns (address) {
returnaddress(this);
}
/**
* @dev Sets the preCrime contract address.
* @param _preCrime The address of the preCrime contract.
*/functionsetPreCrime(address _preCrime) publicvirtualonlyOwner{
preCrime = _preCrime;
emit PreCrimeSet(_preCrime);
}
/**
* @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.
* @param _packets An array of InboundPacket objects representing received packets to be delivered.
*
* @dev WARNING: MUST revert at the end with the simulation results.
* @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,
* WITHOUT actually executing them.
*/functionlzReceiveAndRevert(InboundPacket[] calldata _packets) publicpayablevirtual{
for (uint256 i =0; i < _packets.length; i++) {
InboundPacket calldata packet = _packets[i];
// Ignore packets that are not from trusted peers.if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;
// @dev Because a verifier is calling this function, it doesnt have access to executor params:// - address _executor// - bytes calldata _extraData// preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().// They are instead stubbed to default values, address(0) and bytes("")// @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,// which would cause the revert to be ignored.this.lzReceiveSimulate{ value: packet.value }(
packet.origin,
packet.guid,
packet.message,
packet.executor,
packet.extraData
);
}
// @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());
}
/**
* @dev Is effectively an internal function because msg.sender must be address(this).
* Allows resetting the call stack for 'internal' calls.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier of the packet.
* @param _message The message payload of the packet.
* @param _executor The executor address for the packet.
* @param _extraData Additional data for the packet.
*/functionlzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytescalldata _message,
address _executor,
bytescalldata _extraData
) externalpayablevirtual{
// @dev Ensure ONLY can be called 'internally'.if (msg.sender!=address(this)) revert OnlySelf();
_lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The GUID of the LayerZero message.
* @param _message The LayerZero message.
* @param _executor The address of the off-chain executor.
* @param _extraData Arbitrary data passed by the msg executor.
*
* @dev Enables the preCrime simulator to mock sending lzReceive() messages,
* routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
*/function_lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytescalldata _message,
address _executor,
bytescalldata _extraData
) internalvirtual;
/**
* @dev checks if the specified peer is considered 'trusted' by the OApp.
* @param _eid The endpoint Id to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*/functionisPeer(uint32 _eid, bytes32 _peer) publicviewvirtualreturns (bool);
}
Contract Source Code
File 28 of 39: OAppReceiver.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { IOAppReceiver, Origin } from"./interfaces/IOAppReceiver.sol";
import { OAppCore } from"./OAppCore.sol";
/**
* @title OAppReceiver
* @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.
*/abstractcontractOAppReceiverisIOAppReceiver, OAppCore{
// Custom error message for when the caller is not the registered endpoint/errorOnlyEndpoint(address addr);
// @dev The version of the OAppReceiver implementation.// @dev Version is bumped when changes are made to this contract.uint64internalconstant RECEIVER_VERSION =1;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.
* ie. this is a RECEIVE only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.
*/functionoAppVersion() publicviewvirtualreturns (uint64 senderVersion, uint64 receiverVersion) {
return (0, RECEIVER_VERSION);
}
/**
* @notice Retrieves the address responsible for 'sending' composeMsg's to the Endpoint.
* @return sender The address responsible for 'sending' composeMsg's to the Endpoint.
*
* @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.
* @dev The default sender IS the OApp implementer.
*/functioncomposeMsgSender() publicviewvirtualreturns (address sender) {
returnaddress(this);
}
/**
* @notice Checks if the path initialization is allowed based on the provided origin.
* @param origin The origin information containing the source endpoint and sender address.
* @return Whether the path has been initialized.
*
* @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.
* @dev This defaults to assuming if a peer has been set, its initialized.
* Can be overridden by the OApp if there is other logic to determine this.
*/functionallowInitializePath(Origin calldata origin) publicviewvirtualreturns (bool) {
return peers[origin.srcEid] == origin.sender;
}
/**
* @notice Retrieves the next nonce for a given source endpoint and sender address.
* @dev _srcEid The source endpoint ID.
* @dev _sender The sender address.
* @return nonce The next nonce.
*
* @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
* @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
* @dev This is also enforced by the OApp.
* @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
*/functionnextNonce(uint32/*_srcEid*/, bytes32/*_sender*/) publicviewvirtualreturns (uint64 nonce) {
return0;
}
/**
* @dev Entry point for receiving messages or packets from the endpoint.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The payload of the received message.
* @param _executor The address of the executor for the received message.
* @param _extraData Additional arbitrary data provided by the corresponding executor.
*
* @dev Entry point for receiving msg/packet from the LayerZero endpoint.
*/functionlzReceive(
Origin calldata _origin,
bytes32 _guid,
bytescalldata _message,
address _executor,
bytescalldata _extraData
) publicpayablevirtual{
// Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.if (address(endpoint) !=msg.sender) revert OnlyEndpoint(msg.sender);
// Ensure that the sender matches the expected peer for the source endpoint.if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);
// Call the internal OApp implementation of lzReceive.
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.
*/function_lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytescalldata _message,
address _executor,
bytescalldata _extraData
) internalvirtual;
}
Contract Source Code
File 29 of 39: OAppSender.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { SafeERC20, IERC20 } from"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessagingParams, MessagingFee, MessagingReceipt } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { OAppCore } from"./OAppCore.sol";
/**
* @title OAppSender
* @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
*/abstractcontractOAppSenderisOAppCore{
usingSafeERC20forIERC20;
// Custom error messageserrorNotEnoughNative(uint256 msgValue);
errorLzTokenUnavailable();
// @dev The version of the OAppSender implementation.// @dev Version is bumped when changes are made to this contract.uint64internalconstant SENDER_VERSION =1;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
* ie. this is a SEND only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
*/functionoAppVersion() publicviewvirtualreturns (uint64 senderVersion, uint64 receiverVersion) {
return (SENDER_VERSION, 0);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
* @return fee The calculated MessagingFee for the message.
* - nativeFee: The native fee for the message.
* - lzTokenFee: The LZ token fee for the message.
*/function_quote(uint32 _dstEid,
bytesmemory _message,
bytesmemory _options,
bool _payInLzToken
) internalviewvirtualreturns (MessagingFee memory fee) {
return
endpoint.quote(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
address(this)
);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _fee The calculated LayerZero fee for the message.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess fee values sent to the endpoint.
* @return receipt The receipt for the sent message.
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/function_lzSend(uint32 _dstEid,
bytesmemory _message,
bytesmemory _options,
MessagingFee memory _fee,
address _refundAddress
) internalvirtualreturns (MessagingReceipt memory receipt) {
// @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.uint256 messageValue = _payNative(_fee.nativeFee);
if (_fee.lzTokenFee >0) _payLzToken(_fee.lzTokenFee);
return// solhint-disable-next-line check-send-result
endpoint.send{ value: messageValue }(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee >0),
_refundAddress
);
}
/**
* @dev Internal function to pay the native fee associated with the message.
* @param _nativeFee The native fee to be paid.
* @return nativeFee The amount of native currency paid.
*
* @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
* this will need to be overridden because msg.value would contain multiple lzFees.
* @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
* @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
* @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
*/function_payNative(uint256 _nativeFee) internalvirtualreturns (uint256 nativeFee) {
if (msg.value!= _nativeFee) revert NotEnoughNative(msg.value);
return _nativeFee;
}
/**
* @dev Internal function to pay the LZ token fee associated with the message.
* @param _lzTokenFee The LZ token fee to be paid.
*
* @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
* @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
*/function_payLzToken(uint256 _lzTokenFee) internalvirtual{
// @dev Cannot cache the token because it is not immutable in the endpoint.address lzToken = endpoint.lzToken();
if (lzToken ==address(0)) revert LzTokenUnavailable();
// Pay LZ token fee by sending tokens to the endpoint.
IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
}
}
Contract Source Code
File 30 of 39: OFTComposeMsgCodec.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;libraryOFTComposeMsgCodec{
// Offset constants for decoding composed messagesuint8privateconstant NONCE_OFFSET =8;
uint8privateconstant SRC_EID_OFFSET =12;
uint8privateconstant AMOUNT_LD_OFFSET =44;
uint8privateconstant COMPOSE_FROM_OFFSET =76;
/**
* @dev Encodes a OFT composed message.
* @param _nonce The nonce value.
* @param _srcEid The source endpoint ID.
* @param _amountLD The amount in local decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded Composed message.
*/functionencode(uint64 _nonce,
uint32 _srcEid,
uint256 _amountLD,
bytesmemory _composeMsg // 0x[composeFrom][composeMsg]) internalpurereturns (bytesmemory _msg) {
_msg =abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);
}
/**
* @dev Retrieves the nonce from the composed message.
* @param _msg The message.
* @return The nonce value.
*/functionnonce(bytescalldata _msg) internalpurereturns (uint64) {
returnuint64(bytes8(_msg[:NONCE_OFFSET]));
}
/**
* @dev Retrieves the source endpoint ID from the composed message.
* @param _msg The message.
* @return The source endpoint ID.
*/functionsrcEid(bytescalldata _msg) internalpurereturns (uint32) {
returnuint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
}
/**
* @dev Retrieves the amount in local decimals from the composed message.
* @param _msg The message.
* @return The amount in local decimals.
*/functionamountLD(bytescalldata _msg) internalpurereturns (uint256) {
returnuint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));
}
/**
* @dev Retrieves the composeFrom value from the composed message.
* @param _msg The message.
* @return The composeFrom value.
*/functioncomposeFrom(bytescalldata _msg) internalpurereturns (bytes32) {
returnbytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);
}
/**
* @dev Retrieves the composed message.
* @param _msg The message.
* @return The composed message.
*/functioncomposeMsg(bytescalldata _msg) internalpurereturns (bytesmemory) {
return _msg[COMPOSE_FROM_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/functionaddressToBytes32(address _addr) internalpurereturns (bytes32) {
returnbytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/functionbytes32ToAddress(bytes32 _b) internalpurereturns (address) {
returnaddress(uint160(uint256(_b)));
}
}
Contract Source Code
File 31 of 39: OFTCore.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { OApp, Origin } from"../oapp/OApp.sol";
import { OAppOptionsType3 } from"../oapp/libs/OAppOptionsType3.sol";
import { IOAppMsgInspector } from"../oapp/interfaces/IOAppMsgInspector.sol";
import { OAppPreCrimeSimulator } from"../precrime/OAppPreCrimeSimulator.sol";
import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from"./interfaces/IOFT.sol";
import { OFTMsgCodec } from"./libs/OFTMsgCodec.sol";
import { OFTComposeMsgCodec } from"./libs/OFTComposeMsgCodec.sol";
/**
* @title OFTCore
* @dev Abstract contract for the OftChain (OFT) token.
*/abstractcontractOFTCoreisIOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3{
usingOFTMsgCodecforbytes;
usingOFTMsgCodecforbytes32;
// @notice Provides a conversion rate when swapping between denominations of SD and LD// - shareDecimals == SD == shared Decimals// - localDecimals == LD == local decimals// @dev Considers that tokens have different decimal amounts on various chains.// @dev eg.// For a token// - locally with 4 decimals --> 1.2345 => uint(12345)// - remotely with 2 decimals --> 1.23 => uint(123)// - The conversion rate would be 10 ** (4 - 2) = 100// @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote,// you can only display 1.23 -> uint(123).// @dev To preserve the dust that would otherwise be lost on that conversion,// we need to unify a denomination that can be represented on ALL chains inside of the OFT meshuint256publicimmutable decimalConversionRate;
// @notice Msg types that are used to identify the various OFT operations.// @dev This can be extended in child contracts for non-default oft operations// @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.uint16publicconstant SEND =1;
uint16publicconstant SEND_AND_CALL =2;
// Address of an optional contract to inspect both 'message' and 'options'addresspublic msgInspector;
eventMsgInspectorSet(address inspector);
/**
* @dev Constructor.
* @param _localDecimals The decimals of the token on the local chain (this chain).
* @param _endpoint The address of the LayerZero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) {
if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals();
decimalConversionRate =10** (_localDecimals - sharedDecimals());
}
/**
* @dev Retrieves the shared decimals of the OFT.
* @return The shared decimals of the OFT.
*
* @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap
* Lowest common decimal denominator between chains.
* Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64).
* For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller.
* ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615
*/functionsharedDecimals() publicpurevirtualreturns (uint8) {
return6;
}
/**
* @dev Sets the message inspector address for the OFT.
* @param _msgInspector The address of the message inspector.
*
* @dev This is an optional contract that can be used to inspect both 'message' and 'options'.
* @dev Set it to address(0) to disable it, or set it to a contract address to enable it.
*/functionsetMsgInspector(address _msgInspector) publicvirtualonlyOwner{
msgInspector = _msgInspector;
emit MsgInspectorSet(_msgInspector);
}
/**
* @notice Provides a quote for OFT-related operations.
* @param _sendParam The parameters for the send operation.
* @return oftLimit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return oftReceipt The OFT receipt information.
*/functionquoteOFT(
SendParam calldata _sendParam
)
externalviewvirtualreturns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)
{
uint256 minAmountLD =0; // Unused in the default implementation.uint256 maxAmountLD =type(uint64).max; // Unused in the default implementation.
oftLimit = OFTLimit(minAmountLD, maxAmountLD);
// Unused in the default implementation; reserved for future complex fee details.
oftFeeDetails =new OFTFeeDetail[](0);
// @dev This is the same as the send() operation, but without the actual send.// - amountSentLD is the amount in local decimals that would be sent from the sender.// - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.// @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.
(uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(
_sendParam.amountLD,
_sendParam.minAmountLD,
_sendParam.dstEid
);
oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
}
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return msgFee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/functionquoteSend(
SendParam calldata _sendParam,
bool _payInLzToken
) externalviewvirtualreturns (MessagingFee memory msgFee) {
// @dev mock the amount to receive, this is the same operation used in the send().// The quote is as similar as possible to the actual send() operation.
(, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid);
// @dev Builds the options and OFT message to quote in the endpoint.
(bytesmemory message, bytesmemory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);
// @dev Calculates the LayerZero fee for the send() operation.return _quote(_sendParam.dstEid, message, options, _payInLzToken);
}
/**
* @dev Executes the send operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The calculated fee for the send() operation.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds.
* @return msgReceipt The receipt for the send operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/functionsend(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) externalpayablevirtualreturns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {
// @dev Applies the token transfers regarding this send() operation.// - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender.// - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance.
(uint256 amountSentLD, uint256 amountReceivedLD) = _debit(
_sendParam.amountLD,
_sendParam.minAmountLD,
_sendParam.dstEid
);
// @dev Builds the options and OFT message to quote in the endpoint.
(bytesmemory message, bytesmemory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);
// @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.
msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);
// @dev Formulate the OFT receipt.
oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD);
}
/**
* @dev Internal function to build the message and options.
* @param _sendParam The parameters for the send() operation.
* @param _amountLD The amount in local decimals.
* @return message The encoded message.
* @return options The encoded options.
*/function_buildMsgAndOptions(
SendParam calldata _sendParam,
uint256 _amountLD
) internalviewvirtualreturns (bytesmemory message, bytesmemory options) {
bool hasCompose;
// @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is.
(message, hasCompose) = OFTMsgCodec.encode(
_sendParam.to,
_toSD(_amountLD),
// @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote.// EVEN if you dont require an arbitrary payload to be sent... eg. '0x01'
_sendParam.composeMsg
);
// @dev Change the msg type depending if its composed or not.uint16 msgType = hasCompose ? SEND_AND_CALL : SEND;
// @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3.
options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);
// @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.// @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return booleanif (msgInspector !=address(0)) IOAppMsgInspector(msgInspector).inspect(message, options);
}
/**
* @dev Internal function to handle the receive on the LayerZero endpoint.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The encoded message.
* @dev _executor The address of the executor.
* @dev _extraData Additional data.
*/function_lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytescalldata _message,
address/*_executor*/, // @dev unused in the default implementation.bytescalldata/*_extraData*/// @dev unused in the default implementation.) internalvirtualoverride{
// @dev The src sending chain doesnt know the address length on this chain (potentially non-evm)// Thus everything is bytes32() encoded in flight.address toAddress = _message.sendTo().bytes32ToAddress();
// @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimalsuint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid);
if (_message.isComposed()) {
// @dev Proprietary composeMsg format for the OFT.bytesmemory composeMsg = OFTComposeMsgCodec.encode(
_origin.nonce,
_origin.srcEid,
amountReceivedLD,
_message.composeMsg()
);
// @dev Stores the lzCompose payload that will be executed in a separate tx.// Standardizes functionality for executing arbitrary contract invocation on some non-evm chains.// @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed.// @dev The index is used when a OApp needs to compose multiple msgs on lzReceive.// For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0.
endpoint.sendCompose(toAddress, _guid, 0/* the index of the composed message*/, composeMsg);
}
emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD);
}
/**
* @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The LayerZero message.
* @param _executor The address of the off-chain executor.
* @param _extraData Arbitrary data passed by the msg executor.
*
* @dev Enables the preCrime simulator to mock sending lzReceive() messages,
* routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
*/function_lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytescalldata _message,
address _executor,
bytescalldata _extraData
) internalvirtualoverride{
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Check if the peer is considered 'trusted' by the OApp.
* @param _eid The endpoint ID to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*
* @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.
*/functionisPeer(uint32 _eid, bytes32 _peer) publicviewvirtualoverridereturns (bool) {
return peers[_eid] == _peer;
}
/**
* @dev Internal function to remove dust from the given local decimal amount.
* @param _amountLD The amount in local decimals.
* @return amountLD The amount after removing dust.
*
* @dev Prevents the loss of dust when moving amounts between chains with different decimals.
* @dev eg. uint(123) with a conversion rate of 100 becomes uint(100).
*/function_removeDust(uint256 _amountLD) internalviewvirtualreturns (uint256 amountLD) {
return (_amountLD / decimalConversionRate) * decimalConversionRate;
}
/**
* @dev Internal function to convert an amount from shared decimals into local decimals.
* @param _amountSD The amount in shared decimals.
* @return amountLD The amount in local decimals.
*/function_toLD(uint64 _amountSD) internalviewvirtualreturns (uint256 amountLD) {
return _amountSD * decimalConversionRate;
}
/**
* @dev Internal function to convert an amount from local decimals into shared decimals.
* @param _amountLD The amount in local decimals.
* @return amountSD The amount in shared decimals.
*/function_toSD(uint256 _amountLD) internalviewvirtualreturns (uint64 amountSD) {
returnuint64(_amountLD / decimalConversionRate);
}
/**
* @dev Internal function to mock the amount mutation from a OFT debit() operation.
* @param _amountLD The amount to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @dev _dstEid The destination endpoint ID.
* @return amountSentLD The amount sent, in local decimals.
* @return amountReceivedLD The amount to be received on the remote chain, in local decimals.
*
* @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote.
*/function_debitView(uint256 _amountLD,
uint256 _minAmountLD,
uint32/*_dstEid*/) internalviewvirtualreturns (uint256 amountSentLD, uint256 amountReceivedLD) {
// @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token.
amountSentLD = _removeDust(_amountLD);
// @dev The amount to send is the same as amount received in the default implementation.
amountReceivedLD = amountSentLD;
// @dev Check for slippage.if (amountReceivedLD < _minAmountLD) {
revert SlippageExceeded(amountReceivedLD, _minAmountLD);
}
}
/**
* @dev Internal function to perform a debit operation.
* @param _amountLD The amount to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination endpoint ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*
* @dev Defined here but are intended to be overriden depending on the OFT implementation.
* @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
*/function_debit(uint256 _amountLD,
uint256 _minAmountLD,
uint32 _dstEid
) internalvirtualreturns (uint256 amountSentLD, uint256 amountReceivedLD);
/**
* @dev Internal function to perform a credit operation.
* @param _to The address to credit.
* @param _amountLD The amount to credit in local decimals.
* @param _srcEid The source endpoint ID.
* @return amountReceivedLD The amount ACTUALLY received in local decimals.
*
* @dev Defined here but are intended to be overriden depending on the OFT implementation.
* @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
*/function_credit(address _to,
uint256 _amountLD,
uint32 _srcEid
) internalvirtualreturns (uint256 amountReceivedLD);
}
Contract Source Code
File 32 of 39: OFTMsgCodec.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;libraryOFTMsgCodec{
// Offset constants for encoding and decoding OFT messagesuint8privateconstant SEND_TO_OFFSET =32;
uint8privateconstant SEND_AMOUNT_SD_OFFSET =40;
/**
* @dev Encodes an OFT LayerZero message.
* @param _sendTo The recipient address.
* @param _amountShared The amount in shared decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded message.
* @return hasCompose A boolean indicating whether the message has a composed payload.
*/functionencode(bytes32 _sendTo,
uint64 _amountShared,
bytesmemory _composeMsg
) internalviewreturns (bytesmemory _msg, bool hasCompose) {
hasCompose = _composeMsg.length>0;
// @dev Remote chains will want to know the composed function caller ie. msg.sender on the src.
_msg = hasCompose
? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg)
: abi.encodePacked(_sendTo, _amountShared);
}
/**
* @dev Checks if the OFT message is composed.
* @param _msg The OFT message.
* @return A boolean indicating whether the message is composed.
*/functionisComposed(bytescalldata _msg) internalpurereturns (bool) {
return _msg.length> SEND_AMOUNT_SD_OFFSET;
}
/**
* @dev Retrieves the recipient address from the OFT message.
* @param _msg The OFT message.
* @return The recipient address.
*/functionsendTo(bytescalldata _msg) internalpurereturns (bytes32) {
returnbytes32(_msg[:SEND_TO_OFFSET]);
}
/**
* @dev Retrieves the amount in shared decimals from the OFT message.
* @param _msg The OFT message.
* @return The amount in shared decimals.
*/functionamountSD(bytescalldata _msg) internalpurereturns (uint64) {
returnuint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET]));
}
/**
* @dev Retrieves the composed message from the OFT message.
* @param _msg The OFT message.
* @return The composed message.
*/functioncomposeMsg(bytescalldata _msg) internalpurereturns (bytesmemory) {
return _msg[SEND_AMOUNT_SD_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/functionaddressToBytes32(address _addr) internalpurereturns (bytes32) {
returnbytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/functionbytes32ToAddress(bytes32 _b) internalpurereturns (address) {
returnaddress(uint160(uint256(_b)));
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/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 35 of 39: Packet.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.20;import { Origin } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { PacketV1Codec } from"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol";
/**
* @title InboundPacket
* @dev Structure representing an inbound packet received by the contract.
*/structInboundPacket {
Origin origin; // Origin information of the packet.uint32 dstEid; // Destination endpointId of the packet.address receiver; // Receiver address for the packet.bytes32 guid; // Unique identifier of the packet.uint256 value; // msg.value of the packet.address executor; // Executor address for the packet.bytes message; // Message payload of the packet.bytes extraData; // Additional arbitrary data for the packet.
}
/**
* @title PacketDecoder
* @dev Library for decoding LayerZero packets.
*/libraryPacketDecoder{
usingPacketV1Codecforbytes;
/**
* @dev Decode an inbound packet from the given packet data.
* @param _packet The packet data to decode.
* @return packet An InboundPacket struct representing the decoded packet.
*/functiondecode(bytescalldata _packet) internalpurereturns (InboundPacket memory packet) {
packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());
packet.dstEid = _packet.dstEid();
packet.receiver = _packet.receiverB20();
packet.guid = _packet.guid();
packet.message = _packet.message();
}
/**
* @dev Decode multiple inbound packets from the given packet data and associated message values.
* @param _packets An array of packet data to decode.
* @param _packetMsgValues An array of associated message values for each packet.
* @return packets An array of InboundPacket structs representing the decoded packets.
*/functiondecode(bytes[] calldata _packets,
uint256[] memory _packetMsgValues
) internalpurereturns (InboundPacket[] memory packets) {
packets =new InboundPacket[](_packets.length);
for (uint256 i =0; i < _packets.length; i++) {
bytescalldata packet = _packets[i];
packets[i] = PacketDecoder.decode(packet);
// @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.
packets[i].value= _packetMsgValues[i];
}
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
import"../extensions/draft-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;
functionsafeTransfer(
IERC20 token,
address to,
uint256 value
) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
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));
}
functionsafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
functionsafeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
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");
if (returndata.length>0) {
// Return data is optionalrequire(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
Contract Source Code
File 38 of 39: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)pragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
uint8privateconstant _ADDRESS_LENGTH =20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/functiontoHexString(address addr) internalpurereturns (stringmemory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
Contract Source Code
File 39 of 39: draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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.
*/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].
*/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);
}