// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"@openzeppelin/contracts/access/Ownable.sol";import"@mapprotocol/mos/contracts/interface/IMOSV3.sol";contractOAppisOwnable { IMOSV3 public mos;// Add the MOS contract address as a parameter in the constructor to ensure that the MOS // interface can be invoked.constructor(address_mos){ mos =IMOSV3(_mos); }}
在上面的代码中,我们部署时需要正确的MOS合约地址。
4. 现在,我们来完成DAPP所需的具体逻辑
我们的需求是:在源链上发送一个数字,在目标链上执行后,结果会与这个数字累加。
// This is a target chain method for accumulating numbers, which will store the accumulated // result in the mapping called "cumulativeResult."functioncrossChainAdd(uint256_number) external {// To prevent arbitrary access to the method from addresses other than the target // chain's MOS contract, we restrict the method to only allow calls from the MOS // address for the accumulation.require(msg.sender ==address(mos),"do not have permission"); cumulativeResult += _number; }// By using this method, you can retrieve the current result of cumulativeResult and verify// if the cross-chain accumulation has been executed.functiongetCumulativeResult() externalviewreturns(uint256){return cumulativeResult; }
enumMessageType { CALLDATA, MESSAGE }// @notice This is the configuration you need across the chain.// @param relay - When it is true, the relay chain is required to perform a special// execution to continue across the chain.// @param msgType - Different execution patterns of messages across chains.// @param target - The contract address of the target chain.// @param payload - Cross-chain data.// @param gasLimit - The gasLimit allowed to be consumed by an operation performed on the// target chain.// @param value - Collateral value cross-chain, currently not supported, default is 0.structMessageData {bool relay; MessageType msgType;bytes target;bytes payload;uint256 gasLimit;uint256 value; }// @notice Initiate cross-chain transactions. Generate cross-chain logs.// @param toChain - Target chain chainID.// @param messageData - Structure MessageData encoding.// @param feeToken - In what Token would you like to pay the fee. functiontransferOut(uint256 toChain,bytesmemory messageData,address feeToken ) externalpayablereturns(bytes32);
// Define two constants to determine the choice of cross-chain mode.uint256publicconstant CROSS_CHIAN_MESSAGE =0;uint256publicconstant CROSS_CHIAN_CALL =1;// This method is intended to retrieve the messageData parameter for transferOut, so it is // designed to serve internal contract functions. Therefore, we define it as internal.// @param _number // @param _targetfunction_getMessageData(uint256_number,bytesmemory_target,uint256_type )internalpurereturns(bytesmemory) {// Define a bytes variable to receive the encoded value, making it easier for the // return statement.bytes messageByte;// Based on the provided type, determine the desired cross-chain method.if(_type == CROSS_CHIAN_MESSAGE){// For the message's cross-chain method, we only need to encode the parameters// required for the cross-chain operation and do not need to include the method's // selector.bytesmemory payload = abi.encode(_number);// false indicates that there is no need for secondary execution on the relay.// IMOSV3.MessageType.MESSAGE is the option to select our cross-chain type. // IMOSV3.MessageType is an enumeration type.// 500000 is the maximum gasLimit estimated to be consumed by the execution of the // method on the target chain. IMOSV3.MessageData memory messageData = IMOSV3.MessageData(false,IMOSV3.MessageType.MESSAGE,_target,payload,500000,0); messageByte = abi.encode(messageData); }elseif(_type == CROSS_CHIAN_CALL){// To obtain the payload field value of the CALLDATA cross-chain method, this is // the callcode that will be executed on the target chain.bytesmemory payload = abi.encodeWithSelector(OAppSourceSender.crossChainAdd.selector,_number);// false indicates that there is no need for secondary execution on the relay.// IMOSV3.MessageType.CALLDATA is the option to select our cross-chain type. // IMOSV3.MessageType is an enumeration type.// 500000 is the maximum gasLimit estimated to be consumed by the execution of the // method on the target chain. IMOSV3.MessageData memory messageData = IMOSV3.MessageData(false,IMOSV3.MessageType.CALLDATA,_target,payload,500000,0); messageByte = abi.encode(messageData); }return messageByte; }
// @notice Gets the fee to cross to the target chain.// @param toChain - Target chain chainID.// @param feeToken - Token address that supports payment fee,if it's native, it's address(0).// @param gasLimit - The gasLimit allowed to be consumed by an operation performed on the target chain.functiongetMessageFee(uint256 toChain,address feeToken,uint256 gasLimit) externalviewreturns(uint256,address);
// Similarly, this method is also intended to serve transferOut, and we will define it as internal as well.function_getTransferOutFee(uint256_toChainId) internalviewreturns(uint256){ (uint256 amount,) = mos.getMessageFee(_toChainId,address(0),500000);return amount; }
6.3 实现发送跨链消息的完整且最终的方法
functionsendCrossChainAdd(uint256_toChainId,uint256_number,bytesmemory_target,uint256_type )externalreturns(bytes32) {bytesmemory messageData =_getMessageData(_number,_target,_type);uint256 fee =_getTransferOutFee(_toChainId);// Since we have chosen to use the native token of this chain to pay the fee, we will // copy the fee value to the value parameter when calling the method.// The three parameters of transferOut should have been understood clearly during our // construction process.bytes32 orderId = mos.transferOut{value:fee}(_tochainId, messageData,address(0));// The returned orderId is a unique identifier assigned by MOS after a successful // transferOut call. It serves as a cross-chain unique identifier and will not be // repeated.return orderId; }
7. 完成 MESSAGE跨链方法用以执行消息跨链的逻辑
发送跨链消息后,在步骤4中,我们完成了CALLDATA跨链方法的执行代码。 使用该MESSAGE方法时,接收合约需要实现一个固定的方法,更多细节可以在IMpoExecutor接口中找到IMapoExecutor interface for more details.
// After the MESSAGE cross-chain, the method will be directly invoked by the MOS contract. // Parameters such as _fromChain, _toChain, _fromAddress, and _orderId can be optionally // passed and ignored if not used.functionmapoExecute(uint256_fromChain,uint256_toChain,bytescalldata_fromAddress,bytes32_orderId,bytescalldata_message ) externaloverridereturns(bytesmemory newMessage){// Check the _orderId to determine whether this method has been called and executed // already, and prevent duplicate calls.require(!orderList[_orderId],"The orderId is invalid");//decode numberuint256 number = abi.decode(_message,(uint256));// Completed the accumulation requirement. cumulativeResult += number;// Mark _orderId as executed. orderList[_orderId] =true;return _message; }
// Fill in the source chain's ID and address, and set the tag to true to indicate a // willingness to trust messages coming from this source chain. With this, MOS can // successfully execute the cross-chain call.functionsetTrustFromAddress(uint256_sourceChainId,bytesmemory_sourceAddress,bool_tag) externalonlyOwner { mos.addRemoteCaller(_sourceChainId,_fromAddress,_tag); }// This method can be used to check if the _targetAddress on the target chain trusts the // sourceAddress from the source chain.functiongetTrustFromAddress(address_targetAddress,uint256_sourceChainId,bytesmemory_sourceAddress) externalviewreturns(bool){return mos.getExecutePermission(_targetAddress,_sourceChainId,_sourceAddress); }
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"@openzeppelin/contracts/access/Ownable.sol";import"@mapprotocol/mos/contracts/interface/IMOSV3.sol";import"@mapprotocol/mos/contracts/interface/IMapoExecutor.sol";contractOAppTargetReceiverisOwnable, IMapoExecutor{ IMOSV3 public mos;uint256public cumulativeResult;mapping(bytes32=>bool) orderList;constructor(address_mos){ mos =IMOSV3(_mos); }functioncrossChainAdd(uint256_number) external {require(msg.sender ==address(mos),"do not have permission"); cumulativeResult += _number; }functionmapoExecute(uint256_fromChain,uint256_toChain,bytescalldata_fromAddress,bytes32_orderId,bytescalldata_message ) externalreturns(bytesmemory newMessage){require(!orderList[_orderId],"The orderId is invalid");uint256 number = abi.decode(_message,(uint256)); cumulativeResult += number; orderList[_orderId] =true;return _message; }functiongetCumulativeResult() externalviewreturns(uint256){return cumulativeResult; }functionsetTrustFromAddress(uint256_sourceChainId,bytesmemory_sourceAddress,bool_tag) externalonlyOwner { mos.addRemoteCaller(_sourceChainId,_sourceAddress,_tag); }functiongetTrustFromAddress(address_targetAddress,uint256_sourceChainId,bytesmemory_sourceAddress) externalviewreturns(bool){return mos.getExecutePermission(_targetAddress,_sourceChainId,_sourceAddress); }}
10. 合约交互的完整过程。
Deploy the OAppSourceSender contract on EVM-based Source Chain A and obtain the Source-contract-address
Similarly, deploy OAppTargetReceiver contract on EVM-based Target Chain and obtain the Target-contract-address.
On the Target Chain, call the setTrustFromAddress method to set a security flag for the Source-contract-address.
Verify the completion of the setting by calling getTrustFromAddress on the Target Chain.
Retrieve the current result by calling getCumulativeResult on the Target Chain.
On the Source Chain, call the sendCrossChainAdd method to send a cross-chain message.
After observing the cross-chain completion on the cross-chain browser, call the getTrustFromAddress method on the Target Chain to verify if the result has been successfully accumulated.