diff --git a/oapp/contracts/oapp/OApp.sol b/oapp/contracts/oapp/OApp.sol index 1e7a832..b58d1a6 100644 --- a/oapp/contracts/oapp/OApp.sol +++ b/oapp/contracts/oapp/OApp.sol @@ -2,9 +2,9 @@ pragma solidity ^0.8.20; -// @dev Import the 'MessagingFee' so it's exposed to OApp implementers +// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers // solhint-disable-next-line no-unused-import -import { OAppSender, MessagingFee } from "./OAppSender.sol"; +import { OAppSender, MessagingFee, MessagingReceipt } from "./OAppSender.sol"; // @dev Import the 'Origin' so it's exposed to OApp implementers // solhint-disable-next-line no-unused-import import { OAppReceiver, Origin } from "./OAppReceiver.sol"; @@ -18,9 +18,9 @@ abstract contract OApp is OAppSender, OAppReceiver { /** * @dev Constructor to initialize the OApp with the provided endpoint and owner. * @param _endpoint The address of the LOCAL LayerZero endpoint. - * @param _owner The address of the owner of the OApp. + * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. */ - constructor(address _endpoint, address _owner) OAppCore(_endpoint, _owner) {} + constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {} /** * @notice Retrieves the OApp version information. diff --git a/oapp/contracts/oapp/OAppCore.sol b/oapp/contracts/oapp/OAppCore.sol index d078abe..966e5d5 100644 --- a/oapp/contracts/oapp/OAppCore.sol +++ b/oapp/contracts/oapp/OAppCore.sol @@ -17,14 +17,17 @@ abstract contract OAppCore is IOAppCore, Ownable { mapping(uint32 eid => bytes32 peer) public peers; /** - * @dev Constructor to initialize the OAppCore with the provided endpoint and owner. + * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate. * @param _endpoint The address of the LOCAL Layer Zero endpoint. - * @param _owner The address of the owner of the OAppCore. + * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. + * + * @dev The delegate typically should be set as the owner of the contract. */ - constructor(address _endpoint, address _owner) { - _transferOwnership(_owner); + constructor(address _endpoint, address _delegate) { endpoint = ILayerZeroEndpointV2(_endpoint); - endpoint.setDelegate(_owner); // @dev By default, the owner is the delegate + + if (_delegate == address(0)) revert InvalidDelegate(); + endpoint.setDelegate(_delegate); } /** @@ -60,7 +63,6 @@ abstract contract OAppCore is IOAppCore, Ownable { * * @dev Only the owner/admin of the OApp can call this function. * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract. - * @dev Defaults to the owner of the OApp. */ function setDelegate(address _delegate) public onlyOwner { endpoint.setDelegate(_delegate); diff --git a/oapp/contracts/oapp/OAppReceiver.sol b/oapp/contracts/oapp/OAppReceiver.sol index 76bb2c3..c797f6f 100644 --- a/oapp/contracts/oapp/OAppReceiver.sol +++ b/oapp/contracts/oapp/OAppReceiver.sol @@ -2,14 +2,14 @@ pragma solidity ^0.8.20; -import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol"; +import { IOAppReceiver, Origin } from "./interfaces/IOAppReceiver.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OAppReceiver * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers. */ -abstract contract OAppReceiver is ILayerZeroReceiver, OAppCore { +abstract contract OAppReceiver is IOAppReceiver, OAppCore { // Custom error message for when the caller is not the registered endpoint/ error OnlyEndpoint(address addr); @@ -23,13 +23,24 @@ abstract contract OAppReceiver is ILayerZeroReceiver, OAppCore { * @return receiverVersion The version of the OAppReceiver.sol contract. * * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented. - * ie. this is a SEND only OApp. + * ie. this is a RECEIVE only OApp. * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions. */ function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) { return (0, RECEIVER_VERSION); } + /** + * @notice Retrieves the address responsible for 'sending' composeMsg's to the Endpoint. + * @return sender The address responsible for 'sending' composeMsg's to the Endpoint. + * + * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer. + * @dev The default sender IS the OApp implementer. + */ + function composeMsgSender() public view virtual returns (address sender) { + return address(this); + } + /** * @notice Checks if the path initialization is allowed based on the provided origin. * @param origin The origin information containing the source endpoint and sender address. diff --git a/oapp/contracts/oapp/OAppSender.sol b/oapp/contracts/oapp/OAppSender.sol index e9209b5..891f34c 100644 --- a/oapp/contracts/oapp/OAppSender.sol +++ b/oapp/contracts/oapp/OAppSender.sol @@ -27,7 +27,7 @@ abstract contract OAppSender is OAppCore { * @return receiverVersion The version of the OAppReceiver.sol contract. * * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented. - * ie. this is a RECEIVE only OApp. + * ie. this is a SEND only OApp. * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions */ function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) { diff --git a/oapp/contracts/oapp/examples/OmniCounter.sol b/oapp/contracts/oapp/examples/OmniCounter.sol index cc21492..ec394b6 100644 --- a/oapp/contracts/oapp/examples/OmniCounter.sol +++ b/oapp/contracts/oapp/examples/OmniCounter.sol @@ -57,7 +57,7 @@ contract OmniCounter is ILayerZeroComposer, OApp, OAppPreCrimeSimulator { mapping(uint32 srcEid => uint256 count) public inboundCount; mapping(uint32 dstEid => uint256 count) public outboundCount; - constructor(address _endpoint, address _owner) OApp(_endpoint, _owner) { + constructor(address _endpoint, address _delegate) OApp(_endpoint, _delegate) { admin = msg.sender; eid = ILayerZeroEndpointV2(_endpoint).eid(); } diff --git a/oapp/contracts/oapp/examples/OmniCounterPreCrime.sol b/oapp/contracts/oapp/examples/OmniCounterPreCrime.sol index 280f236..f9f2aac 100644 --- a/oapp/contracts/oapp/examples/OmniCounterPreCrime.sol +++ b/oapp/contracts/oapp/examples/OmniCounterPreCrime.sol @@ -13,7 +13,7 @@ contract OmniCounterPreCrime is PreCrime { uint256 outboundCount; } - constructor(address _endpoint, address _counter, address _owner) PreCrime(_endpoint, _counter, _owner) {} + constructor(address _endpoint, address _counter) PreCrime(_endpoint, _counter) {} function buildSimulationResult() external view override returns (bytes memory) { address payable payableSimulator = payable(simulator); diff --git a/oapp/contracts/oapp/interfaces/IOAppCore.sol b/oapp/contracts/oapp/interfaces/IOAppCore.sol index ffa943e..ad7af41 100644 --- a/oapp/contracts/oapp/interfaces/IOAppCore.sol +++ b/oapp/contracts/oapp/interfaces/IOAppCore.sol @@ -12,6 +12,7 @@ interface IOAppCore { error OnlyPeer(uint32 eid, bytes32 sender); error NoPeer(uint32 eid); error InvalidEndpointCall(); + error InvalidDelegate(); // Event emitted when a peer (OApp) is set for a corresponding endpoint event PeerSet(uint32 eid, bytes32 peer); diff --git a/oapp/contracts/oapp/interfaces/IOAppReceiver.sol b/oapp/contracts/oapp/interfaces/IOAppReceiver.sol new file mode 100644 index 0000000..425f9f5 --- /dev/null +++ b/oapp/contracts/oapp/interfaces/IOAppReceiver.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol"; + +interface IOAppReceiver is ILayerZeroReceiver { + /** + * @notice Retrieves the address responsible for 'sending' composeMsg's to the Endpoint. + * @return sender The address responsible for 'sending' composeMsg's to the Endpoint. + * + * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer. + * @dev The default sender IS the OApp implementer. + */ + function composeMsgSender() external view returns (address sender); +} diff --git a/oapp/contracts/oft/OFT.sol b/oapp/contracts/oft/OFT.sol new file mode 100644 index 0000000..c96364e --- /dev/null +++ b/oapp/contracts/oft/OFT.sol @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import { IOFT, OFTCore } from "./OFTCore.sol"; + +/** + * @title OFT Contract + * @dev OFT is an ERC-20 token that extends the functionality of the OFTCore contract. + */ +abstract contract OFT is OFTCore, ERC20 { + /** + * @dev Constructor for the OFT contract. + * @param _name The name of the OFT. + * @param _symbol The symbol of the OFT. + * @param _lzEndpoint The LayerZero endpoint address. + * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. + */ + constructor( + string memory _name, + string memory _symbol, + address _lzEndpoint, + address _delegate + ) ERC20(_name, _symbol) OFTCore(decimals(), _lzEndpoint, _delegate) {} + + /** + * @notice Retrieves interfaceID and the version of the OFT. + * @return interfaceId The interface ID. + * @return version The version. + * + * @dev interfaceId: This specific interface ID is '0x02e49c2c'. + * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs. + * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented. + * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1) + */ + function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) { + return (type(IOFT).interfaceId, 1); + } + + /** + * @dev Retrieves the address of the underlying ERC20 implementation. + * @return The address of the OFT token. + * + * @dev In the case of OFT, address(this) and erc20 are the same contract. + */ + function token() external view returns (address) { + return address(this); + } + + /** + * @notice Indicates whether the OFT contract requires approval of the 'token()' to send. + * @return requiresApproval Needs approval of the underlying token implementation. + * + * @dev In the case of OFT where the contract IS the token, approval is NOT required. + */ + function approvalRequired() external pure virtual returns (bool) { + return false; + } + + /** + * @dev Burns tokens from the sender's specified balance. + * @param _amountLD The amount of tokens to send in local decimals. + * @param _minAmountLD The minimum amount to send in local decimals. + * @param _dstEid The destination chain ID. + * @return amountSentLD The amount sent in local decimals. + * @return amountReceivedLD The amount received in local decimals on the remote. + */ + function _debit( + uint256 _amountLD, + uint256 _minAmountLD, + uint32 _dstEid + ) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) { + (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid); + + // @dev In NON-default OFT, amountSentLD could be 100, with a 10% fee, the amountReceivedLD amount is 90, + // therefore amountSentLD CAN differ from amountReceivedLD. + + // @dev Default OFT burns on src. + _burn(msg.sender, amountSentLD); + } + + /** + * @dev Credits tokens to the specified address. + * @param _to The address to credit the tokens to. + * @param _amountLD The amount of tokens to credit in local decimals. + * @dev _srcEid The source chain ID. + * @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals. + */ + function _credit( + address _to, + uint256 _amountLD, + uint32 /*_srcEid*/ + ) internal virtual override returns (uint256 amountReceivedLD) { + // @dev Default OFT mints on dst. + _mint(_to, _amountLD); + // @dev In the case of NON-default OFT, the _amountLD MIGHT not be == amountReceivedLD. + return _amountLD; + } +} diff --git a/oapp/contracts/oft/OFTAdapter.sol b/oapp/contracts/oft/OFTAdapter.sol new file mode 100644 index 0000000..a3b4845 --- /dev/null +++ b/oapp/contracts/oft/OFTAdapter.sol @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +import { IERC20Metadata, IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; +import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import { IOFT, OFTCore } from "./OFTCore.sol"; + +/** + * @title OFTAdapter Contract + * @dev OFTAdapter is a contract that adapts an ERC-20 token to the OFT functionality. + * + * @dev For existing ERC20 tokens, this can be used to convert the token to crosschain compatibility. + * @dev WARNING: ONLY 1 of these should exist for a given global mesh, + * unless you make a NON-default implementation of OFT and needs to be done very carefully. + * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out. + * IF the 'innerToken' applies something like a transfer fee, the default will NOT work... + * a pre/post balance check will need to be done to calculate the amountSentLD/amountReceivedLD. + */ +abstract contract OFTAdapter is OFTCore { + using SafeERC20 for IERC20; + + IERC20 internal immutable innerToken; + + /** + * @dev Constructor for the OFTAdapter contract. + * @param _token The address of the ERC-20 token to be adapted. + * @param _lzEndpoint The LayerZero endpoint address. + * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. + */ + constructor( + address _token, + address _lzEndpoint, + address _delegate + ) OFTCore(IERC20Metadata(_token).decimals(), _lzEndpoint, _delegate) { + innerToken = IERC20(_token); + } + + /** + * @notice Retrieves interfaceID and the version of the OFT. + * @return interfaceId The interface ID. + * @return version The version. + * + * @dev interfaceId: This specific interface ID is '0x02e49c2c'. + * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs. + * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented. + * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1) + */ + function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) { + return (type(IOFT).interfaceId, 1); + } + + /** + * @dev Retrieves the address of the underlying ERC20 implementation. + * @return The address of the adapted ERC-20 token. + * + * @dev In the case of OFTAdapter, address(this) and erc20 are NOT the same contract. + */ + function token() external view returns (address) { + return address(innerToken); + } + + /** + * @notice Indicates whether the OFT contract requires approval of the 'token()' to send. + * @return requiresApproval Needs approval of the underlying token implementation. + * + * @dev In the case of default OFTAdapter, approval is required. + * @dev In non-default OFTAdapter contracts with something like mint and burn privileges, it would NOT need approval. + */ + function approvalRequired() external pure virtual returns (bool) { + return true; + } + + /** + * @dev Burns tokens from the sender's specified balance, ie. pull method. + * @param _amountLD The amount of tokens to send in local decimals. + * @param _minAmountLD The minimum amount to send in local decimals. + * @param _dstEid The destination chain ID. + * @return amountSentLD The amount sent in local decimals. + * @return amountReceivedLD The amount received in local decimals on the remote. + * + * @dev msg.sender will need to approve this _amountLD of tokens to be locked inside of the contract. + * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out. + * IF the 'innerToken' applies something like a transfer fee, the default will NOT work... + * a pre/post balance check will need to be done to calculate the amountReceivedLD. + */ + function _debit( + uint256 _amountLD, + uint256 _minAmountLD, + uint32 _dstEid + ) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) { + (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid); + // @dev Lock tokens by moving them into this contract from the caller. + innerToken.safeTransferFrom(msg.sender, address(this), amountSentLD); + } + + /** + * @dev Credits tokens to the specified address. + * @param _to The address to credit the tokens to. + * @param _amountLD The amount of tokens to credit in local decimals. + * @dev _srcEid The source chain ID. + * @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals. + * + * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out. + * IF the 'innerToken' applies something like a transfer fee, the default will NOT work... + * a pre/post balance check will need to be done to calculate the amountReceivedLD. + */ + function _credit( + address _to, + uint256 _amountLD, + uint32 /*_srcEid*/ + ) internal virtual override returns (uint256 amountReceivedLD) { + // @dev Unlock the tokens and transfer to the recipient. + innerToken.safeTransfer(_to, _amountLD); + // @dev In the case of NON-default OFTAdapter, the amountLD MIGHT not be == amountReceivedLD. + return _amountLD; + } +} diff --git a/oapp/contracts/oft/OFTCore.sol b/oapp/contracts/oft/OFTCore.sol new file mode 100644 index 0000000..495584d --- /dev/null +++ b/oapp/contracts/oft/OFTCore.sol @@ -0,0 +1,382 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +import { OApp, Origin } from "../oapp/OApp.sol"; +import { OAppOptionsType3 } from "../oapp/libs/OAppOptionsType3.sol"; +import { IOAppMsgInspector } from "../oapp/interfaces/IOAppMsgInspector.sol"; + +import { OAppPreCrimeSimulator } from "../precrime/OAppPreCrimeSimulator.sol"; + +import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from "./interfaces/IOFT.sol"; +import { OFTMsgCodec } from "./libs/OFTMsgCodec.sol"; +import { OFTComposeMsgCodec } from "./libs/OFTComposeMsgCodec.sol"; + +/** + * @title OFTCore + * @dev Abstract contract for the OftChain (OFT) token. + */ +abstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 { + using OFTMsgCodec for bytes; + using OFTMsgCodec for bytes32; + + // @notice Provides a conversion rate when swapping between denominations of SD and LD + // - shareDecimals == SD == shared Decimals + // - localDecimals == LD == local decimals + // @dev Considers that tokens have different decimal amounts on various chains. + // @dev eg. + // For a token + // - locally with 4 decimals --> 1.2345 => uint(12345) + // - remotely with 2 decimals --> 1.23 => uint(123) + // - The conversion rate would be 10 ** (4 - 2) = 100 + // @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote, + // you can only display 1.23 -> uint(123). + // @dev To preserve the dust that would otherwise be lost on that conversion, + // we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh + uint256 public immutable decimalConversionRate; + + // @notice Msg types that are used to identify the various OFT operations. + // @dev This can be extended in child contracts for non-default oft operations + // @dev These values are used in things like combineOptions() in OAppOptionsType3.sol. + uint16 public constant SEND = 1; + uint16 public constant SEND_AND_CALL = 2; + + // Address of an optional contract to inspect both 'message' and 'options' + address public msgInspector; + event MsgInspectorSet(address inspector); + + /** + * @dev Constructor. + * @param _localDecimals The decimals of the token on the local chain (this chain). + * @param _endpoint The address of the LayerZero endpoint. + * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. + */ + constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) { + if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals(); + decimalConversionRate = 10 ** (_localDecimals - sharedDecimals()); + } + + /** + * @dev Retrieves the shared decimals of the OFT. + * @return The shared decimals of the OFT. + * + * @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap + * Lowest common decimal denominator between chains. + * Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64). + * For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller. + * ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615 + */ + function sharedDecimals() public pure virtual returns (uint8) { + return 6; + } + + /** + * @dev Sets the message inspector address for the OFT. + * @param _msgInspector The address of the message inspector. + * + * @dev This is an optional contract that can be used to inspect both 'message' and 'options'. + * @dev Set it to address(0) to disable it, or set it to a contract address to enable it. + */ + function setMsgInspector(address _msgInspector) public virtual onlyOwner { + msgInspector = _msgInspector; + emit MsgInspectorSet(_msgInspector); + } + + /** + * @notice Provides a quote for OFT-related operations. + * @param _sendParam The parameters for the send operation. + * @return oftLimit The OFT limit information. + * @return oftFeeDetails The details of OFT fees. + * @return oftReceipt The OFT receipt information. + */ + function quoteOFT( + SendParam calldata _sendParam + ) + external + view + virtual + returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt) + { + uint256 minAmountLD = 0; // Unused in the default implementation. + uint256 maxAmountLD = type(uint64).max; // Unused in the default implementation. + oftLimit = OFTLimit(minAmountLD, maxAmountLD); + + // Unused in the default implementation; reserved for future complex fee details. + oftFeeDetails = new OFTFeeDetail[](0); + + // @dev This is the same as the send() operation, but without the actual send. + // - amountSentLD is the amount in local decimals that would be sent from the sender. + // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance. + // @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does. + (uint256 amountSentLD, uint256 amountReceivedLD) = _debitView( + _sendParam.amountLD, + _sendParam.minAmountLD, + _sendParam.dstEid + ); + oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD); + } + + /** + * @notice Provides a quote for the send() operation. + * @param _sendParam The parameters for the send() operation. + * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token. + * @return msgFee The calculated LayerZero messaging fee from the send() operation. + * + * @dev MessagingFee: LayerZero msg fee + * - nativeFee: The native fee. + * - lzTokenFee: The lzToken fee. + */ + function quoteSend( + SendParam calldata _sendParam, + bool _payInLzToken + ) external view virtual returns (MessagingFee memory msgFee) { + // @dev mock the amount to receive, this is the same operation used in the send(). + // The quote is as similar as possible to the actual send() operation. + (, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid); + + // @dev Builds the options and OFT message to quote in the endpoint. + (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD); + + // @dev Calculates the LayerZero fee for the send() operation. + return _quote(_sendParam.dstEid, message, options, _payInLzToken); + } + + /** + * @dev Executes the send operation. + * @param _sendParam The parameters for the send operation. + * @param _fee The calculated fee for the send() operation. + * - nativeFee: The native fee. + * - lzTokenFee: The lzToken fee. + * @param _refundAddress The address to receive any excess funds. + * @return msgReceipt The receipt for the send operation. + * @return oftReceipt The OFT receipt information. + * + * @dev MessagingReceipt: LayerZero msg receipt + * - guid: The unique identifier for the sent message. + * - nonce: The nonce of the sent message. + * - fee: The LayerZero fee incurred for the message. + */ + function send( + SendParam calldata _sendParam, + MessagingFee calldata _fee, + address _refundAddress + ) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) { + // @dev Applies the token transfers regarding this send() operation. + // - amountSentLD is the amount in local decimals that was ACTUALLY sent from the sender. + // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance. + (uint256 amountSentLD, uint256 amountReceivedLD) = _debit( + _sendParam.amountLD, + _sendParam.minAmountLD, + _sendParam.dstEid + ); + + // @dev Builds the options and OFT message to quote in the endpoint. + (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD); + + // @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt. + msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress); + // @dev Formulate the OFT receipt. + oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD); + + emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD); + } + + /** + * @dev Internal function to build the message and options. + * @param _sendParam The parameters for the send() operation. + * @param _amountLD The amount in local decimals. + * @return message The encoded message. + * @return options The encoded options. + */ + function _buildMsgAndOptions( + SendParam calldata _sendParam, + uint256 _amountLD + ) internal view virtual returns (bytes memory message, bytes memory options) { + bool hasCompose; + // @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is. + (message, hasCompose) = OFTMsgCodec.encode( + _sendParam.to, + _toSD(_amountLD), + // @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote. + // EVEN if you dont require an arbitrary payload to be sent... eg. '0x01' + _sendParam.composeMsg + ); + // @dev Change the msg type depending if its composed or not. + uint16 msgType = hasCompose ? SEND_AND_CALL : SEND; + // @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3. + options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions); + + // @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector. + // @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean + if (msgInspector != address(0)) IOAppMsgInspector(msgInspector).inspect(message, options); + } + + /** + * @dev Internal function to handle the receive on the LayerZero endpoint. + * @param _origin The origin information. + * - srcEid: The source chain endpoint ID. + * - sender: The sender address from the src chain. + * - nonce: The nonce of the LayerZero message. + * @param _guid The unique identifier for the received LayerZero message. + * @param _message The encoded message. + * @dev _executor The address of the executor. + * @dev _extraData Additional data. + */ + function _lzReceive( + Origin calldata _origin, + bytes32 _guid, + bytes calldata _message, + address /*_executor*/, // @dev unused in the default implementation. + bytes calldata /*_extraData*/ // @dev unused in the default implementation. + ) internal virtual override { + // @dev The src sending chain doesnt know the address length on this chain (potentially non-evm) + // Thus everything is bytes32() encoded in flight. + address toAddress = _message.sendTo().bytes32ToAddress(); + // @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals + uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid); + + if (_message.isComposed()) { + // @dev Proprietary composeMsg format for the OFT. + bytes memory composeMsg = OFTComposeMsgCodec.encode( + _origin.nonce, + _origin.srcEid, + amountReceivedLD, + _message.composeMsg() + ); + + // @dev Stores the lzCompose payload that will be executed in a separate tx. + // Standardizes functionality for executing arbitrary contract invocation on some non-evm chains. + // @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed. + // @dev The index is used when a OApp needs to compose multiple msgs on lzReceive. + // For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0. + endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg); + } + + emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD); + } + + /** + * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive. + * @param _origin The origin information. + * - srcEid: The source chain endpoint ID. + * - sender: The sender address from the src chain. + * - nonce: The nonce of the LayerZero message. + * @param _guid The unique identifier for the received LayerZero message. + * @param _message The LayerZero message. + * @param _executor The address of the off-chain executor. + * @param _extraData Arbitrary data passed by the msg executor. + * + * @dev Enables the preCrime simulator to mock sending lzReceive() messages, + * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver. + */ + function _lzReceiveSimulate( + Origin calldata _origin, + bytes32 _guid, + bytes calldata _message, + address _executor, + bytes calldata _extraData + ) internal virtual override { + _lzReceive(_origin, _guid, _message, _executor, _extraData); + } + + /** + * @dev Check if the peer is considered 'trusted' by the OApp. + * @param _eid The endpoint ID to check. + * @param _peer The peer to check. + * @return Whether the peer passed is considered 'trusted' by the OApp. + * + * @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source. + */ + function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) { + return peers[_eid] == _peer; + } + + /** + * @dev Internal function to remove dust from the given local decimal amount. + * @param _amountLD The amount in local decimals. + * @return amountLD The amount after removing dust. + * + * @dev Prevents the loss of dust when moving amounts between chains with different decimals. + * @dev eg. uint(123) with a conversion rate of 100 becomes uint(100). + */ + function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) { + return (_amountLD / decimalConversionRate) * decimalConversionRate; + } + + /** + * @dev Internal function to convert an amount from shared decimals into local decimals. + * @param _amountSD The amount in shared decimals. + * @return amountLD The amount in local decimals. + */ + function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) { + return _amountSD * decimalConversionRate; + } + + /** + * @dev Internal function to convert an amount from local decimals into shared decimals. + * @param _amountLD The amount in local decimals. + * @return amountSD The amount in shared decimals. + */ + function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) { + return uint64(_amountLD / decimalConversionRate); + } + + /** + * @dev Internal function to mock the amount mutation from a OFT debit() operation. + * @param _amountLD The amount to send in local decimals. + * @param _minAmountLD The minimum amount to send in local decimals. + * @dev _dstEid The destination endpoint ID. + * @return amountSentLD The amount sent, in local decimals. + * @return amountReceivedLD The amount to be received on the remote chain, in local decimals. + * + * @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote. + */ + function _debitView( + uint256 _amountLD, + uint256 _minAmountLD, + uint32 /*_dstEid*/ + ) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) { + // @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token. + amountSentLD = _removeDust(_amountLD); + // @dev The amount to send is the same as amount received in the default implementation. + amountReceivedLD = amountSentLD; + + // @dev Check for slippage. + if (amountReceivedLD < _minAmountLD) { + revert SlippageExceeded(amountReceivedLD, _minAmountLD); + } + } + + /** + * @dev Internal function to perform a debit operation. + * @param _amountLD The amount to send in local decimals. + * @param _minAmountLD The minimum amount to send in local decimals. + * @param _dstEid The destination endpoint ID. + * @return amountSentLD The amount sent in local decimals. + * @return amountReceivedLD The amount received in local decimals on the remote. + * + * @dev Defined here but are intended to be overriden depending on the OFT implementation. + * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD. + */ + function _debit( + uint256 _amountLD, + uint256 _minAmountLD, + uint32 _dstEid + ) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD); + + /** + * @dev Internal function to perform a credit operation. + * @param _to The address to credit. + * @param _amountLD The amount to credit in local decimals. + * @param _srcEid The source endpoint ID. + * @return amountReceivedLD The amount ACTUALLY received in local decimals. + * + * @dev Defined here but are intended to be overriden depending on the OFT implementation. + * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD. + */ + function _credit( + address _to, + uint256 _amountLD, + uint32 _srcEid + ) internal virtual returns (uint256 amountReceivedLD); +} diff --git a/oapp/contracts/oft/OFTPrecrime.sol b/oapp/contracts/oft/OFTPrecrime.sol new file mode 100644 index 0000000..5797bba --- /dev/null +++ b/oapp/contracts/oft/OFTPrecrime.sol @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +// import { IOApp } from "../../interfaces/IOApp.sol"; +// import { IOFT } from "./interfaces/IOFT.sol"; +// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +// import { OFTAdapter } from "./OFTAdapter.sol"; + +//contract OFTPreCrime is PreCrime { +// address public oft; +// uint256 public EXPECTED_GLOBAL_SUPPLY; +// +// constructor(address _endpoint, address _oft) PreCrime(_endpoint) { +// oft = _oft; +// } +// +// struct SimulationResult { +// uint256 totalSupplyLD; +// bool isAdapter; +// } +// +// // @dev only necessary when its exclusive 'OFT', NOT 'OFTAdapter' type +// // sum of all tokens in the oft network, it can change, but this will need to be updated for pre-Crime to pass +// function setGlobalSupply(uint256 _globalSupply) public onlyPreCrimeAdmin { +// EXPECTED_GLOBAL_SUPPLY = _globalSupply; +// } +// +// // ------------------------------- +// // PreCrime +// function _receiver() internal view override returns (address) { +// return address(oft); +// } +// +// function _preCrime(bytes[] memory _simulation) internal view override returns (uint16 code, bytes memory reason) { +// uint256 globalSupply; +// uint256 expectedGlobalSupply = EXPECTED_GLOBAL_SUPPLY; +// +// // @dev indicates that there is an 'OFTAdapter' on one of the chains, not necessarily this local chain +// bool isOFTAdapter; +// +// for (uint256 i = 0; i < _simulation.length; i++) { +// SimulationResult memory result = abi.decode(_simulation[i], (SimulationResult)); +// +// if (result.isAdapter) { +// // @dev does not support multiple' 'OFTAdapter' contracts for a given oft mesh +// if (isOFTAdapter) return (CODE_PRECRIME_FAILURE, "OFTPreCrime: multiple OFTAdapters found"); +// isOFTAdapter = true; +// +// expectedGlobalSupply = result.totalSupplyLD; +// } else { +// globalSupply += result.totalSupplyLD; +// } +// } +// +// if (isOFTAdapter && globalSupply > expectedGlobalSupply) { +// // @dev expectedGlobal supply for an 'OFTAdapter' can be slightly higher due to users sending tokens direct +// // to the OFTAdapter contract, cant check explicitly "==" +// return (CODE_PRECRIME_FAILURE, "OFTPreCrime: globalSupply > expectedGlobalSupply"); +// } else if (globalSupply != expectedGlobalSupply) { +// // @dev exclusively 'OFT', NOT 'OFTAdapter' instances, balances should be exactly "==" +// return (CODE_PRECRIME_FAILURE, "OFTPreCrime: globalSupply != expectedGlobalSupply"); +// } else { +// return (CODE_SUCCESS, ""); +// } +// } +// +// function simulationCallback() external view override returns (bytes memory result) { +// address token = IOFT(oft).token(); +// +// // @dev checks if the corresponding _oft on this chain is an adapter version, or returns false if its regular 'OFT' +// // eg. 'OFTAdapter' lock/unlock tokens from an external token contract, vs. regular 'OFT' mints/burns +// bool isAdapter = token != oft; +// +// // @dev for 'OFTAdapter' the total supply is the total amount locked, otherwise its the totalSupply of oft tokens on the chain +// uint256 totalSupply = isAdapter ? IERC20(token).balanceOf(oft) : IERC20(oft).totalSupply(); +// +// return abi.encode(SimulationResult(totalSupply, isAdapter)); +// } +// +// function _simulate(Packet[] calldata _packets) internal override returns (uint16 code, bytes memory simulation) { +// (bool success, bytes memory result) = oft.call{value: msg.value}( +// abi.encodeWithSelector(IOApp.lzReceiveAndRevert.selector, _packets) +// ); +// require(!success, "OFTPreCrime: simulationCallback should be called via revert"); +// +// (, result) = _parseRevertResult(result, LzReceiveRevert.selector); +// return (CODE_SUCCESS, result); +// } +// +// // @dev need to ensure that all preCrimePeers are present inside of the results passed into _checkResultsCompleteness() +// // when checking oft preCrime we always want every simulation/result from the remote peers +// function _getPreCrimePeers( +// Packet[] calldata /*_packets*/ +// ) internal view override returns (uint32[] memory eids, bytes32[] memory peers) { +// // @dev assumes that the preCrimeEids is the full list of oft eids for this oft mesh +// return (preCrimeEids, preCrimePeers); +// } +//} diff --git a/oapp/contracts/oft/interfaces/IOFT.sol b/oapp/contracts/oft/interfaces/IOFT.sol new file mode 100644 index 0000000..2ad0421 --- /dev/null +++ b/oapp/contracts/oft/interfaces/IOFT.sol @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +import { MessagingReceipt, MessagingFee } from "../../oapp/OAppSender.sol"; + +/** + * @dev Struct representing token parameters for the OFT send() operation. + */ +struct SendParam { + uint32 dstEid; // Destination endpoint ID. + bytes32 to; // Recipient address. + uint256 amountLD; // Amount to send in local decimals. + uint256 minAmountLD; // Minimum amount to send in local decimals. + bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message. + bytes composeMsg; // The composed message for the send() operation. + bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations. +} + +/** + * @dev Struct representing OFT limit information. + * @dev These amounts can change dynamically and are up the the specific oft implementation. + */ +struct OFTLimit { + uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient. + uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient. +} + +/** + * @dev Struct representing OFT receipt information. + */ +struct OFTReceipt { + uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals. + // @dev In non-default implementations, the amountReceivedLD COULD differ from this value. + uint256 amountReceivedLD; // Amount of tokens to be received on the remote side. +} + +/** + * @dev Struct representing OFT fee details. + * @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI. + */ +struct OFTFeeDetail { + int256 feeAmountLD; // Amount of the fee in local decimals. + string description; // Description of the fee. +} + +/** + * @title IOFT + * @dev Interface for the OftChain (OFT) token. + * @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well. + * @dev This specific interface ID is '0x02e49c2c'. + */ +interface IOFT { + // Custom error messages + error InvalidLocalDecimals(); + error SlippageExceeded(uint256 amountLD, uint256 minAmountLD); + + // Events + event OFTSent( + bytes32 indexed guid, // GUID of the OFT message. + uint32 dstEid, // Destination Endpoint ID. + address indexed fromAddress, // Address of the sender on the src chain. + uint256 amountLD // Amount of tokens sent in local decimals. + ); + event OFTReceived( + bytes32 indexed guid, // GUID of the OFT message. + uint32 srcEid, // Source Endpoint ID. + address indexed toAddress, // Address of the recipient on the dst chain. + uint256 amountLD // Amount of tokens received in local decimals. + ); + + /** + * @notice Retrieves interfaceID and the version of the OFT. + * @return interfaceId The interface ID. + * @return version The version. + * + * @dev interfaceId: This specific interface ID is '0x02e49c2c'. + * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs. + * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented. + * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1) + */ + function oftVersion() external view returns (bytes4 interfaceId, uint64 version); + + /** + * @notice Retrieves the address of the token associated with the OFT. + * @return token The address of the ERC20 token implementation. + */ + function token() external view returns (address); + + /** + * @notice Indicates whether the OFT contract requires approval of the 'token()' to send. + * @return requiresApproval Needs approval of the underlying token implementation. + * + * @dev Allows things like wallet implementers to determine integration requirements, + * without understanding the underlying token implementation. + */ + function approvalRequired() external view returns (bool); + + /** + * @notice Retrieves the shared decimals of the OFT. + * @return sharedDecimals The shared decimals of the OFT. + */ + function sharedDecimals() external view returns (uint8); + + /** + * @notice Provides a quote for OFT-related operations. + * @param _sendParam The parameters for the send operation. + * @return limit The OFT limit information. + * @return oftFeeDetails The details of OFT fees. + * @return receipt The OFT receipt information. + */ + function quoteOFT( + SendParam calldata _sendParam + ) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory); + + /** + * @notice Provides a quote for the send() operation. + * @param _sendParam The parameters for the send() operation. + * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token. + * @return fee The calculated LayerZero messaging fee from the send() operation. + * + * @dev MessagingFee: LayerZero msg fee + * - nativeFee: The native fee. + * - lzTokenFee: The lzToken fee. + */ + function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory); + + /** + * @notice Executes the send() operation. + * @param _sendParam The parameters for the send operation. + * @param _fee The fee information supplied by the caller. + * - nativeFee: The native fee. + * - lzTokenFee: The lzToken fee. + * @param _refundAddress The address to receive any excess funds from fees etc. on the src. + * @return receipt The LayerZero messaging receipt from the send() operation. + * @return oftReceipt The OFT receipt information. + * + * @dev MessagingReceipt: LayerZero msg receipt + * - guid: The unique identifier for the sent message. + * - nonce: The nonce of the sent message. + * - fee: The LayerZero fee incurred for the message. + */ + function send( + SendParam calldata _sendParam, + MessagingFee calldata _fee, + address _refundAddress + ) external payable returns (MessagingReceipt memory, OFTReceipt memory); +} diff --git a/oapp/contracts/oft/libs/OFTComposeMsgCodec.sol b/oapp/contracts/oft/libs/OFTComposeMsgCodec.sol new file mode 100644 index 0000000..13e3ffb --- /dev/null +++ b/oapp/contracts/oft/libs/OFTComposeMsgCodec.sol @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +library OFTComposeMsgCodec { + // Offset constants for decoding composed messages + uint8 private constant NONCE_OFFSET = 8; + uint8 private constant SRC_EID_OFFSET = 12; + uint8 private constant AMOUNT_LD_OFFSET = 44; + uint8 private constant COMPOSE_FROM_OFFSET = 76; + + /** + * @dev Encodes a OFT composed message. + * @param _nonce The nonce value. + * @param _srcEid The source endpoint ID. + * @param _amountLD The amount in local decimals. + * @param _composeMsg The composed message. + * @return _msg The encoded Composed message. + */ + function encode( + uint64 _nonce, + uint32 _srcEid, + uint256 _amountLD, + bytes memory _composeMsg // 0x[composeFrom][composeMsg] + ) internal pure returns (bytes memory _msg) { + _msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg); + } + + /** + * @dev Retrieves the nonce from the composed message. + * @param _msg The message. + * @return The nonce value. + */ + function nonce(bytes calldata _msg) internal pure returns (uint64) { + return uint64(bytes8(_msg[:NONCE_OFFSET])); + } + + /** + * @dev Retrieves the source endpoint ID from the composed message. + * @param _msg The message. + * @return The source endpoint ID. + */ + function srcEid(bytes calldata _msg) internal pure returns (uint32) { + return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET])); + } + + /** + * @dev Retrieves the amount in local decimals from the composed message. + * @param _msg The message. + * @return The amount in local decimals. + */ + function amountLD(bytes calldata _msg) internal pure returns (uint256) { + return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET])); + } + + /** + * @dev Retrieves the composeFrom value from the composed message. + * @param _msg The message. + * @return The composeFrom value. + */ + function composeFrom(bytes calldata _msg) internal pure returns (bytes32) { + return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]); + } + + /** + * @dev Retrieves the composed message. + * @param _msg The message. + * @return The composed message. + */ + function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) { + return _msg[COMPOSE_FROM_OFFSET:]; + } + + /** + * @dev Converts an address to bytes32. + * @param _addr The address to convert. + * @return The bytes32 representation of the address. + */ + function addressToBytes32(address _addr) internal pure returns (bytes32) { + return bytes32(uint256(uint160(_addr))); + } + + /** + * @dev Converts bytes32 to an address. + * @param _b The bytes32 value to convert. + * @return The address representation of bytes32. + */ + function bytes32ToAddress(bytes32 _b) internal pure returns (address) { + return address(uint160(uint256(_b))); + } +} diff --git a/oapp/contracts/oft/libs/OFTMsgCodec.sol b/oapp/contracts/oft/libs/OFTMsgCodec.sol new file mode 100644 index 0000000..f57a82e --- /dev/null +++ b/oapp/contracts/oft/libs/OFTMsgCodec.sol @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +library OFTMsgCodec { + // Offset constants for encoding and decoding OFT messages + uint8 private constant SEND_TO_OFFSET = 32; + uint8 private constant SEND_AMOUNT_SD_OFFSET = 40; + + /** + * @dev Encodes an OFT LayerZero message. + * @param _sendTo The recipient address. + * @param _amountShared The amount in shared decimals. + * @param _composeMsg The composed message. + * @return _msg The encoded message. + * @return hasCompose A boolean indicating whether the message has a composed payload. + */ + function encode( + bytes32 _sendTo, + uint64 _amountShared, + bytes memory _composeMsg + ) internal view returns (bytes memory _msg, bool hasCompose) { + hasCompose = _composeMsg.length > 0; + // @dev Remote chains will want to know the composed function caller ie. msg.sender on the src. + _msg = hasCompose + ? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg) + : abi.encodePacked(_sendTo, _amountShared); + } + + /** + * @dev Checks if the OFT message is composed. + * @param _msg The OFT message. + * @return A boolean indicating whether the message is composed. + */ + function isComposed(bytes calldata _msg) internal pure returns (bool) { + return _msg.length > SEND_AMOUNT_SD_OFFSET; + } + + /** + * @dev Retrieves the recipient address from the OFT message. + * @param _msg The OFT message. + * @return The recipient address. + */ + function sendTo(bytes calldata _msg) internal pure returns (bytes32) { + return bytes32(_msg[:SEND_TO_OFFSET]); + } + + /** + * @dev Retrieves the amount in shared decimals from the OFT message. + * @param _msg The OFT message. + * @return The amount in shared decimals. + */ + function amountSD(bytes calldata _msg) internal pure returns (uint64) { + return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET])); + } + + /** + * @dev Retrieves the composed message from the OFT message. + * @param _msg The OFT message. + * @return The composed message. + */ + function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) { + return _msg[SEND_AMOUNT_SD_OFFSET:]; + } + + /** + * @dev Converts an address to bytes32. + * @param _addr The address to convert. + * @return The bytes32 representation of the address. + */ + function addressToBytes32(address _addr) internal pure returns (bytes32) { + return bytes32(uint256(uint160(_addr))); + } + + /** + * @dev Converts bytes32 to an address. + * @param _b The bytes32 value to convert. + * @return The address representation of bytes32. + */ + function bytes32ToAddress(bytes32 _b) internal pure returns (address) { + return address(uint160(uint256(_b))); + } +} diff --git a/oapp/contracts/precrime/PreCrime.sol b/oapp/contracts/precrime/PreCrime.sol index 5c9f8fc..f1e2b46 100644 --- a/oapp/contracts/precrime/PreCrime.sol +++ b/oapp/contracts/precrime/PreCrime.sol @@ -32,8 +32,7 @@ abstract contract PreCrime is Ownable, IPreCrime { _; } - constructor(address _endpoint, address _simulator, address _owner) { - _transferOwnership(_owner); + constructor(address _endpoint, address _simulator) { lzEndpoint = _endpoint; simulator = _simulator; oApp = IOAppPreCrimeSimulator(_simulator).oApp(); diff --git a/oapp/contracts/precrime/extensions/PreCrimeE1.sol b/oapp/contracts/precrime/extensions/PreCrimeE1.sol index ae737f3..8d03e38 100644 --- a/oapp/contracts/precrime/extensions/PreCrimeE1.sol +++ b/oapp/contracts/precrime/extensions/PreCrimeE1.sol @@ -13,7 +13,7 @@ abstract contract PreCrimeE1 is PreCrime { uint32 internal immutable localEid; - constructor(uint32 _localEid, address _endpoint, address _simulator) PreCrime(_endpoint, _simulator, msg.sender) { + constructor(uint32 _localEid, address _endpoint, address _simulator) PreCrime(_endpoint, _simulator) { localEid = _localEid; } diff --git a/oapp/test/OFT.t.sol b/oapp/test/OFT.t.sol new file mode 100644 index 0000000..f7d3220 --- /dev/null +++ b/oapp/test/OFT.t.sol @@ -0,0 +1,529 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.20; + +import { OptionsBuilder } from "../contracts/oapp/libs/OptionsBuilder.sol"; + +import { OFTMock } from "./mocks/OFTMock.sol"; +import { MessagingFee, MessagingReceipt } from "../contracts/oft/OFTCore.sol"; +import { OFTAdapterMock } from "./mocks/OFTAdapterMock.sol"; +import { ERC20Mock } from "./mocks/ERC20Mock.sol"; +import { OFTComposerMock } from "./mocks/OFTComposerMock.sol"; +import { OFTInspectorMock, IOAppMsgInspector } from "./mocks/OFTInspectorMock.sol"; +import { IOAppOptionsType3, EnforcedOptionParam } from "../contracts/oapp/libs/OAppOptionsType3.sol"; + +import { OFTMsgCodec } from "../contracts/oft/libs/OFTMsgCodec.sol"; +import { OFTComposeMsgCodec } from "../contracts/oft/libs/OFTComposeMsgCodec.sol"; + +import { IOFT, SendParam, OFTReceipt } from "../contracts/oft/interfaces/IOFT.sol"; +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; + +import "forge-std/console.sol"; +import { TestHelper } from "./TestHelper.sol"; + +contract OFTTest is TestHelper { + using OptionsBuilder for bytes; + + uint32 aEid = 1; + uint32 bEid = 2; + uint32 cEid = 3; + + OFTMock aOFT; + OFTMock bOFT; + OFTAdapterMock cOFTAdapter; + ERC20Mock cERC20Mock; + + OFTInspectorMock oAppInspector; + + address public userA = address(0x1); + address public userB = address(0x2); + address public userC = address(0x3); + uint256 public initialBalance = 100 ether; + + function setUp() public virtual override { + vm.deal(userA, 1000 ether); + vm.deal(userB, 1000 ether); + vm.deal(userC, 1000 ether); + + super.setUp(); + setUpEndpoints(3, LibraryType.UltraLightNode); + + aOFT = OFTMock( + _deployOApp(type(OFTMock).creationCode, abi.encode("aOFT", "aOFT", address(endpoints[aEid]), address(this))) + ); + + bOFT = OFTMock( + _deployOApp(type(OFTMock).creationCode, abi.encode("bOFT", "bOFT", address(endpoints[bEid]), address(this))) + ); + + cERC20Mock = new ERC20Mock("cToken", "cToken"); + cOFTAdapter = OFTAdapterMock( + _deployOApp( + type(OFTAdapterMock).creationCode, + abi.encode(address(cERC20Mock), address(endpoints[cEid]), address(this)) + ) + ); + + // config and wire the ofts + address[] memory ofts = new address[](3); + ofts[0] = address(aOFT); + ofts[1] = address(bOFT); + ofts[2] = address(cOFTAdapter); + this.wireOApps(ofts); + + // mint tokens + aOFT.mint(userA, initialBalance); + bOFT.mint(userB, initialBalance); + cERC20Mock.mint(userC, initialBalance); + + // deploy a universal inspector, can be used by each oft + oAppInspector = new OFTInspectorMock(); + } + + function test_constructor() public { + assertEq(aOFT.owner(), address(this)); + assertEq(bOFT.owner(), address(this)); + assertEq(cOFTAdapter.owner(), address(this)); + + assertEq(aOFT.balanceOf(userA), initialBalance); + assertEq(bOFT.balanceOf(userB), initialBalance); + assertEq(IERC20(cOFTAdapter.token()).balanceOf(userC), initialBalance); + + assertEq(aOFT.token(), address(aOFT)); + assertEq(bOFT.token(), address(bOFT)); + assertEq(cOFTAdapter.token(), address(cERC20Mock)); + } + + function test_oftVersion() public { + (bytes4 interfaceId, ) = aOFT.oftVersion(); + bytes4 expectedId = 0x02e49c2c; + assertEq(interfaceId, expectedId); + } + + function test_send_oft() public { + uint256 tokensToSend = 1 ether; + bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + SendParam memory sendParam = SendParam( + bEid, + addressToBytes32(userB), + tokensToSend, + tokensToSend, + options, + "", + "" + ); + MessagingFee memory fee = aOFT.quoteSend(sendParam, false); + + assertEq(aOFT.balanceOf(userA), initialBalance); + assertEq(bOFT.balanceOf(userB), initialBalance); + + vm.prank(userA); + aOFT.send{ value: fee.nativeFee }(sendParam, fee, payable(address(this))); + verifyPackets(bEid, addressToBytes32(address(bOFT))); + + assertEq(aOFT.balanceOf(userA), initialBalance - tokensToSend); + assertEq(bOFT.balanceOf(userB), initialBalance + tokensToSend); + } + + function test_send_oft_compose_msg() public { + uint256 tokensToSend = 1 ether; + + OFTComposerMock composer = new OFTComposerMock(); + + bytes memory options = OptionsBuilder + .newOptions() + .addExecutorLzReceiveOption(200000, 0) + .addExecutorLzComposeOption(0, 500000, 0); + bytes memory composeMsg = hex"1234"; + SendParam memory sendParam = SendParam( + bEid, + addressToBytes32(address(composer)), + tokensToSend, + tokensToSend, + options, + composeMsg, + "" + ); + MessagingFee memory fee = aOFT.quoteSend(sendParam, false); + + assertEq(aOFT.balanceOf(userA), initialBalance); + assertEq(bOFT.balanceOf(address(composer)), 0); + + vm.prank(userA); + (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) = aOFT.send{ value: fee.nativeFee }( + sendParam, + fee, + payable(address(this)) + ); + verifyPackets(bEid, addressToBytes32(address(bOFT))); + + // lzCompose params + uint32 dstEid_ = bEid; + address from_ = address(bOFT); + bytes memory options_ = options; + bytes32 guid_ = msgReceipt.guid; + address to_ = address(composer); + bytes memory composerMsg_ = OFTComposeMsgCodec.encode( + msgReceipt.nonce, + aEid, + oftReceipt.amountReceivedLD, + abi.encodePacked(addressToBytes32(userA), composeMsg) + ); + this.lzCompose(dstEid_, from_, options_, guid_, to_, composerMsg_); + + assertEq(aOFT.balanceOf(userA), initialBalance - tokensToSend); + assertEq(bOFT.balanceOf(address(composer)), tokensToSend); + + assertEq(composer.from(), from_); + assertEq(composer.guid(), guid_); + assertEq(composer.message(), composerMsg_); + assertEq(composer.executor(), address(this)); + assertEq(composer.extraData(), composerMsg_); // default to setting the extraData to the message as well to test + } + + function test_oft_compose_codec() public { + uint64 nonce = 1; + uint32 srcEid = 2; + uint256 amountCreditLD = 3; + bytes memory composeMsg = hex"1234"; + + bytes memory message = OFTComposeMsgCodec.encode( + nonce, + srcEid, + amountCreditLD, + abi.encodePacked(addressToBytes32(msg.sender), composeMsg) + ); + (uint64 nonce_, uint32 srcEid_, uint256 amountCreditLD_, bytes32 composeFrom_, bytes memory composeMsg_) = this + .decodeOFTComposeMsgCodec(message); + + assertEq(nonce_, nonce); + assertEq(srcEid_, srcEid); + assertEq(amountCreditLD_, amountCreditLD); + assertEq(composeFrom_, addressToBytes32(msg.sender)); + assertEq(composeMsg_, composeMsg); + } + + function decodeOFTComposeMsgCodec( + bytes calldata message + ) + public + pure + returns (uint64 nonce, uint32 srcEid, uint256 amountCreditLD, bytes32 composeFrom, bytes memory composeMsg) + { + nonce = OFTComposeMsgCodec.nonce(message); + srcEid = OFTComposeMsgCodec.srcEid(message); + amountCreditLD = OFTComposeMsgCodec.amountLD(message); + composeFrom = OFTComposeMsgCodec.composeFrom(message); + composeMsg = OFTComposeMsgCodec.composeMsg(message); + } + + function test_debit_slippage_removeDust() public { + uint256 amountToSendLD = 1.23456789 ether; + uint256 minAmountToCreditLD = 1.23456789 ether; + uint32 dstEid = aEid; + + // remove the dust form the shared decimal conversion + assertEq(aOFT.removeDust(amountToSendLD), 1.234567 ether); + + vm.expectRevert( + abi.encodeWithSelector(IOFT.SlippageExceeded.selector, aOFT.removeDust(amountToSendLD), minAmountToCreditLD) + ); + aOFT.debit(amountToSendLD, minAmountToCreditLD, dstEid); + } + + function test_debit_slippage_minAmountToCreditLD() public { + uint256 amountToSendLD = 1 ether; + uint256 minAmountToCreditLD = 1.00000001 ether; + uint32 dstEid = aEid; + + vm.expectRevert(abi.encodeWithSelector(IOFT.SlippageExceeded.selector, amountToSendLD, minAmountToCreditLD)); + aOFT.debit(amountToSendLD, minAmountToCreditLD, dstEid); + } + + function test_toLD() public { + uint64 amountSD = 1000; + assertEq(amountSD * aOFT.decimalConversionRate(), aOFT.toLD(uint64(amountSD))); + } + + function test_toSD() public { + uint256 amountLD = 1000000; + assertEq(amountLD / aOFT.decimalConversionRate(), aOFT.toSD(amountLD)); + } + + function test_oft_debit() public { + uint256 amountToSendLD = 1 ether; + uint256 minAmountToCreditLD = 1 ether; + uint32 dstEid = aEid; + + assertEq(aOFT.balanceOf(userA), initialBalance); + assertEq(aOFT.balanceOf(address(this)), 0); + + vm.prank(userA); + (uint256 amountDebitedLD, uint256 amountToCreditLD) = aOFT.debit(amountToSendLD, minAmountToCreditLD, dstEid); + + assertEq(amountDebitedLD, amountToSendLD); + assertEq(amountToCreditLD, amountToSendLD); + + assertEq(aOFT.balanceOf(userA), initialBalance - amountToSendLD); + assertEq(aOFT.balanceOf(address(this)), 0); + } + + function test_oft_credit() public { + uint256 amountToCreditLD = 1 ether; + uint32 srcEid = aEid; + + assertEq(aOFT.balanceOf(userA), initialBalance); + assertEq(aOFT.balanceOf(address(this)), 0); + + vm.prank(userA); + uint256 amountReceived = aOFT.credit(userA, amountToCreditLD, srcEid); + + assertEq(aOFT.balanceOf(userA), initialBalance + amountReceived); + assertEq(aOFT.balanceOf(address(this)), 0); + } + + function test_oft_adapter_debit() public { + uint256 amountToSendLD = 1 ether; + uint256 minAmountToCreditLD = 1 ether; + uint32 dstEid = cEid; + + assertEq(cERC20Mock.balanceOf(userC), initialBalance); + assertEq(cERC20Mock.balanceOf(address(cOFTAdapter)), 0); + + vm.prank(userC); + vm.expectRevert( + abi.encodeWithSelector(IOFT.SlippageExceeded.selector, amountToSendLD, minAmountToCreditLD + 1) + ); + cOFTAdapter.debitView(amountToSendLD, minAmountToCreditLD + 1, dstEid); + + vm.prank(userC); + cERC20Mock.approve(address(cOFTAdapter), amountToSendLD); + vm.prank(userC); + (uint256 amountDebitedLD, uint256 amountToCreditLD) = cOFTAdapter.debit( + amountToSendLD, + minAmountToCreditLD, + dstEid + ); + + assertEq(amountDebitedLD, amountToSendLD); + assertEq(amountToCreditLD, amountToSendLD); + + assertEq(cERC20Mock.balanceOf(userC), initialBalance - amountToSendLD); + assertEq(cERC20Mock.balanceOf(address(cOFTAdapter)), amountToSendLD); + } + + function test_oft_adapter_credit() public { + uint256 amountToCreditLD = 1 ether; + uint32 srcEid = cEid; + + assertEq(cERC20Mock.balanceOf(userC), initialBalance); + assertEq(cERC20Mock.balanceOf(address(cOFTAdapter)), 0); + + vm.prank(userC); + cERC20Mock.transfer(address(cOFTAdapter), amountToCreditLD); + + uint256 amountReceived = cOFTAdapter.credit(userB, amountToCreditLD, srcEid); + + assertEq(cERC20Mock.balanceOf(userC), initialBalance - amountToCreditLD); + assertEq(cERC20Mock.balanceOf(address(userB)), amountReceived); + assertEq(cERC20Mock.balanceOf(address(cOFTAdapter)), 0); + } + + function decodeOFTMsgCodec( + bytes calldata message + ) public pure returns (bool isComposed, bytes32 sendTo, uint64 amountSD, bytes memory composeMsg) { + isComposed = OFTMsgCodec.isComposed(message); + sendTo = OFTMsgCodec.sendTo(message); + amountSD = OFTMsgCodec.amountSD(message); + composeMsg = OFTMsgCodec.composeMsg(message); + } + + function test_oft_build_msg() public { + uint32 dstEid = bEid; + bytes32 to = addressToBytes32(userA); + uint256 amountToSendLD = 1.23456789 ether; + uint256 minAmountToCreditLD = aOFT.removeDust(amountToSendLD); + + // params for buildMsgAndOptions + bytes memory extraOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + bytes memory composeMsg = hex"1234"; + SendParam memory sendParam = SendParam( + dstEid, + to, + amountToSendLD, + minAmountToCreditLD, + extraOptions, + composeMsg, + "" + ); + uint256 amountToCreditLD = minAmountToCreditLD; + + (bytes memory message, ) = aOFT.buildMsgAndOptions(sendParam, amountToCreditLD); + + (bool isComposed_, bytes32 sendTo_, uint64 amountSD_, bytes memory composeMsg_) = this.decodeOFTMsgCodec( + message + ); + + assertEq(isComposed_, true); + assertEq(sendTo_, to); + assertEq(amountSD_, aOFT.toSD(amountToCreditLD)); + bytes memory expectedComposeMsg = abi.encodePacked(addressToBytes32(address(this)), composeMsg); + assertEq(composeMsg_, expectedComposeMsg); + } + + function test_oft_build_msg_no_compose_msg() public { + uint32 dstEid = bEid; + bytes32 to = addressToBytes32(userA); + uint256 amountToSendLD = 1.23456789 ether; + uint256 minAmountToCreditLD = aOFT.removeDust(amountToSendLD); + + // params for buildMsgAndOptions + bytes memory extraOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + bytes memory composeMsg = ""; + SendParam memory sendParam = SendParam( + dstEid, + to, + amountToSendLD, + minAmountToCreditLD, + extraOptions, + composeMsg, + "" + ); + uint256 amountToCreditLD = minAmountToCreditLD; + + (bytes memory message, ) = aOFT.buildMsgAndOptions(sendParam, amountToCreditLD); + + (bool isComposed_, bytes32 sendTo_, uint64 amountSD_, bytes memory composeMsg_) = this.decodeOFTMsgCodec( + message + ); + + assertEq(isComposed_, false); + assertEq(sendTo_, to); + assertEq(amountSD_, aOFT.toSD(amountToCreditLD)); + assertEq(composeMsg_, ""); + } + + function test_set_enforced_options() public { + uint32 eid = 1; + + bytes memory optionsTypeOne = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + bytes memory optionsTypeTwo = OptionsBuilder.newOptions().addExecutorLzReceiveOption(250000, 0); + + EnforcedOptionParam[] memory enforcedOptions = new EnforcedOptionParam[](2); + enforcedOptions[0] = EnforcedOptionParam(eid, 1, optionsTypeOne); + enforcedOptions[1] = EnforcedOptionParam(eid, 2, optionsTypeTwo); + + aOFT.setEnforcedOptions(enforcedOptions); + + assertEq(aOFT.enforcedOptions(eid, 1), optionsTypeOne); + assertEq(aOFT.enforcedOptions(eid, 2), optionsTypeTwo); + } + + function test_assert_options_type3_revert() public { + uint32 eid = 1; + EnforcedOptionParam[] memory enforcedOptions = new EnforcedOptionParam[](1); + + enforcedOptions[0] = EnforcedOptionParam(eid, 1, hex"0004"); // not type 3 + vm.expectRevert(abi.encodeWithSelector(IOAppOptionsType3.InvalidOptions.selector, hex"0004")); + aOFT.setEnforcedOptions(enforcedOptions); + + enforcedOptions[0] = EnforcedOptionParam(eid, 1, hex"0002"); // not type 3 + vm.expectRevert(abi.encodeWithSelector(IOAppOptionsType3.InvalidOptions.selector, hex"0002")); + aOFT.setEnforcedOptions(enforcedOptions); + + enforcedOptions[0] = EnforcedOptionParam(eid, 1, hex"0001"); // not type 3 + vm.expectRevert(abi.encodeWithSelector(IOAppOptionsType3.InvalidOptions.selector, hex"0001")); + aOFT.setEnforcedOptions(enforcedOptions); + + enforcedOptions[0] = EnforcedOptionParam(eid, 1, hex"0003"); // IS type 3 + aOFT.setEnforcedOptions(enforcedOptions); // doesnt revert cus option type 3 + } + + function test_combine_options() public { + uint32 eid = 1; + uint16 msgType = 1; + + bytes memory enforcedOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + EnforcedOptionParam[] memory enforcedOptionsArray = new EnforcedOptionParam[](1); + enforcedOptionsArray[0] = EnforcedOptionParam(eid, msgType, enforcedOptions); + aOFT.setEnforcedOptions(enforcedOptionsArray); + + bytes memory extraOptions = OptionsBuilder.newOptions().addExecutorNativeDropOption( + 1.2345 ether, + addressToBytes32(userA) + ); + + bytes memory expectedOptions = OptionsBuilder + .newOptions() + .addExecutorLzReceiveOption(200000, 0) + .addExecutorNativeDropOption(1.2345 ether, addressToBytes32(userA)); + + bytes memory combinedOptions = aOFT.combineOptions(eid, msgType, extraOptions); + assertEq(combinedOptions, expectedOptions); + } + + function test_combine_options_no_extra_options() public { + uint32 eid = 1; + uint16 msgType = 1; + + bytes memory enforcedOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + EnforcedOptionParam[] memory enforcedOptionsArray = new EnforcedOptionParam[](1); + enforcedOptionsArray[0] = EnforcedOptionParam(eid, msgType, enforcedOptions); + aOFT.setEnforcedOptions(enforcedOptionsArray); + + bytes memory expectedOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + + bytes memory combinedOptions = aOFT.combineOptions(eid, msgType, ""); + assertEq(combinedOptions, expectedOptions); + } + + function test_combine_options_no_enforced_options() public { + uint32 eid = 1; + uint16 msgType = 1; + + bytes memory extraOptions = OptionsBuilder.newOptions().addExecutorNativeDropOption( + 1.2345 ether, + addressToBytes32(userA) + ); + + bytes memory expectedOptions = OptionsBuilder.newOptions().addExecutorNativeDropOption( + 1.2345 ether, + addressToBytes32(userA) + ); + + bytes memory combinedOptions = aOFT.combineOptions(eid, msgType, extraOptions); + assertEq(combinedOptions, expectedOptions); + } + + function test_oapp_inspector_inspect() public { + uint32 dstEid = bEid; + bytes32 to = addressToBytes32(userA); + uint256 amountToSendLD = 1.23456789 ether; + uint256 minAmountToCreditLD = aOFT.removeDust(amountToSendLD); + + // params for buildMsgAndOptions + bytes memory extraOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200000, 0); + bytes memory composeMsg = ""; + SendParam memory sendParam = SendParam( + dstEid, + to, + amountToSendLD, + minAmountToCreditLD, + extraOptions, + composeMsg, + "" + ); + uint256 amountToCreditLD = minAmountToCreditLD; + + // doesnt revert + (bytes memory message, ) = aOFT.buildMsgAndOptions(sendParam, amountToCreditLD); + + // deploy a universal inspector, it automatically reverts + oAppInspector = new OFTInspectorMock(); + // set the inspector + aOFT.setMsgInspector(address(oAppInspector)); + + // does revert because inspector is set + vm.expectRevert(abi.encodeWithSelector(IOAppMsgInspector.InspectionFailed.selector, message, extraOptions)); + (message, ) = aOFT.buildMsgAndOptions(sendParam, amountToCreditLD); + } +} diff --git a/oapp/test/OmniCounter.t.sol b/oapp/test/OmniCounter.t.sol index 12690ac..562c5ab 100644 --- a/oapp/test/OmniCounter.t.sol +++ b/oapp/test/OmniCounter.t.sol @@ -45,7 +45,7 @@ contract OmniCounterTest is TestHelper { function setUpPreCrime() public { // set up precrime for aCounter - aPreCrime = new OmniCounterPreCrime(address(aCounter.endpoint()), address(aCounter), address(this)); + aPreCrime = new OmniCounterPreCrime(address(aCounter.endpoint()), address(aCounter)); aPreCrime.setMaxBatchSize(10); PreCrimePeer[] memory aCounterPreCrimePeers = new PreCrimePeer[](1); @@ -59,7 +59,7 @@ contract OmniCounterTest is TestHelper { aCounter.setPreCrime(address(aPreCrime)); // set up precrime for bCounter - bPreCrime = new OmniCounterPreCrime(address(bCounter.endpoint()), address(bCounter), address(this)); + bPreCrime = new OmniCounterPreCrime(address(bCounter.endpoint()), address(bCounter)); bPreCrime.setMaxBatchSize(10); PreCrimePeer[] memory bCounterPreCrimePeers = new PreCrimePeer[](1); diff --git a/oapp/test/mocks/OFTAdapterMock.sol b/oapp/test/mocks/OFTAdapterMock.sol new file mode 100644 index 0000000..f60056d --- /dev/null +++ b/oapp/test/mocks/OFTAdapterMock.sol @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.0; + +import { OFTAdapter } from "../../contracts/oft/OFTAdapter.sol"; + +contract OFTAdapterMock is OFTAdapter { + constructor(address _token, address _lzEndpoint, address _delegate) OFTAdapter(_token, _lzEndpoint, _delegate) {} + + // @dev expose internal functions for testing purposes + function debit( + uint256 _amountToSendLD, + uint256 _minAmountToCreditLD, + uint32 _dstEid + ) public returns (uint256 amountDebitedLD, uint256 amountToCreditLD) { + return _debit(_amountToSendLD, _minAmountToCreditLD, _dstEid); + } + + function debitView( + uint256 _amountToSendLD, + uint256 _minAmountToCreditLD, + uint32 _dstEid + ) public view returns (uint256 amountDebitedLD, uint256 amountToCreditLD) { + return _debitView(_amountToSendLD, _minAmountToCreditLD, _dstEid); + } + + function credit(address _to, uint256 _amountToCreditLD, uint32 _srcEid) public returns (uint256 amountReceivedLD) { + return _credit(_to, _amountToCreditLD, _srcEid); + } + + function removeDust(uint256 _amountLD) public view returns (uint256 amountLD) { + return _removeDust(_amountLD); + } +} diff --git a/oapp/test/mocks/OFTComposerMock.sol b/oapp/test/mocks/OFTComposerMock.sol new file mode 100644 index 0000000..6a18d26 --- /dev/null +++ b/oapp/test/mocks/OFTComposerMock.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.0; + +import { IOAppComposer } from "../../contracts/oapp/interfaces/IOAppComposer.sol"; + +contract OFTComposerMock is IOAppComposer { + // default empty values for testing a lzCompose received message + address public from; + bytes32 public guid; + bytes public message; + address public executor; + bytes public extraData; + + function lzCompose( + address _from, + bytes32 _guid, + bytes calldata _message, + address _executor, + bytes calldata /*_extraData*/ + ) external payable { + from = _from; + guid = _guid; + message = _message; + executor = _executor; + extraData = _message; + } +} diff --git a/oapp/test/mocks/OFTInspectorMock.sol b/oapp/test/mocks/OFTInspectorMock.sol new file mode 100644 index 0000000..b67818a --- /dev/null +++ b/oapp/test/mocks/OFTInspectorMock.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.0; + +import { IOAppMsgInspector } from "../../contracts/oapp/interfaces/IOAppMsgInspector.sol"; + +contract OFTInspectorMock is IOAppMsgInspector { + function inspect(bytes calldata _message, bytes calldata _options) external pure returns (bool) { + revert InspectionFailed(_message, _options); + } +} diff --git a/oapp/test/mocks/OFTMock.sol b/oapp/test/mocks/OFTMock.sol new file mode 100644 index 0000000..c63538b --- /dev/null +++ b/oapp/test/mocks/OFTMock.sol @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.0; + +import { OFT } from "../../contracts/oft/OFT.sol"; +import { SendParam } from "../../contracts/oft/OFTCore.sol"; + +contract OFTMock is OFT { + constructor( + string memory _name, + string memory _symbol, + address _lzEndpoint, + address _delegate + ) OFT(_name, _symbol, _lzEndpoint, _delegate) {} + + function mint(address _to, uint256 _amount) public { + _mint(_to, _amount); + } + + // @dev expose internal functions for testing purposes + function debit( + uint256 _amountToSendLD, + uint256 _minAmountToCreditLD, + uint32 _dstEid + ) public returns (uint256 amountDebitedLD, uint256 amountToCreditLD) { + return _debit(_amountToSendLD, _minAmountToCreditLD, _dstEid); + } + + function debitView( + uint256 _amountToSendLD, + uint256 _minAmountToCreditLD, + uint32 _dstEid + ) public view returns (uint256 amountDebitedLD, uint256 amountToCreditLD) { + return _debitView(_amountToSendLD, _minAmountToCreditLD, _dstEid); + } + + function removeDust(uint256 _amountLD) public view returns (uint256 amountLD) { + return _removeDust(_amountLD); + } + + function toLD(uint64 _amountSD) public view returns (uint256 amountLD) { + return _toLD(_amountSD); + } + + function toSD(uint256 _amountLD) public view returns (uint64 amountSD) { + return _toSD(_amountLD); + } + + function credit(address _to, uint256 _amountToCreditLD, uint32 _srcEid) public returns (uint256 amountReceivedLD) { + return _credit(_to, _amountToCreditLD, _srcEid); + } + + function buildMsgAndOptions( + SendParam calldata _sendParam, + uint256 _amountToCreditLD + ) public view returns (bytes memory message, bytes memory options) { + return _buildMsgAndOptions(_sendParam, _amountToCreditLD); + } +} diff --git a/oapp/test/mocks/PreCrimeV2Mock.sol b/oapp/test/mocks/PreCrimeV2Mock.sol index 37c3fce..18558f8 100644 --- a/oapp/test/mocks/PreCrimeV2Mock.sol +++ b/oapp/test/mocks/PreCrimeV2Mock.sol @@ -9,7 +9,7 @@ import { InboundPacket } from "../../contracts/precrime/libs/Packet.sol"; import { PreCrimeV2SimulatorMock } from "./PreCrimeV2SimulatorMock.sol"; contract PreCrimeV2Mock is PreCrime { - constructor(address _endpoint, address _simulator) PreCrime(_endpoint, _simulator, msg.sender) {} + constructor(address _endpoint, address _simulator) PreCrime(_endpoint, _simulator) {} uint32[] public eids; bytes[] public results; diff --git a/oapp/test/mocks/PreCrimeV2SimulatorMock.sol b/oapp/test/mocks/PreCrimeV2SimulatorMock.sol index 2e53f22..6b8b5db 100644 --- a/oapp/test/mocks/PreCrimeV2SimulatorMock.sol +++ b/oapp/test/mocks/PreCrimeV2SimulatorMock.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.0; import { Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; +import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { OAppPreCrimeSimulator } from "../../contracts/precrime/OAppPreCrimeSimulator.sol";