// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 35: 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 35: BitMaps.sol
// SPDX-License-Identifier: MIT// modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.solpragmasolidity ^0.8.20;type BitMap256 isuint256;
usingBitMapsforBitMap256global;
libraryBitMaps{
/**
* @dev Returns whether the bit at `index` is set.
*/functionget(BitMap256 bitmap, uint8 index) internalpurereturns (bool) {
uint256 mask =1<< index;
return BitMap256.unwrap(bitmap) & mask !=0;
}
/**
* @dev Sets the bit at `index`.
*/functionset(BitMap256 bitmap, uint8 index) internalpurereturns (BitMap256) {
uint256 mask =1<< index;
return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask);
}
}
Contract Source Code
File 4 of 35: BytesLib.sol
// SPDX-License-Identifier: Unlicense/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <goncalo.sa@consensys.net>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/pragmasolidity >=0.8.0 <0.9.0;libraryBytesLib{
functionconcat(bytesmemory _preBytes,
bytesmemory _postBytes
)
internalpurereturns (bytesmemory)
{
bytesmemory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as// Solidity does for memory variables.
tempBytes :=mload(0x40)
// Store the length of the first bytes array at the beginning of// the memory for tempBytes.let length :=mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the// temp bytes array by adding the 32 bytes for the array length to// the starting location.let mc :=add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the// first bytes array.let end :=add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,// 32 bytes into its memory.let cc :=add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc :=add(mc, 0x20)
cc :=add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes// at a time.mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes// and store it as the new length in the first 32 bytes of the// tempBytes memory.
length :=mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined// length of the arrays.
end :=add(mc, length)
for {
let cc :=add(_postBytes, 0x20)
} lt(mc, end) {
mc :=add(mc, 0x20)
cc :=add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location// to 32 bytes: add 31 bytes to the end of tempBytes to move to the// next 32 byte block, then round down to the nearest multiple of// 32. If the sum of the length of the two arrays is zero then add// one before rounding down to leave a blank 32 bytes (the length block with 0).mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
functionconcatStorage(bytesstorage _preBytes, bytesmemory _postBytes) internal{
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length// of the array. (We don't need to use the offset into the slot// because arrays use the entire slot.)let fslot :=sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,// while longer arrays have an odd value. The actual length is// the slot divided by two for odd values, and the lowest order// byte divided by two for even values.// If the slot is even, bitwise and the slot with 255 and divide by// two to get the length. If the slot is odd, bitwise and the slot// with -1 and divide by two.let slength :=div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength :=mload(_postBytes)
let newlength :=add(slength, mlength)
// slength can contain both the length and contents of the array// if length < 32 bytes so let's prepare for that// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storageswitchadd(lt(slength, 32), lt(newlength, 32))
case2 {
// Since the new array still fits in the slot, we just need to// update the contents of the slot.// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_lengthsstore(
_preBytes.slot,
// all the modifications to the slot are inside this// next blockadd(
// we can just add to the slot contents because the// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memorymload(add(_postBytes, 0x20)),
// zero all bytes to the rightexp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to// leave space for the length in the slotexp(0x100, sub(32, newlength))
),
// increase length by the double of the memory// bytes lengthmul(mlength, 2)
)
)
)
}
case1 {
// The stored value fits in the slot, but the combined value// will exceed it.// get the keccak hash to get the contents of the arraymstore(0x0, _preBytes.slot)
let sc :=add(keccak256(0x0, 0x20), div(slength, 32))
// save new lengthsstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into// the structure. Our first read should obtain the `submod`// bytes that can fit into the unused space in the last word// of the stored array. To get this, we read 32 bytes starting// from `submod`, so the data we read overlaps with the array// contents by `submod` bytes. Masking the lowest-order// `submod` bytes allows us to add that value directly to the// stored value.let submod :=sub(32, slength)
let mc :=add(_postBytes, submod)
let end :=add(_postBytes, mlength)
let mask :=sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc :=add(mc, 0x20)
sc :=add(sc, 1)
} lt(mc, end) {
sc :=add(sc, 1)
mc :=add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask :=exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the arraymstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.let sc :=add(keccak256(0x0, 0x20), div(slength, 32))
// save new lengthsstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in// case 1 above.let slengthmod :=mod(slength, 32)
let mlengthmod :=mod(mlength, 32)
let submod :=sub(32, slengthmod)
let mc :=add(_postBytes, submod)
let end :=add(_postBytes, mlength)
let mask :=sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc :=add(sc, 1)
mc :=add(mc, 0x20)
} lt(mc, end) {
sc :=add(sc, 1)
mc :=add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask :=exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
functionslice(bytesmemory _bytes,
uint256 _start,
uint256 _length
)
internalpurereturns (bytesmemory)
{
require(_length +31>= _length, "slice_overflow");
require(_bytes.length>= _start + _length, "slice_outOfBounds");
bytesmemory tempBytes;
assembly {
switchiszero(_length)
case0 {
// Get a location of some free memory and store it in tempBytes as// Solidity does for memory variables.
tempBytes :=mload(0x40)
// The first word of the slice result is potentially a partial// word read from the original array. To read it, we calculate// the length of that partial word and start copying that many// bytes into the array. The first word we copy will start with// data we don't care about, but the last `lengthmod` bytes will// land at the beginning of the contents of the new array. When// we're done copying, we overwrite the full first word with// the actual length of the slice.let lengthmod :=and(_length, 31)
// The multiplication in the next line is necessary// because when slicing multiples of 32 bytes (lengthmod == 0)// the following copy loop was copying the origin's length// and then ending prematurely not copying everything it should.let mc :=add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end :=add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose// as the one above.let cc :=add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc :=add(mc, 0x20)
cc :=add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer//allocating the array padded to 32 bytes like the compiler does nowmstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length arraydefault {
tempBytes :=mload(0x40)
//zero out the 32 bytes slice we are about to return//we need to do it because Solidity does not garbage collectmstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
functiontoAddress(bytesmemory _bytes, uint256 _start) internalpurereturns (address) {
require(_bytes.length>= _start +20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress :=div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
functiontoUint8(bytesmemory _bytes, uint256 _start) internalpurereturns (uint8) {
require(_bytes.length>= _start +1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
functiontoUint16(bytesmemory _bytes, uint256 _start) internalpurereturns (uint16) {
require(_bytes.length>= _start +2, "toUint16_outOfBounds");
uint16 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
functiontoUint32(bytesmemory _bytes, uint256 _start) internalpurereturns (uint32) {
require(_bytes.length>= _start +4, "toUint32_outOfBounds");
uint32 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
functiontoUint64(bytesmemory _bytes, uint256 _start) internalpurereturns (uint64) {
require(_bytes.length>= _start +8, "toUint64_outOfBounds");
uint64 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
functiontoUint96(bytesmemory _bytes, uint256 _start) internalpurereturns (uint96) {
require(_bytes.length>= _start +12, "toUint96_outOfBounds");
uint96 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
functiontoUint128(bytesmemory _bytes, uint256 _start) internalpurereturns (uint128) {
require(_bytes.length>= _start +16, "toUint128_outOfBounds");
uint128 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
functiontoUint256(bytesmemory _bytes, uint256 _start) internalpurereturns (uint256) {
require(_bytes.length>= _start +32, "toUint256_outOfBounds");
uint256 tempUint;
assembly {
tempUint :=mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
functiontoBytes32(bytesmemory _bytes, uint256 _start) internalpurereturns (bytes32) {
require(_bytes.length>= _start +32, "toBytes32_outOfBounds");
bytes32 tempBytes32;
assembly {
tempBytes32 :=mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
functionequal(bytesmemory _preBytes, bytesmemory _postBytes) internalpurereturns (bool) {
bool success =true;
assembly {
let length :=mload(_preBytes)
// if lengths don't match the arrays are not equalswitcheq(length, mload(_postBytes))
case1 {
// cb is a circuit breaker in the for loop since there's// no said feature for inline assembly loops// cb = 1 - don't breaker// cb = 0 - breaklet cb :=1let mc :=add(_preBytes, 0x20)
let end :=add(mc, length)
for {
let cc :=add(_postBytes, 0x20)
// the next line is the loop condition:// while(uint256(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc :=add(mc, 0x20)
cc :=add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equalifiszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success :=0
cb :=0
}
}
}
default {
// unsuccess:
success :=0
}
}
return success;
}
functionequalStorage(bytesstorage _preBytes,
bytesmemory _postBytes
)
internalviewreturns (bool)
{
bool success =true;
assembly {
// we know _preBytes_offset is 0let fslot :=sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().let slength :=div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength :=mload(_postBytes)
// if lengths don't match the arrays are not equalswitcheq(slength, mlength)
case1 {
// slength can contain both the length and contents of the array// if length < 32 bytes so let's prepare for that// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storageifiszero(iszero(slength)) {
switchlt(slength, 32)
case1 {
// blank the last byte which is the length
fslot :=mul(div(fslot, 0x100), 0x100)
ifiszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success :=0
}
}
default {
// cb is a circuit breaker in the for loop since there's// no said feature for inline assembly loops// cb = 1 - don't breaker// cb = 0 - breaklet cb :=1// get the keccak hash to get the contents of the arraymstore(0x0, _preBytes.slot)
let sc :=keccak256(0x0, 0x20)
let mc :=add(_postBytes, 0x20)
let end :=add(mc, mlength)
// the next line is the loop condition:// while(uint256(mc < end) + cb == 2)for {} eq(add(lt(mc, end), cb), 2) {
sc :=add(sc, 1)
mc :=add(mc, 0x20)
} {
ifiszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success :=0
cb :=0
}
}
}
}
}
default {
// unsuccess:
success :=0
}
}
return success;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
function_contextSuffixLength() internalviewvirtualreturns (uint256) {
return0;
}
}
Contract Source Code
File 7 of 35: DVNOptions.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { BytesLib } from"solidity-bytes-utils/contracts/BytesLib.sol";
import { BitMap256 } from"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol";
import { CalldataBytesLib } from"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol";
libraryDVNOptions{
usingCalldataBytesLibforbytes;
usingBytesLibforbytes;
uint8internalconstant WORKER_ID =2;
uint8internalconstant OPTION_TYPE_PRECRIME =1;
errorDVN_InvalidDVNIdx();
errorDVN_InvalidDVNOptions(uint256 cursor);
/// @dev group dvn options by its idx/// @param _options [dvn_id][dvn_option][dvn_id][dvn_option].../// dvn_option = [option_size][dvn_idx][option_type][option]/// option_size = len(dvn_idx) + len(option_type) + len(option)/// dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes/// @return dvnOptions the grouped options, still share the same format of _options/// @return dvnIndices the dvn indicesfunctiongroupDVNOptionsByIdx(bytesmemory _options
) internalpurereturns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) {
if (_options.length==0) return (dvnOptions, dvnIndices);
uint8 numDVNs = getNumDVNs(_options);
// if there is only 1 dvn, we can just return the whole optionsif (numDVNs ==1) {
dvnOptions =newbytes[](1);
dvnOptions[0] = _options;
dvnIndices =newuint8[](1);
dvnIndices[0] = _options.toUint8(3); // dvn idxreturn (dvnOptions, dvnIndices);
}
// otherwise, we need to group the options by dvn_idx
dvnIndices =newuint8[](numDVNs);
dvnOptions =newbytes[](numDVNs);
unchecked {
uint256 cursor =0;
uint256 start =0;
uint8 lastDVNIdx =255; // 255 is an invalid dvn_idxwhile (cursor < _options.length) {
++cursor; // skip worker_id// optionLength asserted in getNumDVNs (skip check)uint16 optionLength = _options.toUint16(cursor);
cursor +=2;
// dvnIdx asserted in getNumDVNs (skip check)uint8 dvnIdx = _options.toUint8(cursor);
// dvnIdx must equal to the lastDVNIdx for the first option// so it is always skipped in the first option// this operation slices out options whenever the scan finds a different lastDVNIdxif (lastDVNIdx ==255) {
lastDVNIdx = dvnIdx;
} elseif (dvnIdx != lastDVNIdx) {
uint256 len = cursor - start -3; // 3 is for worker_id and option_lengthbytesmemory opt = _options.slice(start, len);
_insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt);
// reset the start and lastDVNIdx
start += len;
lastDVNIdx = dvnIdx;
}
cursor += optionLength;
}
// skip check the cursor here because the cursor is asserted in getNumDVNs// if we have reached the end of the options, we need to process the last dvnuint256 size = cursor - start;
bytesmemory op = _options.slice(start, size);
_insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op);
// revert dvnIndices to start from 0for (uint8 i =0; i < numDVNs; ++i) {
--dvnIndices[i];
}
}
}
function_insertDVNOptions(bytes[] memory _dvnOptions,
uint8[] memory _dvnIndices,
uint8 _dvnIdx,
bytesmemory _newOptions
) internalpure{
// dvnIdx starts from 0 but default value of dvnIndices is 0,// so we tell if the slot is empty by adding 1 to dvnIdxif (_dvnIdx ==255) revert DVN_InvalidDVNIdx();
uint8 dvnIdxAdj = _dvnIdx +1;
for (uint256 j =0; j < _dvnIndices.length; ++j) {
uint8 index = _dvnIndices[j];
if (dvnIdxAdj == index) {
_dvnOptions[j] =abi.encodePacked(_dvnOptions[j], _newOptions);
break;
} elseif (index ==0) {
// empty slot, that means it is the first time we see this dvn
_dvnIndices[j] = dvnIdxAdj;
_dvnOptions[j] = _newOptions;
break;
}
}
}
/// @dev get the number of unique dvns/// @param _options the format is the same as groupDVNOptionsByIdxfunctiongetNumDVNs(bytesmemory _options) internalpurereturns (uint8 numDVNs) {
uint256 cursor =0;
BitMap256 bitmap;
// find number of unique dvn_idxunchecked {
while (cursor < _options.length) {
++cursor; // skip worker_iduint16 optionLength = _options.toUint16(cursor);
cursor +=2;
if (optionLength <2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_typeuint8 dvnIdx = _options.toUint8(cursor);
// if dvnIdx is not set, increment numDVNs// max num of dvns is 255, 255 is an invalid dvn_idx// The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken// the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has// already enforced certain options can append additional options to the end of the enforced// ones without restrictions.if (dvnIdx ==255) revert DVN_InvalidDVNIdx();
if (!bitmap.get(dvnIdx)) {
++numDVNs;
bitmap = bitmap.set(dvnIdx);
}
cursor += optionLength;
}
}
if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor);
}
/// @dev decode the next dvn option from _options starting from the specified cursor/// @param _options the format is the same as groupDVNOptionsByIdx/// @param _cursor the cursor to start decoding/// @return optionType the type of the option/// @return option the option/// @return cursor the cursor to start decoding the next optionfunctionnextDVNOption(bytescalldata _options,
uint256 _cursor
) internalpurereturns (uint8 optionType, bytescalldata option, uint256 cursor) {
unchecked {
// skip worker id
cursor = _cursor +1;
// read option sizeuint16 size = _options.toU16(cursor);
cursor +=2;
// read option type
optionType = _options.toU8(cursor +1); // skip dvn_idx// startCursor and endCursor are used to slice the option from _optionsuint256 startCursor = cursor +2; // skip option type and dvn_idxuint256 endCursor = cursor + size;
option = _options[startCursor:endCursor];
cursor += size;
}
}
}
Contract Source Code
File 8 of 35: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 9 of 35: ExecutorOptions.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { CalldataBytesLib } from"../../libs/CalldataBytesLib.sol";
libraryExecutorOptions{
usingCalldataBytesLibforbytes;
uint8internalconstant WORKER_ID =1;
uint8internalconstant OPTION_TYPE_LZRECEIVE =1;
uint8internalconstant OPTION_TYPE_NATIVE_DROP =2;
uint8internalconstant OPTION_TYPE_LZCOMPOSE =3;
uint8internalconstant OPTION_TYPE_ORDERED_EXECUTION =4;
errorExecutor_InvalidLzReceiveOption();
errorExecutor_InvalidNativeDropOption();
errorExecutor_InvalidLzComposeOption();
/// @dev decode the next executor option from the options starting from the specified cursor/// @param _options [executor_id][executor_option][executor_id][executor_option].../// executor_option = [option_size][option_type][option]/// option_size = len(option_type) + len(option)/// executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes/// @param _cursor the cursor to start decoding from/// @return optionType the type of the option/// @return option the option of the executor/// @return cursor the cursor to start decoding the next executor optionfunctionnextExecutorOption(bytescalldata _options,
uint256 _cursor
) internalpurereturns (uint8 optionType, bytescalldata option, uint256 cursor) {
unchecked {
// skip worker id
cursor = _cursor +1;
// read option sizeuint16 size = _options.toU16(cursor);
cursor +=2;
// read option type
optionType = _options.toU8(cursor);
// startCursor and endCursor are used to slice the option from _optionsuint256 startCursor = cursor +1; // skip option typeuint256 endCursor = cursor + size;
option = _options[startCursor:endCursor];
cursor += size;
}
}
functiondecodeLzReceiveOption(bytescalldata _option) internalpurereturns (uint128 gas, uint128 value) {
if (_option.length!=16&& _option.length!=32) revert Executor_InvalidLzReceiveOption();
gas = _option.toU128(0);
value = _option.length==32 ? _option.toU128(16) : 0;
}
functiondecodeNativeDropOption(bytescalldata _option) internalpurereturns (uint128 amount, bytes32 receiver) {
if (_option.length!=48) revert Executor_InvalidNativeDropOption();
amount = _option.toU128(0);
receiver = _option.toB32(16);
}
functiondecodeLzComposeOption(bytescalldata _option
) internalpurereturns (uint16 index, uint128 gas, uint128 value) {
if (_option.length!=18&& _option.length!=34) revert Executor_InvalidLzComposeOption();
index = _option.toU16(0);
gas = _option.toU128(2);
value = _option.length==34 ? _option.toU128(18) : 0;
}
functionencodeLzReceiveOption(uint128 _gas, uint128 _value) internalpurereturns (bytesmemory) {
return _value ==0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value);
}
functionencodeNativeDropOption(uint128 _amount, bytes32 _receiver) internalpurereturns (bytesmemory) {
returnabi.encodePacked(_amount, _receiver);
}
functionencodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internalpurereturns (bytesmemory) {
return _value ==0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value);
}
}
Contract Source Code
File 10 of 35: 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 11 of 35: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
Contract Source Code
File 12 of 35: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
Contract Source Code
File 13 of 35: ILayerZeroDVN.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.8.0;interfaceILayerZeroDVN{
structAssignJobParam {
uint32 dstEid;
bytes packetHeader;
bytes32 payloadHash;
uint64 confirmations;
address sender;
}
// @notice query price and assign jobs at the same time// @param _dstEid - the destination endpoint identifier// @param _packetHeader - version + nonce + path// @param _payloadHash - hash of guid + message// @param _confirmations - block confirmation delay before relaying blocks// @param _sender - the source sending contract address// @param _options - optionsfunctionassignJob(AssignJobParam calldata _param, bytescalldata _options) externalpayablereturns (uint256 fee);
// @notice query the dvn fee for relaying block information to the destination chain// @param _dstEid the destination endpoint identifier// @param _confirmations - block confirmation delay before relaying blocks// @param _sender - the source sending contract address// @param _options - optionsfunctiongetFee(uint32 _dstEid,
uint64 _confirmations,
address _sender,
bytescalldata _options
) externalviewreturns (uint256 fee);
}
// SPDX-License-Identifier: MITpragmasolidity >=0.8.0;interfaceILayerZeroExecutor{
// @notice query price and assign jobs at the same time// @param _dstEid - the destination endpoint identifier// @param _sender - the source sending contract address. executors may apply price discrimination to senders// @param _calldataSize - dynamic data size of message + caller params// @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chainfunctionassignJob(uint32 _dstEid,
address _sender,
uint256 _calldataSize,
bytescalldata _options
) externalreturns (uint256 price);
// @notice query the executor price for relaying the payload and its proof to the destination chain// @param _dstEid - the destination endpoint identifier// @param _sender - the source sending contract address. executors may apply price discrimination to senders// @param _calldataSize - dynamic data size of message + caller params// @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chainfunctiongetFee(uint32 _dstEid,
address _sender,
uint256 _calldataSize,
bytescalldata _options
) externalviewreturns (uint256 price);
}
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;/// @dev simply a container of endpoint address and local eidabstractcontractMessageLibBase{
addressinternalimmutable endpoint;
uint32internalimmutable localEid;
errorLZ_MessageLib_OnlyEndpoint();
modifieronlyEndpoint() {
if (endpoint !=msg.sender) revert LZ_MessageLib_OnlyEndpoint();
_;
}
constructor(address _endpoint, uint32 _localEid) {
endpoint = _endpoint;
localEid = _localEid;
}
}
Contract Source Code
File 24 of 35: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0pragmasolidity ^0.8.20;/// @dev copied from https://github.com/nomad-xyz/ExcessivelySafeCall/blob/main/src/ExcessivelySafeCall.sol.librarySafeCall{
/// @notice calls a contract with a specified gas limit and value and captures the return data/// @param _target The address to call/// @param _gas The amount of gas to forward to the remote contract/// @param _value The value in wei to send to the remote contract/// to memory./// @param _maxCopy The maximum number of bytes of returndata to copy/// to memory./// @param _calldata The data to send to the remote contract/// @return success and returndata, as `.call()`. Returndata is capped to/// `_maxCopy` bytes.functionsafeCall(address _target,
uint256 _gas,
uint256 _value,
uint16 _maxCopy,
bytesmemory _calldata
) internalreturns (bool, bytesmemory) {
// check that target has codeuint size;
assembly {
size :=extcodesize(_target)
}
if (size ==0) {
return (false, newbytes(0));
}
// set up for assembly calluint256 _toCopy;
bool _success;
bytesmemory _returnData =newbytes(_maxCopy);
// dispatch message to recipient// by assembly calling "handle" function// we call via assembly to avoid memcopying a very large returndata// returned by a malicious contractassembly {
_success :=call(
_gas, // gas
_target, // recipient
_value, // ether valueadd(_calldata, 0x20), // inlocmload(_calldata), // inlen0, // outloc0// outlen
)
// limit our copy to 100 bytes
_toCopy :=returndatasize()
ifgt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytesmstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
return (_success, _returnData);
}
/// @notice Use when you _really_ really _really_ don't trust the called/// contract. This prevents the called contract from causing reversion of/// the caller in as many ways as we can./// @dev The main difference between this and a solidity low-level call is/// that we limit the number of bytes that the callee can cause to be/// copied to caller memory. This prevents stupid things like malicious/// contracts returning 10,000,000 bytes causing a local OOG when copying/// to memory./// @param _target The address to call/// @param _gas The amount of gas to forward to the remote contract/// @param _maxCopy The maximum number of bytes of returndata to copy/// to memory./// @param _calldata The data to send to the remote contract/// @return success and returndata, as `.call()`. Returndata is capped to/// `_maxCopy` bytes.functionsafeStaticCall(address _target,
uint256 _gas,
uint16 _maxCopy,
bytesmemory _calldata
) internalviewreturns (bool, bytesmemory) {
// check that target has codeuint size;
assembly {
size :=extcodesize(_target)
}
if (size ==0) {
return (false, newbytes(0));
}
// set up for assembly calluint256 _toCopy;
bool _success;
bytesmemory _returnData =newbytes(_maxCopy);
// dispatch message to recipient// by assembly calling "handle" function// we call via assembly to avoid memcopying a very large returndata// returned by a malicious contractassembly {
_success :=staticcall(
_gas, // gas
_target, // recipientadd(_calldata, 0x20), // inlocmload(_calldata), // inlen0, // outloc0// outlen
)
// limit our copy to 256 bytes
_toCopy :=returndatasize()
ifgt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytesmstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
return (_success, _returnData);
}
}
Contract Source Code
File 27 of 35: SafeCast.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)// This file was procedurally generated from scripts/generate/templates/SafeCast.js.pragmasolidity ^0.8.0;/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/librarySafeCast{
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/functiontoUint248(uint256 value) internalpurereturns (uint248) {
require(value <=type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
returnuint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/functiontoUint240(uint256 value) internalpurereturns (uint240) {
require(value <=type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
returnuint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/functiontoUint232(uint256 value) internalpurereturns (uint232) {
require(value <=type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
returnuint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/functiontoUint224(uint256 value) internalpurereturns (uint224) {
require(value <=type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
returnuint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/functiontoUint216(uint256 value) internalpurereturns (uint216) {
require(value <=type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
returnuint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/functiontoUint208(uint256 value) internalpurereturns (uint208) {
require(value <=type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
returnuint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/functiontoUint200(uint256 value) internalpurereturns (uint200) {
require(value <=type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
returnuint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/functiontoUint192(uint256 value) internalpurereturns (uint192) {
require(value <=type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
returnuint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/functiontoUint184(uint256 value) internalpurereturns (uint184) {
require(value <=type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
returnuint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/functiontoUint176(uint256 value) internalpurereturns (uint176) {
require(value <=type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
returnuint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/functiontoUint168(uint256 value) internalpurereturns (uint168) {
require(value <=type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
returnuint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/functiontoUint160(uint256 value) internalpurereturns (uint160) {
require(value <=type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
returnuint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/functiontoUint152(uint256 value) internalpurereturns (uint152) {
require(value <=type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
returnuint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/functiontoUint144(uint256 value) internalpurereturns (uint144) {
require(value <=type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
returnuint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/functiontoUint136(uint256 value) internalpurereturns (uint136) {
require(value <=type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
returnuint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/functiontoUint128(uint256 value) internalpurereturns (uint128) {
require(value <=type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
returnuint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/functiontoUint120(uint256 value) internalpurereturns (uint120) {
require(value <=type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
returnuint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/functiontoUint112(uint256 value) internalpurereturns (uint112) {
require(value <=type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
returnuint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/functiontoUint104(uint256 value) internalpurereturns (uint104) {
require(value <=type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
returnuint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/functiontoUint96(uint256 value) internalpurereturns (uint96) {
require(value <=type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
returnuint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/functiontoUint88(uint256 value) internalpurereturns (uint88) {
require(value <=type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
returnuint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/functiontoUint80(uint256 value) internalpurereturns (uint80) {
require(value <=type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
returnuint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/functiontoUint72(uint256 value) internalpurereturns (uint72) {
require(value <=type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
returnuint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/functiontoUint64(uint256 value) internalpurereturns (uint64) {
require(value <=type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
returnuint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/functiontoUint56(uint256 value) internalpurereturns (uint56) {
require(value <=type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
returnuint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/functiontoUint48(uint256 value) internalpurereturns (uint48) {
require(value <=type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
returnuint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/functiontoUint40(uint256 value) internalpurereturns (uint40) {
require(value <=type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
returnuint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/functiontoUint32(uint256 value) internalpurereturns (uint32) {
require(value <=type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
returnuint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/functiontoUint24(uint256 value) internalpurereturns (uint24) {
require(value <=type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
returnuint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/functiontoUint16(uint256 value) internalpurereturns (uint16) {
require(value <=type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
returnuint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/functiontoUint8(uint256 value) internalpurereturns (uint8) {
require(value <=type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
returnuint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/functiontoUint256(int256 value) internalpurereturns (uint256) {
require(value >=0, "SafeCast: value must be positive");
returnuint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/functiontoInt248(int256 value) internalpurereturns (int248 downcasted) {
downcasted =int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/functiontoInt240(int256 value) internalpurereturns (int240 downcasted) {
downcasted =int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/functiontoInt232(int256 value) internalpurereturns (int232 downcasted) {
downcasted =int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/functiontoInt224(int256 value) internalpurereturns (int224 downcasted) {
downcasted =int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/functiontoInt216(int256 value) internalpurereturns (int216 downcasted) {
downcasted =int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/functiontoInt208(int256 value) internalpurereturns (int208 downcasted) {
downcasted =int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/functiontoInt200(int256 value) internalpurereturns (int200 downcasted) {
downcasted =int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/functiontoInt192(int256 value) internalpurereturns (int192 downcasted) {
downcasted =int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/functiontoInt184(int256 value) internalpurereturns (int184 downcasted) {
downcasted =int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/functiontoInt176(int256 value) internalpurereturns (int176 downcasted) {
downcasted =int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/functiontoInt168(int256 value) internalpurereturns (int168 downcasted) {
downcasted =int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/functiontoInt160(int256 value) internalpurereturns (int160 downcasted) {
downcasted =int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/functiontoInt152(int256 value) internalpurereturns (int152 downcasted) {
downcasted =int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/functiontoInt144(int256 value) internalpurereturns (int144 downcasted) {
downcasted =int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/functiontoInt136(int256 value) internalpurereturns (int136 downcasted) {
downcasted =int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/functiontoInt128(int256 value) internalpurereturns (int128 downcasted) {
downcasted =int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/functiontoInt120(int256 value) internalpurereturns (int120 downcasted) {
downcasted =int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/functiontoInt112(int256 value) internalpurereturns (int112 downcasted) {
downcasted =int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/functiontoInt104(int256 value) internalpurereturns (int104 downcasted) {
downcasted =int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/functiontoInt96(int256 value) internalpurereturns (int96 downcasted) {
downcasted =int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/functiontoInt88(int256 value) internalpurereturns (int88 downcasted) {
downcasted =int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/functiontoInt80(int256 value) internalpurereturns (int80 downcasted) {
downcasted =int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/functiontoInt72(int256 value) internalpurereturns (int72 downcasted) {
downcasted =int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/functiontoInt64(int256 value) internalpurereturns (int64 downcasted) {
downcasted =int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/functiontoInt56(int256 value) internalpurereturns (int56 downcasted) {
downcasted =int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/functiontoInt48(int256 value) internalpurereturns (int48 downcasted) {
downcasted =int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/functiontoInt40(int256 value) internalpurereturns (int40 downcasted) {
downcasted =int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/functiontoInt32(int256 value) internalpurereturns (int32 downcasted) {
downcasted =int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/functiontoInt24(int256 value) internalpurereturns (int24 downcasted) {
downcasted =int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/functiontoInt16(int256 value) internalpurereturns (int16 downcasted) {
downcasted =int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/functiontoInt8(int256 value) internalpurereturns (int8 downcasted) {
downcasted =int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/functiontoInt256(uint256 value) internalpurereturns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positiverequire(value <=uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
returnint256(value);
}
}
Contract Source Code
File 28 of 35: SafeERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
import"../extensions/IERC20Permit.sol";
import"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/functionsafeApprove(IERC20 token, address spender, uint256 value) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'require(
(value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/functionsafePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal{
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore +1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that// the target address contains contract code and also asserts for success in the low-level call.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length==0||abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return
success && (returndata.length==0||abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
Contract Source Code
File 29 of 35: SendLibBase.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { Ownable } from"@openzeppelin/contracts/access/Ownable.sol";
import { Transfer } from"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Transfer.sol";
import { ILayerZeroExecutor } from"./interfaces/ILayerZeroExecutor.sol";
import { ILayerZeroTreasury } from"./interfaces/ILayerZeroTreasury.sol";
import { SafeCall } from"./libs/SafeCall.sol";
import { MessageLibBase } from"./MessageLibBase.sol";
structWorkerOptions {
uint8 workerId;
bytes options;
}
structSetDefaultExecutorConfigParam {
uint32 eid;
ExecutorConfig config;
}
structExecutorConfig {
uint32 maxMessageSize;
address executor;
}
/// @dev base contract for both SendLibBaseE1 and SendLibBaseE2abstractcontractSendLibBaseisMessageLibBase, Ownable{
usingSafeCallforaddress;
addressprivateconstant DEFAULT_CONFIG =address(0);
uint16internalconstant TREASURY_MAX_COPY =32;
uint256internalimmutable treasuryGasLimit;
uint256internal treasuryNativeFeeCap;
// configaddresspublic treasury;
mapping(address oapp =>mapping(uint32 eid => ExecutorConfig)) public executorConfigs;
// accumulated fees for workers and treasurymapping(address worker =>uint256) public fees;
eventExecutorFeePaid(address executor, uint256 fee);
eventTreasurySet(address treasury);
eventDefaultExecutorConfigsSet(SetDefaultExecutorConfigParam[] params);
eventExecutorConfigSet(address oapp, uint32 eid, ExecutorConfig config);
eventTreasuryNativeFeeCapSet(uint256 newTreasuryNativeFeeCap);
errorLZ_MessageLib_InvalidMessageSize(uint256 actual, uint256 max);
errorLZ_MessageLib_InvalidAmount(uint256 requested, uint256 available);
errorLZ_MessageLib_TransferFailed();
errorLZ_MessageLib_InvalidExecutor();
errorLZ_MessageLib_ZeroMessageSize();
constructor(address _endpoint,
uint32 _localEid,
uint256 _treasuryGasLimit,
uint256 _treasuryNativeFeeCap
) MessageLibBase(_endpoint, _localEid) {
treasuryGasLimit = _treasuryGasLimit;
treasuryNativeFeeCap = _treasuryNativeFeeCap;
}
functionsetDefaultExecutorConfigs(SetDefaultExecutorConfigParam[] calldata _params) externalonlyOwner{
for (uint256 i =0; i < _params.length; ++i) {
SetDefaultExecutorConfigParam calldata param = _params[i];
if (param.config.executor ==address(0x0)) revert LZ_MessageLib_InvalidExecutor();
if (param.config.maxMessageSize ==0) revert LZ_MessageLib_ZeroMessageSize();
executorConfigs[DEFAULT_CONFIG][param.eid] = param.config;
}
emit DefaultExecutorConfigsSet(_params);
}
/// @dev the new value can not be greater than the old value, i.e. down onlyfunctionsetTreasuryNativeFeeCap(uint256 _newTreasuryNativeFeeCap) externalonlyOwner{
// assert the new value is no greater than the old valueif (_newTreasuryNativeFeeCap > treasuryNativeFeeCap)
revert LZ_MessageLib_InvalidAmount(_newTreasuryNativeFeeCap, treasuryNativeFeeCap);
treasuryNativeFeeCap = _newTreasuryNativeFeeCap;
emit TreasuryNativeFeeCapSet(_newTreasuryNativeFeeCap);
}
// ============================ View ===================================// @dev get the executor config and if not set, return the default configfunctiongetExecutorConfig(address _oapp, uint32 _remoteEid) publicviewreturns (ExecutorConfig memory rtnConfig) {
ExecutorConfig storage defaultConfig = executorConfigs[DEFAULT_CONFIG][_remoteEid];
ExecutorConfig storage customConfig = executorConfigs[_oapp][_remoteEid];
uint32 maxMessageSize = customConfig.maxMessageSize;
rtnConfig.maxMessageSize = maxMessageSize !=0 ? maxMessageSize : defaultConfig.maxMessageSize;
address executor = customConfig.executor;
rtnConfig.executor = executor !=address(0x0) ? executor : defaultConfig.executor;
}
// ======================= Internal =======================function_assertMessageSize(uint256 _actual, uint256 _max) internalpure{
if (_actual > _max) revert LZ_MessageLib_InvalidMessageSize(_actual, _max);
}
function_payExecutor(address _executor,
uint32 _dstEid,
address _sender,
uint256 _msgSize,
bytesmemory _executorOptions
) internalreturns (uint256 executorFee) {
executorFee = ILayerZeroExecutor(_executor).assignJob(_dstEid, _sender, _msgSize, _executorOptions);
if (executorFee >0) {
fees[_executor] += executorFee;
}
emit ExecutorFeePaid(_executor, executorFee);
}
function_payTreasury(address _sender,
uint32 _dstEid,
uint256 _totalNativeFee,
bool _payInLzToken
) internalreturns (uint256 treasuryNativeFee, uint256 lzTokenFee) {
if (treasury !=address(0x0)) {
bytesmemory callData =abi.encodeCall(
ILayerZeroTreasury.payFee,
(_sender, _dstEid, _totalNativeFee, _payInLzToken)
);
(bool success, bytesmemory result) = treasury.safeCall(treasuryGasLimit, 0, TREASURY_MAX_COPY, callData);
(treasuryNativeFee, lzTokenFee) = _parseTreasuryResult(_totalNativeFee, _payInLzToken, success, result);
// fee should be in lzTokenFee if payInLzToken, otherwise in nativeif (treasuryNativeFee >0) {
fees[treasury] += treasuryNativeFee;
}
}
}
/// @dev the abstract process for quote() is:/// 0/ split out the executor options and options of other workers/// 1/ quote workers/// 2/ quote executor/// 3/ quote treasury/// @return nativeFee, lzTokenFeefunction_quote(address _sender,
uint32 _dstEid,
uint256 _msgSize,
bool _payInLzToken,
bytescalldata _options
) internalviewreturns (uint256, uint256) {
(bytesmemory executorOptions, WorkerOptions[] memory validationOptions) = _splitOptions(_options);
// quote the verifier used in the library. for ULN, it is a list of DVNsuint256 nativeFee = _quoteVerifier(_sender, _dstEid, validationOptions);
// quote executor
ExecutorConfig memory config = getExecutorConfig(_sender, _dstEid);
// assert msg size
_assertMessageSize(_msgSize, config.maxMessageSize);
nativeFee += ILayerZeroExecutor(config.executor).getFee(_dstEid, _sender, _msgSize, executorOptions);
// quote treasury
(uint256 treasuryNativeFee, uint256 lzTokenFee) = _quoteTreasury(_sender, _dstEid, nativeFee, _payInLzToken);
nativeFee += treasuryNativeFee;
return (nativeFee, lzTokenFee);
}
/// @dev this interface should be DoS-free if the user is paying with native. properties/// 1/ treasury can return an overly high lzToken fee/// 2/ if treasury returns an overly high native fee, it will be capped by maxNativeFee,/// which can be reasoned with the configurations/// 3/ the owner can not configure the treasury in a way that force this function to revertfunction_quoteTreasury(address _sender,
uint32 _dstEid,
uint256 _totalNativeFee,
bool _payInLzToken
) internalviewreturns (uint256 nativeFee, uint256 lzTokenFee) {
// treasury must be set, and it has to be a contractif (treasury !=address(0x0)) {
bytesmemory callData =abi.encodeCall(
ILayerZeroTreasury.getFee,
(_sender, _dstEid, _totalNativeFee, _payInLzToken)
);
(bool success, bytesmemory result) = treasury.safeStaticCall(
treasuryGasLimit,
TREASURY_MAX_COPY,
callData
);
return _parseTreasuryResult(_totalNativeFee, _payInLzToken, success, result);
}
}
function_parseTreasuryResult(uint256 _totalNativeFee,
bool _payInLzToken,
bool _success,
bytesmemory _result
) internalviewreturns (uint256 nativeFee, uint256 lzTokenFee) {
// failure, charges nothingif (!_success || _result.length< TREASURY_MAX_COPY) return (0, 0);
// parse the resultuint256 treasureFeeQuote =abi.decode(_result, (uint256));
if (_payInLzToken) {
lzTokenFee = treasureFeeQuote;
} else {
// pay in native// we must prevent high-treasuryFee Dos attack// nativeFee = min(treasureFeeQuote, maxNativeFee)// opportunistically raise the maxNativeFee to be the same as _totalNativeFee// can't use the _totalNativeFee alone because the oapp can use custom workers to force the fee to 0.// maxNativeFee = max (_totalNativeFee, treasuryNativeFeeCap)uint256 maxNativeFee = _totalNativeFee > treasuryNativeFeeCap ? _totalNativeFee : treasuryNativeFeeCap;
// min (treasureFeeQuote, nativeFeeCap)
nativeFee = treasureFeeQuote > maxNativeFee ? maxNativeFee : treasureFeeQuote;
}
}
/// @dev authenticated by msg.sender onlyfunction_debitFee(uint256 _amount) internal{
uint256 fee = fees[msg.sender];
if (_amount > fee) revert LZ_MessageLib_InvalidAmount(_amount, fee);
unchecked {
fees[msg.sender] = fee - _amount;
}
}
function_setTreasury(address _treasury) internal{
treasury = _treasury;
emit TreasurySet(_treasury);
}
function_setExecutorConfig(uint32 _remoteEid, address _oapp, ExecutorConfig memory _config) internal{
executorConfigs[_oapp][_remoteEid] = _config;
emit ExecutorConfigSet(_oapp, _remoteEid, _config);
}
// ======================= Virtual =======================/// @dev these two functions will be overridden with specific logics of the library functionfunction_quoteVerifier(address _oapp,
uint32 _eid,
WorkerOptions[] memory _options
) internalviewvirtualreturns (uint256 nativeFee);
/// @dev this function will split the options into executorOptions and validationOptionsfunction_splitOptions(bytescalldata _options
) internalviewvirtualreturns (bytesmemory executorOptions, WorkerOptions[] memory validationOptions);
}
Contract Source Code
File 30 of 35: SendLibBaseE2.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { IERC165 } from"@openzeppelin/contracts/utils/introspection/IERC165.sol";
import { ERC165 } from"@openzeppelin/contracts/utils/introspection/ERC165.sol";
import { ILayerZeroEndpointV2, MessagingFee } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { IMessageLib, MessageLibType } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLib.sol";
import { ISendLib, Packet } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol";
import { Transfer } from"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Transfer.sol";
import { SendLibBase, WorkerOptions, ExecutorConfig } from"./SendLibBase.sol";
/// @dev send-side message library base contract on endpoint v2./// design: the high level logic is the same as SendLibBaseE1/// 1/ with added interfaces/// 2/ adapt the functions to the new types, like uint32 for eid, address for sender.abstractcontractSendLibBaseE2isSendLibBase, ERC165, ISendLib{
eventNativeFeeWithdrawn(address worker, address receiver, uint256 amount);
eventLzTokenFeeWithdrawn(address lzToken, address receiver, uint256 amount);
errorLZ_MessageLib_NotTreasury();
errorLZ_MessageLib_CannotWithdrawAltToken();
constructor(address _endpoint,
uint256 _treasuryGasLimit,
uint256 _treasuryNativeFeeCap
) SendLibBase(_endpoint, ILayerZeroEndpointV2(_endpoint).eid(), _treasuryGasLimit, _treasuryNativeFeeCap) {}
functionsupportsInterface(bytes4 _interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
_interfaceId ==type(IMessageLib).interfaceId||
_interfaceId ==type(ISendLib).interfaceId||super.supportsInterface(_interfaceId);
}
// ========================= OnlyEndpoint =========================// @dev this function is marked as virtual and public for testing purposefunctionsend(
Packet calldata _packet,
bytescalldata _options,
bool _payInLzToken
) publicvirtualonlyEndpointreturns (MessagingFee memory, bytesmemory) {
(bytesmemory encodedPacket, uint256 totalNativeFee) = _payWorkers(_packet, _options);
(uint256 treasuryNativeFee, uint256 lzTokenFee) = _payTreasury(
_packet.sender,
_packet.dstEid,
totalNativeFee,
_payInLzToken
);
totalNativeFee += treasuryNativeFee;
return (MessagingFee(totalNativeFee, lzTokenFee), encodedPacket);
}
// ========================= OnlyOwner =========================functionsetTreasury(address _treasury) externalonlyOwner{
_setTreasury(_treasury);
}
// ========================= External =========================/// @dev E2 onlyfunctionwithdrawFee(address _to, uint256 _amount) external{
_debitFee(_amount);
address nativeToken = ILayerZeroEndpointV2(endpoint).nativeToken();
// transfers native if nativeToken == address(0x0)
Transfer.nativeOrToken(nativeToken, _to, _amount);
emit NativeFeeWithdrawn(msg.sender, _to, _amount);
}
/// @dev _lzToken is a user-supplied value because lzToken might change in the endpoint before all lzToken can be taken out/// @dev E2 only/// @dev treasury only functionfunctionwithdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external{
if (msg.sender!= treasury) revert LZ_MessageLib_NotTreasury();
// lz token cannot be the same as the native tokenif (ILayerZeroEndpointV2(endpoint).nativeToken() == _lzToken) revert LZ_MessageLib_CannotWithdrawAltToken();
Transfer.token(_lzToken, _to, _amount);
emit LzTokenFeeWithdrawn(_lzToken, _to, _amount);
}
// ========================= View =========================functionquote(
Packet calldata _packet,
bytescalldata _options,
bool _payInLzToken
) externalviewreturns (MessagingFee memory) {
(uint256 nativeFee, uint256 lzTokenFee) = _quote(
_packet.sender,
_packet.dstEid,
_packet.message.length,
_payInLzToken,
_options
);
return MessagingFee(nativeFee, lzTokenFee);
}
functionmessageLibType() externalpurevirtualoverridereturns (MessageLibType) {
return MessageLibType.Send;
}
// ========================= Internal =========================/// 1/ handle executor/// 2/ handle other workersfunction_payWorkers(
Packet calldata _packet,
bytescalldata _options
) internalreturns (bytesmemory encodedPacket, uint256 totalNativeFee) {
// split workers options
(bytesmemory executorOptions, WorkerOptions[] memory validationOptions) = _splitOptions(_options);
// handle executor
ExecutorConfig memory config = getExecutorConfig(_packet.sender, _packet.dstEid);
uint256 msgSize = _packet.message.length;
_assertMessageSize(msgSize, config.maxMessageSize);
totalNativeFee += _payExecutor(config.executor, _packet.dstEid, _packet.sender, msgSize, executorOptions);
// handle other workers
(uint256 verifierFee, bytesmemory packetBytes) = _payVerifier(_packet, validationOptions); //for ULN, it will be dvns
totalNativeFee += verifierFee;
encodedPacket = packetBytes;
}
// ======================= Virtual =======================// For implementation to overridefunction_payVerifier(
Packet calldata _packet,
WorkerOptions[] memory _options
) internalvirtualreturns (uint256 otherWorkerFees, bytesmemory encodedPacket);
// receive native token from endpointreceive() externalpayablevirtual{}
}
Contract Source Code
File 31 of 35: SendUln302.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { Packet } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol";
import { SetConfigParam } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol";
import { ExecutorConfig } from"../../SendLibBase.sol";
import { SendLibBaseE2, WorkerOptions } from"../../SendLibBaseE2.sol";
import { UlnConfig } from"../UlnBase.sol";
import { SendUlnBase } from"../SendUlnBase.sol";
/// @dev This is a gluing contract. It simply parses the requests and forward to the super.impl() accordingly./// @dev In this case, it combines the logic of SendUlnBase and SendLibBaseE2contractSendUln302isSendUlnBase, SendLibBaseE2{
uint32internalconstant CONFIG_TYPE_EXECUTOR =1;
uint32internalconstant CONFIG_TYPE_ULN =2;
errorLZ_ULN_InvalidConfigType(uint32 configType);
constructor(address _endpoint,
uint256 _treasuryGasLimit,
uint256 _treasuryGasForFeeCap
) SendLibBaseE2(_endpoint, _treasuryGasLimit, _treasuryGasForFeeCap) {}
// ============================ OnlyEndpoint ===================================// on the send side the user can config both the executor and the ULNfunctionsetConfig(address _oapp, SetConfigParam[] calldata _params) externaloverrideonlyEndpoint{
for (uint256 i =0; i < _params.length; i++) {
SetConfigParam calldata param = _params[i];
_assertSupportedEid(param.eid);
if (param.configType == CONFIG_TYPE_EXECUTOR) {
_setExecutorConfig(param.eid, _oapp, abi.decode(param.config, (ExecutorConfig)));
} elseif (param.configType == CONFIG_TYPE_ULN) {
_setUlnConfig(param.eid, _oapp, abi.decode(param.config, (UlnConfig)));
} else {
revert LZ_ULN_InvalidConfigType(param.configType);
}
}
}
// ============================ View ===================================functiongetConfig(uint32 _eid, address _oapp, uint32 _configType) externalviewoverridereturns (bytesmemory) {
if (_configType == CONFIG_TYPE_EXECUTOR) {
returnabi.encode(getExecutorConfig(_oapp, _eid));
} elseif (_configType == CONFIG_TYPE_ULN) {
returnabi.encode(getUlnConfig(_oapp, _eid));
} else {
revert LZ_ULN_InvalidConfigType(_configType);
}
}
functionversion() externalpureoverridereturns (uint64 major, uint8 minor, uint8 endpointVersion) {
return (3, 0, 2);
}
functionisSupportedEid(uint32 _eid) externalviewoverridereturns (bool) {
return _isSupportedEid(_eid);
}
// ============================ Internal ===================================function_quoteVerifier(address _sender,
uint32 _dstEid,
WorkerOptions[] memory _options
) internalviewoverridereturns (uint256) {
return _quoteDVNs(_sender, _dstEid, _options);
}
function_payVerifier(
Packet calldata _packet,
WorkerOptions[] memory _options
) internaloverridereturns (uint256 otherWorkerFees, bytesmemory encodedPacket) {
(otherWorkerFees, encodedPacket) = _payDVNs(fees, _packet, _options);
}
function_splitOptions(bytescalldata _options
) internalpureoverridereturns (bytesmemory, WorkerOptions[] memory) {
return _splitUlnOptions(_options);
}
}
Contract Source Code
File 32 of 35: SendUlnBase.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { Packet } from"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol";
import { PacketV1Codec } from"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol";
import { ILayerZeroDVN } from"./interfaces/ILayerZeroDVN.sol";
import { DVNOptions } from"./libs/DVNOptions.sol";
import { UlnOptions } from"./libs/UlnOptions.sol";
import { WorkerOptions } from"../SendLibBase.sol";
import { UlnConfig, UlnBase } from"./UlnBase.sol";
/// @dev includes the utility functions for checking ULN states and logicsabstractcontractSendUlnBaseisUlnBase{
eventDVNFeePaid(address[] requiredDVNs, address[] optionalDVNs, uint256[] fees);
function_splitUlnOptions(bytescalldata _options) internalpurereturns (bytesmemory, WorkerOptions[] memory) {
(bytesmemory executorOpts, bytesmemory dvnOpts) = UlnOptions.decode(_options);
if (dvnOpts.length==0) {
return (executorOpts, new WorkerOptions[](0));
}
WorkerOptions[] memory workerOpts =new WorkerOptions[](1);
workerOpts[0] = WorkerOptions(DVNOptions.WORKER_ID, dvnOpts);
return (executorOpts, workerOpts);
}
/// ---------- pay and assign jobs ----------function_payDVNs(mapping(address => uint256) storage _fees,
Packet memory _packet,
WorkerOptions[] memory _options
) internalreturns (uint256 totalFee, bytesmemory encodedPacket) {
bytesmemory packetHeader = PacketV1Codec.encodePacketHeader(_packet);
bytesmemory payload = PacketV1Codec.encodePayload(_packet);
bytes32 payloadHash =keccak256(payload);
uint32 dstEid = _packet.dstEid;
address sender = _packet.sender;
UlnConfig memory config = getUlnConfig(sender, dstEid);
// if options is not empty, it must be dvn optionsbytesmemory dvnOptions = _options.length==0 ? bytes("") : _options[0].options;
uint256[] memory dvnFees;
(totalFee, dvnFees) = _assignJobs(
_fees,
config,
ILayerZeroDVN.AssignJobParam(dstEid, packetHeader, payloadHash, config.confirmations, sender),
dvnOptions
);
encodedPacket =abi.encodePacked(packetHeader, payload);
emit DVNFeePaid(config.requiredDVNs, config.optionalDVNs, dvnFees);
}
function_assignJobs(mapping(address => uint256) storage _fees,
UlnConfig memory _ulnConfig,
ILayerZeroDVN.AssignJobParam memory _param,
bytesmemory dvnOptions
) internalreturns (uint256 totalFee, uint256[] memory dvnFees) {
(bytes[] memory optionsArray, uint8[] memory dvnIds) = DVNOptions.groupDVNOptionsByIdx(dvnOptions);
uint8 dvnsLength = _ulnConfig.requiredDVNCount + _ulnConfig.optionalDVNCount;
dvnFees =newuint256[](dvnsLength);
for (uint8 i =0; i < dvnsLength; ++i) {
address dvn = i < _ulnConfig.requiredDVNCount
? _ulnConfig.requiredDVNs[i]
: _ulnConfig.optionalDVNs[i - _ulnConfig.requiredDVNCount];
bytesmemory options ="";
for (uint256 j =0; j < dvnIds.length; ++j) {
if (dvnIds[j] == i) {
options = optionsArray[j];
break;
}
}
dvnFees[i] = ILayerZeroDVN(dvn).assignJob(_param, options);
if (dvnFees[i] >0) {
_fees[dvn] += dvnFees[i];
totalFee += dvnFees[i];
}
}
}
/// ---------- quote ----------function_quoteDVNs(address _sender,
uint32 _dstEid,
WorkerOptions[] memory _options
) internalviewreturns (uint256 totalFee) {
UlnConfig memory config = getUlnConfig(_sender, _dstEid);
// if options is not empty, it must be dvn optionsbytesmemory dvnOptions = _options.length==0 ? bytes("") : _options[0].options;
(bytes[] memory optionsArray, uint8[] memory dvnIndices) = DVNOptions.groupDVNOptionsByIdx(dvnOptions);
totalFee = _getFees(config, _dstEid, _sender, optionsArray, dvnIndices);
}
function_getFees(
UlnConfig memory _config,
uint32 _dstEid,
address _sender,
bytes[] memory _optionsArray,
uint8[] memory _dvnIds
) internalviewreturns (uint256 totalFee) {
// here we merge 2 list of dvns into 1 to allocate the indexed dvn options to the right dvnuint8 dvnsLength = _config.requiredDVNCount + _config.optionalDVNCount;
for (uint8 i =0; i < dvnsLength; ++i) {
address dvn = i < _config.requiredDVNCount
? _config.requiredDVNs[i]
: _config.optionalDVNs[i - _config.requiredDVNCount];
bytesmemory options ="";
// it is a double loop here. however, if the list is short, the cost is very acceptable.for (uint256 j =0; j < _dvnIds.length; ++j) {
if (_dvnIds[j] == i) {
options = _optionsArray[j];
break;
}
}
totalFee += ILayerZeroDVN(dvn).getFee(_dstEid, _config.confirmations, _sender, options);
}
}
}
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { Ownable } from"@openzeppelin/contracts/access/Ownable.sol";
// the formal properties are documented in the setter functionsstructUlnConfig {
uint64 confirmations;
// we store the length of required DVNs and optional DVNs instead of using DVN.length directly to save gasuint8 requiredDVNCount; // 0 indicate DEFAULT, NIL_DVN_COUNT indicate NONE (to override the value of default)uint8 optionalDVNCount; // 0 indicate DEFAULT, NIL_DVN_COUNT indicate NONE (to override the value of default)uint8 optionalDVNThreshold; // (0, optionalDVNCount]address[] requiredDVNs; // no duplicates. sorted an an ascending order. allowed overlap with optionalDVNsaddress[] optionalDVNs; // no duplicates. sorted an an ascending order. allowed overlap with requiredDVNs
}
structSetDefaultUlnConfigParam {
uint32 eid;
UlnConfig config;
}
/// @dev includes the utility functions for checking ULN states and logicsabstractcontractUlnBaseisOwnable{
addressprivateconstant DEFAULT_CONFIG =address(0);
// reserved values foruint8internalconstant DEFAULT =0;
uint8internalconstant NIL_DVN_COUNT =type(uint8).max;
uint64internalconstant NIL_CONFIRMATIONS =type(uint64).max;
// 127 to prevent total number of DVNs (127 * 2) exceeding uint8.max (255)// by limiting the total size, it would help constraint the design of DVNOptionsuint8privateconstant MAX_COUNT = (type(uint8).max-1) /2;
mapping(address oapp =>mapping(uint32 eid => UlnConfig)) internal ulnConfigs;
errorLZ_ULN_Unsorted();
errorLZ_ULN_InvalidRequiredDVNCount();
errorLZ_ULN_InvalidOptionalDVNCount();
errorLZ_ULN_AtLeastOneDVN();
errorLZ_ULN_InvalidOptionalDVNThreshold();
errorLZ_ULN_InvalidConfirmations();
errorLZ_ULN_UnsupportedEid(uint32 eid);
eventDefaultUlnConfigsSet(SetDefaultUlnConfigParam[] params);
eventUlnConfigSet(address oapp, uint32 eid, UlnConfig config);
// ============================ OnlyOwner ===================================/// @dev about the DEFAULT ULN config/// 1) its values are all LITERAL (e.g. 0 is 0). whereas in the oapp ULN config, 0 (default value) points to the default ULN config/// this design enables the oapp to point to DEFAULT config without explicitly setting the config/// 2) its configuration is more restrictive than the oapp ULN config that/// a) it must not use NIL value, where NIL is used only by oapps to indicate the LITERAL 0/// b) it must have at least one DVNfunctionsetDefaultUlnConfigs(SetDefaultUlnConfigParam[] calldata _params) externalonlyOwner{
for (uint256 i =0; i < _params.length; ++i) {
SetDefaultUlnConfigParam calldata param = _params[i];
// 2.a must not use NILif (param.config.requiredDVNCount == NIL_DVN_COUNT) revert LZ_ULN_InvalidRequiredDVNCount();
if (param.config.optionalDVNCount == NIL_DVN_COUNT) revert LZ_ULN_InvalidOptionalDVNCount();
if (param.config.confirmations == NIL_CONFIRMATIONS) revert LZ_ULN_InvalidConfirmations();
// 2.b must have at least one dvn
_assertAtLeastOneDVN(param.config);
_setConfig(DEFAULT_CONFIG, param.eid, param.config);
}
emit DefaultUlnConfigsSet(_params);
}
// ============================ View ===================================// @dev assuming most oapps use default, we get default as memory and custom as storage to save gasfunctiongetUlnConfig(address _oapp, uint32 _remoteEid) publicviewreturns (UlnConfig memory rtnConfig) {
UlnConfig storage defaultConfig = ulnConfigs[DEFAULT_CONFIG][_remoteEid];
UlnConfig storage customConfig = ulnConfigs[_oapp][_remoteEid];
// if confirmations is 0, use defaultuint64 confirmations = customConfig.confirmations;
if (confirmations == DEFAULT) {
rtnConfig.confirmations = defaultConfig.confirmations;
} elseif (confirmations != NIL_CONFIRMATIONS) {
// if confirmations is uint64.max, no block confirmations required
rtnConfig.confirmations = confirmations;
} // else do nothing, rtnConfig.confirmation is 0if (customConfig.requiredDVNCount == DEFAULT) {
if (defaultConfig.requiredDVNCount >0) {
// copy only if count > 0. save gas
rtnConfig.requiredDVNs = defaultConfig.requiredDVNs;
rtnConfig.requiredDVNCount = defaultConfig.requiredDVNCount;
} // else, do nothing
} else {
if (customConfig.requiredDVNCount != NIL_DVN_COUNT) {
rtnConfig.requiredDVNs = customConfig.requiredDVNs;
rtnConfig.requiredDVNCount = customConfig.requiredDVNCount;
} // else, do nothing
}
if (customConfig.optionalDVNCount == DEFAULT) {
if (defaultConfig.optionalDVNCount >0) {
// copy only if count > 0. save gas
rtnConfig.optionalDVNs = defaultConfig.optionalDVNs;
rtnConfig.optionalDVNCount = defaultConfig.optionalDVNCount;
rtnConfig.optionalDVNThreshold = defaultConfig.optionalDVNThreshold;
}
} else {
if (customConfig.optionalDVNCount != NIL_DVN_COUNT) {
rtnConfig.optionalDVNs = customConfig.optionalDVNs;
rtnConfig.optionalDVNCount = customConfig.optionalDVNCount;
rtnConfig.optionalDVNThreshold = customConfig.optionalDVNThreshold;
}
}
// the final value must have at least one dvn// it is possible that some default config result into 0 dvns
_assertAtLeastOneDVN(rtnConfig);
}
/// @dev Get the uln config without the default config for the given remoteEid.functiongetAppUlnConfig(address _oapp, uint32 _remoteEid) externalviewreturns (UlnConfig memory) {
return ulnConfigs[_oapp][_remoteEid];
}
// ============================ Internal ===================================function_setUlnConfig(uint32 _remoteEid, address _oapp, UlnConfig memory _param) internal{
_setConfig(_oapp, _remoteEid, _param);
// get ULN config again as a catch all to ensure the config is valid
getUlnConfig(_oapp, _remoteEid);
emit UlnConfigSet(_oapp, _remoteEid, _param);
}
/// @dev a supported Eid must have a valid default uln config, which has at least one dvnfunction_isSupportedEid(uint32 _remoteEid) internalviewreturns (bool) {
UlnConfig storage defaultConfig = ulnConfigs[DEFAULT_CONFIG][_remoteEid];
return defaultConfig.requiredDVNCount >0|| defaultConfig.optionalDVNThreshold >0;
}
function_assertSupportedEid(uint32 _remoteEid) internalview{
if (!_isSupportedEid(_remoteEid)) revert LZ_ULN_UnsupportedEid(_remoteEid);
}
// ============================ Private ===================================function_assertAtLeastOneDVN(UlnConfig memory _config) privatepure{
if (_config.requiredDVNCount ==0&& _config.optionalDVNThreshold ==0) revert LZ_ULN_AtLeastOneDVN();
}
/// @dev this private function is used in both setDefaultUlnConfigs and setUlnConfigfunction_setConfig(address _oapp, uint32 _eid, UlnConfig memory _param) private{
// @dev required dvns// if dvnCount == NONE, dvns list must be empty// if dvnCount == DEFAULT, dvn list must be empty// otherwise, dvnList.length == dvnCount and assert the list is validif (_param.requiredDVNCount == NIL_DVN_COUNT || _param.requiredDVNCount == DEFAULT) {
if (_param.requiredDVNs.length!=0) revert LZ_ULN_InvalidRequiredDVNCount();
} else {
if (_param.requiredDVNs.length!= _param.requiredDVNCount || _param.requiredDVNCount > MAX_COUNT)
revert LZ_ULN_InvalidRequiredDVNCount();
_assertNoDuplicates(_param.requiredDVNs);
}
// @dev optional dvns// if optionalDVNCount == NONE, optionalDVNs list must be empty and threshold must be 0// if optionalDVNCount == DEFAULT, optionalDVNs list must be empty and threshold must be 0// otherwise, optionalDVNs.length == optionalDVNCount, threshold > 0 && threshold <= optionalDVNCount and assert the list is valid// example use case: an oapp uses the DEFAULT 'required' but// a) use a custom 1/1 dvn (practically a required dvn), or// b) use a custom 2/3 dvnif (_param.optionalDVNCount == NIL_DVN_COUNT || _param.optionalDVNCount == DEFAULT) {
if (_param.optionalDVNs.length!=0) revert LZ_ULN_InvalidOptionalDVNCount();
if (_param.optionalDVNThreshold !=0) revert LZ_ULN_InvalidOptionalDVNThreshold();
} else {
if (_param.optionalDVNs.length!= _param.optionalDVNCount || _param.optionalDVNCount > MAX_COUNT)
revert LZ_ULN_InvalidOptionalDVNCount();
if (_param.optionalDVNThreshold ==0|| _param.optionalDVNThreshold > _param.optionalDVNCount)
revert LZ_ULN_InvalidOptionalDVNThreshold();
_assertNoDuplicates(_param.optionalDVNs);
}
// don't assert valid count here, as it needs to be validated along side default config
ulnConfigs[_oapp][_eid] = _param;
}
function_assertNoDuplicates(address[] memory _dvns) privatepure{
address lastDVN =address(0);
for (uint256 i =0; i < _dvns.length; i++) {
address dvn = _dvns[i];
if (dvn <= lastDVN) revert LZ_ULN_Unsorted(); // to ensure no duplicates
lastDVN = dvn;
}
}
}
Contract Source Code
File 35 of 35: UlnOptions.sol
// SPDX-License-Identifier: LZBL-1.2pragmasolidity ^0.8.20;import { SafeCast } from"@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ExecutorOptions } from"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/ExecutorOptions.sol";
import { DVNOptions } from"./DVNOptions.sol";
libraryUlnOptions{
usingSafeCastforuint256;
uint16internalconstant TYPE_1 =1; // legacy options type 1uint16internalconstant TYPE_2 =2; // legacy options type 2uint16internalconstant TYPE_3 =3;
errorLZ_ULN_InvalidWorkerOptions(uint256 cursor);
errorLZ_ULN_InvalidWorkerId(uint8 workerId);
errorLZ_ULN_InvalidLegacyType1Option();
errorLZ_ULN_InvalidLegacyType2Option();
errorLZ_ULN_UnsupportedOptionType(uint16 optionType);
/// @dev decode the options into executorOptions and dvnOptions/// @param _options the options can be either legacy options (type 1 or 2) or type 3 options/// @return executorOptions the executor options, share the same format of type 3 options/// @return dvnOptions the dvn options, share the same format of type 3 optionsfunctiondecode(bytescalldata _options
) internalpurereturns (bytesmemory executorOptions, bytesmemory dvnOptions) {
// at least 2 bytes for the option type, but can have no optionsif (_options.length<2) revert LZ_ULN_InvalidWorkerOptions(0);
uint16 optionsType =uint16(bytes2(_options[0:2]));
uint256 cursor =2;
// type3 options: [worker_option][worker_option]...// worker_option: [worker_id][option_size][option]// worker_id: uint8, option_size: uint16, option: bytesif (optionsType == TYPE_3) {
unchecked {
uint256 start = cursor;
uint8 lastWorkerId; // worker_id starts from 1, so 0 is an invalid worker_id// heuristic: we assume that the options are mostly EXECUTOR options only// checking the workerID can reduce gas usage for most caseswhile (cursor < _options.length) {
uint8 workerId =uint8(bytes1(_options[cursor:cursor +1]));
if (workerId ==0) revert LZ_ULN_InvalidWorkerId(0);
// workerId must equal to the lastWorkerId for the first option// so it is always skipped in the first option// this operation slices out options whenever the the scan finds a different workerIdif (lastWorkerId ==0) {
lastWorkerId = workerId;
} elseif (workerId != lastWorkerId) {
bytescalldata op = _options[start:cursor]; // slice out the last worker's options
(executorOptions, dvnOptions) = _insertWorkerOptions(
executorOptions,
dvnOptions,
lastWorkerId,
op
);
// reset the start cursor and lastWorkerId
start = cursor;
lastWorkerId = workerId;
}
++cursor; // for workerIduint16 size =uint16(bytes2(_options[cursor:cursor +2]));
if (size ==0) revert LZ_ULN_InvalidWorkerOptions(cursor);
cursor += size +2;
}
// the options length must be the same as the cursor at the endif (cursor != _options.length) revert LZ_ULN_InvalidWorkerOptions(cursor);
// if we have reached the end of the options and the options are not empty// we need to process the last worker's optionsif (_options.length>2) {
bytescalldata op = _options[start:cursor];
(executorOptions, dvnOptions) = _insertWorkerOptions(executorOptions, dvnOptions, lastWorkerId, op);
}
}
} else {
executorOptions = decodeLegacyOptions(optionsType, _options);
}
}
function_insertWorkerOptions(bytesmemory _executorOptions,
bytesmemory _dvnOptions,
uint8 _workerId,
bytescalldata _newOptions
) privatepurereturns (bytesmemory, bytesmemory) {
if (_workerId == ExecutorOptions.WORKER_ID) {
_executorOptions = _executorOptions.length==0
? _newOptions
: abi.encodePacked(_executorOptions, _newOptions);
} elseif (_workerId == DVNOptions.WORKER_ID) {
_dvnOptions = _dvnOptions.length==0 ? _newOptions : abi.encodePacked(_dvnOptions, _newOptions);
} else {
revert LZ_ULN_InvalidWorkerId(_workerId);
}
return (_executorOptions, _dvnOptions);
}
/// @dev decode the legacy options (type 1 or 2) into executorOptions/// @param _optionType the legacy option type/// @param _options the legacy options, which still has the option type in the first 2 bytes/// @return executorOptions the executor options, share the same format of type 3 options/// Data format:/// legacy type 1: [extraGas]/// legacy type 2: [extraGas][dstNativeAmt][dstNativeAddress]/// extraGas: uint256, dstNativeAmt: uint256, dstNativeAddress: bytesfunctiondecodeLegacyOptions(uint16 _optionType,
bytescalldata _options
) internalpurereturns (bytesmemory executorOptions) {
if (_optionType == TYPE_1) {
if (_options.length!=34) revert LZ_ULN_InvalidLegacyType1Option();
// execution gasuint128 executionGas =uint256(bytes32(_options[2:2+32])).toUint128();
// dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once// the result is a lzReceive option: [executor_id][option_size][option_type][execution_gas]// option_type: uint8, execution_gas: uint128// option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17
executorOptions =abi.encodePacked(
ExecutorOptions.WORKER_ID,
uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type
ExecutorOptions.OPTION_TYPE_LZRECEIVE,
executionGas
);
} elseif (_optionType == TYPE_2) {
// receiver size <= 32if (_options.length<=66|| _options.length>98) revert LZ_ULN_InvalidLegacyType2Option();
// execution gasuint128 executionGas =uint256(bytes32(_options[2:2+32])).toUint128();
// nativeDrop (amount + receiver)uint128 amount =uint256(bytes32(_options[34:34+32])).toUint128(); // offset 2 + 32bytes32 receiver;
unchecked {
uint256 receiverLen = _options.length-66; // offset 2 + 32 + 32
receiver =bytes32(_options[66:]);
receiver = receiver >> (8* (32- receiverLen)); // padding 0 to the left
}
// dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once// the result has one lzReceive option and one nativeDrop option:// [executor_id][lzReceive_option_size][option_type][execution_gas] +// [executor_id][nativeDrop_option_size][option_type][nativeDrop_amount][receiver]// option_type: uint8, execution_gas: uint128, nativeDrop_amount: uint128, receiver: bytes32// lzReceive_option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17// nativeDrop_option_size = len(option_type) + len(nativeDrop_amount) + len(receiver) = 1 + 16 + 32 = 49
executorOptions =abi.encodePacked(
ExecutorOptions.WORKER_ID,
uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type
ExecutorOptions.OPTION_TYPE_LZRECEIVE,
executionGas,
ExecutorOptions.WORKER_ID,
uint16(49), // 48 + 1, 32 + 16 for option_length, + 1 for option_type
ExecutorOptions.OPTION_TYPE_NATIVE_DROP,
amount,
receiver
);
} else {
revert LZ_ULN_UnsupportedOptionType(_optionType);
}
}
}