Проверенный контрактТочноеMIT
HelioRouter
Адрес0xe64dc09a2fadf2d2c00ec663674e0218cc2e1065
- Баланс
0 ETH
- Транзакций
2
- Компилятор
solc 0.8.26
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.26+commit.8a97fa7a
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 291 323
- Транзакция создания
- 0xce466e4eb7…830c23198e
92 файла
Исходный код большой: показывается один файл. Выберите файл в списке.
- src/HelioRouter.solглавный19,94 КБ
- lib/solady/src/utils/FixedPointMathLib.sol55,64 КБ
- lib/solady/src/utils/SSTORE2.sol12,63 КБ
- lib/v4-periphery/lib/v4-core/src/interfaces/IExtsload.sol1,02 КБ
- lib/v4-periphery/lib/v4-core/src/interfaces/IExttload.sol699 Б
- lib/v4-periphery/lib/v4-core/src/interfaces/IHooks.sol8,23 КБ
- lib/v4-periphery/lib/v4-core/src/interfaces/IPoolManager.sol12,84 КБ
- lib/v4-periphery/lib/v4-core/src/interfaces/IProtocolFees.sol2,49 КБ
- lib/v4-periphery/lib/v4-core/src/interfaces/callback/IUnlockCallback.sol488 Б
- lib/v4-periphery/lib/v4-core/src/interfaces/external/IERC20Minimal.sol3,04 КБ
- lib/v4-periphery/lib/v4-core/src/interfaces/external/IERC6909Claims.sol3,16 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/BitMath.sol2,61 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/CustomRevert.sol5,17 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/FixedPoint128.sol297 Б
- lib/v4-periphery/lib/v4-core/src/libraries/FixedPoint96.sol366 Б
- lib/v4-periphery/lib/v4-core/src/libraries/FullMath.sol5,46 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/Hooks.sol16,51 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/LPFeeLibrary.sol3,6 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/LiquidityMath.sol742 Б
- lib/v4-periphery/lib/v4-core/src/libraries/ParseBytes.sol1,2 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/Position.sol4,81 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/SafeCast.sol2,27 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/StateLibrary.sol16,03 КБ
- lib/v4-periphery/lib/v4-core/src/libraries/TickMath.sol12,38 КБ
- lib/v4-periphery/lib/v4-core/src/types/BalanceDelta.sol2,34 КБ
- lib/v4-periphery/lib/v4-core/src/types/BeforeSwapDelta.sol1,47 КБ
- lib/v4-periphery/lib/v4-core/src/types/Currency.sol5,46 КБ
- lib/v4-periphery/lib/v4-core/src/types/PoolId.sol539 Б
- lib/v4-periphery/lib/v4-core/src/types/PoolKey.sol805 Б
- lib/v4-periphery/lib/v4-core/src/types/PoolOperation.sol907 Б
- lib/v4-periphery/src/libraries/LiquidityAmounts.sol3,8 КБ
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/MessageLibBase.sol528 Б
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/SendLibBase.sol10,51 КБ
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/interfaces/ILayerZeroExecutor.sol1,35 КБ
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/interfaces/ILayerZeroTreasury.sol442 Б
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol4,33 КБ
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/SafeCall.sol4,64 КБ
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/UlnBase.sol9,85 КБ
- node_modules/@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol7,32 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroComposer.sol1,05 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol2,59 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol519 Б
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLib.sol805 Б
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol2,76 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingChannel.sol1,54 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingComposer.sol1,03 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingContext.sol239 Б
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol923 Б
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/libs/AddressCast.sol1,47 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol1,78 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Transfer.sol1,12 КБ
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol751 Б
- node_modules/@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol3,67 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol1,53 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/OAppCore.sol3,36 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/OAppReceiver.sol5,41 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol5,63 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppComposer.sol427 Б
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol1,86 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppMsgInspector.sol909 Б
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppOptionsType3.sol1,44 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppReceiver.sol1,08 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol4,9 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol9,28 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/precrime/OAppPreCrimeSimulator.sol5,36 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/precrime/interfaces/IOAppPreCrimeSimulator.sol1,92 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/precrime/interfaces/IPreCrime.sol1,11 КБ
- node_modules/@layerzerolabs/oapp-evm/contracts/precrime/libs/Packet.sol2,47 КБ
- node_modules/@layerzerolabs/oft-evm/contracts/OFT.sol3,4 КБ
- node_modules/@layerzerolabs/oft-evm/contracts/OFTCore.sol20,65 КБ
- node_modules/@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol6,28 КБ
- node_modules/@layerzerolabs/oft-evm/contracts/libs/OFTComposeMsgCodec.sol2,99 КБ
- node_modules/@layerzerolabs/oft-evm/contracts/libs/OFTMsgCodec.sol2,91 КБ
- node_modules/@openzeppelin/contracts/access/Ownable.sol3,1 КБ
- node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol4,45 КБ
- node_modules/@openzeppelin/contracts/interfaces/IERC165.sol193 Б
- node_modules/@openzeppelin/contracts/interfaces/IERC20.sol182 Б
- node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol6,54 КБ
- node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol10,8 КБ
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2,78 КБ
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13,31 КБ
- node_modules/@openzeppelin/contracts/utils/Context.sol963 Б
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol871 Б
- node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol34,94 КБ
- node_modules/solidity-bytes-utils/contracts/BytesLib.sol19,44 КБ
- src/GasVault.sol2,16 КБ
- src/HelioCoin.sol4,22 КБ
- src/HelioFactory.sol26,54 КБ
- src/HelioHook.sol18,33 КБ
- src/LzConfig.sol6,36 КБ
- src/Sessions.sol1,74 КБ
src/HelioRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IOAppComposer} from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppComposer.sol";
import {OptionsBuilder} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol";
import {
IOFT,
SendParam,
MessagingFee,
MessagingReceipt,
OFTReceipt
} from "@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol";
import {OFTComposeMsgCodec} from "@layerzerolabs/oft-evm/contracts/libs/OFTComposeMsgCodec.sol";
import {ILayerZeroEndpointV2} from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {Sessions} from "./Sessions.sol";
import {HelioHook} from "./HelioHook.sol";
import {HelioFactory} from "./HelioFactory.sol";
import {GasVault} from "./GasVault.sol";
import {HelioCoin} from "./HelioCoin.sol";
/// @title HelioRouter
/// @notice After-hours orders: trade a coin whose pool on this chain is closed, against the pool of a chain that is
/// open, in one transaction for the user. Every router swap pays the hook's 1% platform fee (on its native leg) to the
/// GasVault, which forwards it to the treasury. In both directions the USER pays the LayerZero fee on top of the order
/// (msg.value, excess refunded, LayerZero refund to the user): the 1% is pure platform revenue. The destination must stay open for at least MIN_DEST_OPEN after the order, and the recipient `to` on the
/// destination is explicit (contract wallets rarely share an address across chains).
/// - sellAfterHours (here closed, `dstEid` open): the USER pays the LayerZero fee (msg.value, excess refunded). Coins
/// are OFT-sent to the router on `dstEid` with a compose message; there lzCompose sells them in the open pool (exact
/// input) and pays the native to `to`. If that swap cannot be done (pool closed by arrival, output below
/// minNativeOut, anything else) `to` gets the coins on `dstEid` instead: the compose never reverts once the message
/// is authentic.
/// - buyAfterHours (here closed, `dstEid` open): msg.value = amountIn + the LayerZero fee. `amountIn` is swapped for
/// coins in this chain's closed pool (only the router and the sync bot may; the hook bounds router buys by the sync
/// bot's last price and takes its 1% from `amountIn`) and the coins are OFT-sent to `to` on `dstEid`, with an
/// optional gas drop that is part of the LayerZero fee. No minimum order. Coins never stay on the closed chain (OFT
/// dust below 1e-6 coin, which cannot be bridged, is burned).
/// No owner: the peers, sessions and gas drops are wired once by the deployer.
contract HelioRouter is IOAppComposer, IUnlockCallback {
using SafeERC20 for IERC20;
using StateLibrary for IPoolManager;
using OptionsBuilder for bytes;
error NotDeployer();
error AlreadyInitialized();
error BadConfig();
error NotEndpoint();
error NotPoolManager();
error NotSelf();
error UnknownCoin();
error UnknownChain(uint32 eid);
error LocalMarketOpen();
error DestinationClosed(uint32 eid);
error MarketClosed();
error TooSmall();
error Slippage(uint256 out, uint256 min);
error InsufficientGas();
error UnexpectedNative();
error TransferFailed();
error BadRecipient();
error InsufficientFee(uint256 required, uint256 sent);
error DestinationClosingSoon(uint32 eid);
event SellSent(
address indexed user,
address indexed coin,
uint32 indexed dstEid,
uint256 amount,
uint256 minNativeOut,
bytes32 guid,
uint256 lzFee
);
event BuySent(
address indexed user,
address indexed coin,
uint32 indexed dstEid,
uint256 amountIn,
uint256 coinsSent,
bytes32 guid,
uint256 lzFee
);
event SellFilled(
address indexed user, address indexed coin, bytes32 indexed guid, uint256 coinsSold, uint256 nativeOut
);
event SellRefunded(address indexed user, address indexed coin, bytes32 indexed guid, uint256 coins, bytes reason);
address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;
/// @notice gas the destination executor gets for lzCompose (the open-pool sell)
uint128 public constant COMPOSE_GAS = 450_000;
/// @notice lzCompose refuses (reverts, retryable) with less gas than this, so nobody can starve the sell and force
/// the refund path by executing the compose with too little gas
uint256 public constant COMPOSE_MIN_GAS = 350_000;
/// @notice gas held back from the sell attempt so the refund can always run
uint256 public constant REFUND_RESERVE = 100_000;
/// @notice an order needs its destination to stay open at least this long (LayerZero delivery takes seconds to
/// minutes; an order arriving after the close would be refunded or delivered onto a closed chain)
uint256 public constant MIN_DEST_OPEN = 10 minutes;
ILayerZeroEndpointV2 public immutable endpoint;
IPoolManager public immutable poolManager;
HelioFactory public immutable factory;
HelioHook public immutable hook;
GasVault public immutable vault;
uint32 public immutable localEid;
address internal immutable deployer;
struct Chain {
address router; // the HelioRouter on that chain (the same address in production)
uint16 sessionStart; // UTC minutes
uint16 sessionEnd;
uint128 gasDrop; // native (of that chain) dropped to the user with each after-hours delivery there; 0 = none
}
mapping(uint32 eid => Chain) public chains;
constructor(address endpoint_, IPoolManager poolManager_, HelioFactory factory_, HelioHook hook_, GasVault vault_) {
endpoint = ILayerZeroEndpointV2(endpoint_);
poolManager = poolManager_;
factory = factory_;
hook = hook_;
vault = vault_;
localEid = ILayerZeroEndpointV2(endpoint_).eid();
deployer = msg.sender;
}
/// @notice one-shot wiring by the deployer: the other chains' routers, sessions and gas drops. Final.
function init(uint32[] calldata eids, Chain[] calldata config) external {
if (msg.sender != deployer) revert NotDeployer();
if (chains[localEid].router != address(0)) revert AlreadyInitialized();
if (eids.length == 0 || eids.length != config.length) revert BadConfig();
chains[localEid] = Chain(address(this), hook.sessionStart(), hook.sessionEnd(), 0);
for (uint256 i; i < eids.length; ++i) {
if (eids[i] == localEid || config[i].router == address(0) || chains[eids[i]].router != address(0)) {
revert BadConfig();
}
Sessions.validate(config[i].sessionStart, config[i].sessionEnd);
chains[eids[i]] = config[i];
}
}
receive() external payable {
if (msg.sender != address(poolManager)) revert UnexpectedNative();
}
// ---------------------------------------------------------------------------------------------------------------
// After-hours orders (source chain: this pool closed, destination open)
// ---------------------------------------------------------------------------------------------------------------
/// @notice sells `amountIn` coins (approve this router first) in the open pool on `dstEid`; the native goes to `to`
/// there. The caller pays the LayerZero fee: send msg.value >= quoteSell(...), the excess is refunded. `amountIn` is
/// rounded down to the OFT's 6 shared decimals (the remainder stays with the caller).
function sellAfterHours(address coin, uint256 amountIn, uint256 minNativeOut, uint32 dstEid, bytes32 to)
external
payable
returns (bytes32 guid)
{
Chain memory dst = _checkRoute(coin, dstEid);
address recipient = _recipient(to);
uint256 rate = HelioCoin(coin).decimalConversionRate();
uint256 amount = (amountIn / rate) * rate;
if (amount == 0) revert TooSmall();
IERC20(coin).safeTransferFrom(msg.sender, address(this), amount);
SendParam memory sp = _sellParam(dst, dstEid, amount, minNativeOut, recipient);
uint256 lzFee = IOFT(coin).quoteSend(sp, false).nativeFee;
if (msg.value < lzFee) revert InsufficientFee(lzFee, msg.value);
(MessagingReceipt memory r,) = IOFT(coin).send{value: lzFee}(sp, MessagingFee(lzFee, 0), msg.sender);
guid = r.guid;
if (msg.value > lzFee) _sendNative(msg.sender, msg.value - lzFee);
emit SellSent(recipient, coin, dstEid, amount, minNativeOut, guid, lzFee);
}
/// @notice buys coins with `amountIn` native in this chain's (closed) pool and delivers them to `to` on `dstEid`.
/// The caller pays the LayerZero fee on top: send msg.value >= amountIn + quoteBuy(...), the excess is refunded.
/// The hook takes its 1% from `amountIn`.
function buyAfterHours(address coin, uint256 amountIn, uint256 minCoinsOut, uint32 dstEid, bytes32 to)
external
payable
returns (bytes32 guid)
{
Chain memory dst = _checkRoute(coin, dstEid);
address recipient = _recipient(to);
if (amountIn == 0) revert TooSmall();
if (msg.value < amountIn) revert InsufficientFee(amountIn, msg.value);
(uint256 paid, uint256 out) = _swap(factory.poolKeyOf(coin), true, amountIn);
if (out < minCoinsOut) revert Slippage(out, minCoinsOut);
uint256 rate = HelioCoin(coin).decimalConversionRate();
uint256 amount = (out / rate) * rate;
if (amount == 0) revert TooSmall();
if (out != amount) IERC20(coin).safeTransfer(DEAD, out - amount);
SendParam memory sp = _buyParam(dst, dstEid, amount, recipient);
uint256 lzFee = IOFT(coin).quoteSend(sp, false).nativeFee;
if (msg.value - paid < lzFee) revert InsufficientFee(paid + lzFee, msg.value);
(MessagingReceipt memory r,) = IOFT(coin).send{value: lzFee}(sp, MessagingFee(lzFee, 0), msg.sender);
guid = r.guid;
if (msg.value > paid + lzFee) _sendNative(msg.sender, msg.value - paid - lzFee);
emit BuySent(recipient, coin, dstEid, paid, amount, guid, lzFee);
}
/// @notice the LayerZero fee the caller pays for a sell (amount already dust-free)
function quoteSell(address coin, uint256 amount, uint256 minNativeOut, uint32 dstEid, bytes32 to)
external
view
returns (uint256)
{
return IOFT(coin).quoteSend(_sellParam(chains[dstEid], dstEid, amount, minNativeOut, _recipient(to)), false)
.nativeFee;
}
/// @notice the LayerZero fee the caller pays on top of a buy (gas drop included): send msg.value = amountIn + this.
/// The fee does not depend on the order size (fixed-size message, fixed options).
function quoteBuy(address coin, uint32 dstEid, bytes32 to) external view returns (uint256) {
uint256 step = HelioCoin(coin).decimalConversionRate();
return IOFT(coin).quoteSend(_buyParam(chains[dstEid], dstEid, step, _recipient(to)), false).nativeFee;
}
/// @dev sells carry no gas drop: the recipient receives native on arrival
function _sellParam(Chain memory dst, uint32 dstEid, uint256 amount, uint256 minNativeOut, address recipient)
internal
pure
returns (SendParam memory)
{
bytes memory options = OptionsBuilder.newOptions().addExecutorLzComposeOption(0, COMPOSE_GAS, 0);
return SendParam(dstEid, _b32(dst.router), amount, amount, options, abi.encode(recipient, minNativeOut), "");
}
function _buyParam(Chain memory dst, uint32 dstEid, uint256 amount, address recipient)
internal
pure
returns (SendParam memory)
{
bytes memory options = OptionsBuilder.newOptions();
if (dst.gasDrop != 0) options = options.addExecutorNativeDropOption(dst.gasDrop, _b32(recipient));
return SendParam(dstEid, _b32(recipient), amount, amount, options, "", "");
}
/// @dev EVM recipient on the destination: a non-zero address left-padded to 32 bytes
function _recipient(bytes32 to) internal pure returns (address r) {
if (uint256(to) >> 160 != 0 || to == bytes32(0)) revert BadRecipient();
r = address(uint160(uint256(to)));
}
// ---------------------------------------------------------------------------------------------------------------
// Destination side of a sell
// ---------------------------------------------------------------------------------------------------------------
/// @notice LayerZero compose after `from` (a HelioCoin) credited coins to this router
function lzCompose(address from, bytes32 guid, bytes calldata message, address, bytes calldata)
external
payable
override
{
if (msg.sender != address(endpoint)) revert NotEndpoint();
if (!factory.isCoin(from)) revert UnknownCoin();
if (gasleft() < COMPOSE_MIN_GAS) revert InsufficientGas();
uint256 amount = OFTComposeMsgCodec.amountLD(message);
uint32 srcEid = OFTComposeMsgCodec.srcEid(message);
address composeFrom = OFTComposeMsgCodec.bytes32ToAddress(OFTComposeMsgCodec.composeFrom(message));
// not from a HelioRouter: no order to fill, hand the coins (and any value) to whoever sent them
if (srcEid == localEid || composeFrom != chains[srcEid].router) {
IERC20(from).safeTransfer(composeFrom, amount);
if (msg.value != 0) _sendNativeSoft(composeFrom, msg.value);
emit SellRefunded(composeFrom, from, guid, amount, "not a router order");
return;
}
(address user, uint256 minOut) = abi.decode(OFTComposeMsgCodec.composeMsg(message), (address, uint256));
if (msg.value != 0) _sendNativeSoft(user, msg.value);
try this.fillSell{gas: gasleft() - REFUND_RESERVE}(from, amount, minOut, user) returns (
uint256 sold, uint256 out
) {
emit SellFilled(user, from, guid, sold, out);
} catch (bytes memory reason) {
IERC20(from).safeTransfer(user, amount);
emit SellRefunded(user, from, guid, amount, reason);
}
}
/// @dev only lzCompose (self-call, so any revert lands in its catch): sells in the open pool, pays the user
function fillSell(address coin, uint256 amount, uint256 minOut, address user)
external
returns (uint256 sold, uint256 out)
{
if (msg.sender != address(this)) revert NotSelf();
if (!hook.isOpenNow()) revert MarketClosed();
(sold, out) = _swap(factory.poolKeyOf(coin), false, amount);
if (out < minOut) revert Slippage(out, minOut);
(bool ok,) = user.call{value: out}("");
if (!ok) revert TransferFailed();
if (sold < amount) IERC20(coin).safeTransfer(user, amount - sold);
}
// ---------------------------------------------------------------------------------------------------------------
// PoolManager
// ---------------------------------------------------------------------------------------------------------------
/// @dev exact-input swap straight on the PoolManager (this router is the hook's `sender`); returns (paid, received)
function _swap(PoolKey memory key, bool zeroForOne, uint256 amountIn) internal returns (uint256 paid, uint256 out) {
(paid, out) = abi.decode(poolManager.unlock(abi.encode(key, zeroForOne, amountIn)), (uint256, uint256));
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
if (msg.sender != address(poolManager)) revert NotPoolManager();
(PoolKey memory key, bool zeroForOne, uint256 amountIn) = abi.decode(data, (PoolKey, bool, uint256));
BalanceDelta d = poolManager.swap(
key,
SwapParams(
zeroForOne, -int256(amountIn), zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
),
""
);
int128 a0 = d.amount0();
int128 a1 = d.amount1();
uint256 paid;
uint256 out;
if (zeroForOne) {
paid = uint256(int256(-a0));
out = uint256(int256(a1));
poolManager.settle{value: paid}();
poolManager.take(key.currency1, address(this), out);
} else {
paid = uint256(int256(-a1));
out = uint256(int256(a0));
poolManager.sync(key.currency1);
IERC20(Currency.unwrap(key.currency1)).safeTransfer(address(poolManager), paid);
poolManager.settle();
if (out != 0) poolManager.take(key.currency0, address(this), out);
}
return abi.encode(paid, out);
}
// ---------------------------------------------------------------------------------------------------------------
// Views and internals
// ---------------------------------------------------------------------------------------------------------------
/// @notice native value of `amount` coins at this chain's pool price (rounded down)
function nativeValue(address coin, uint256 amount) public view returns (uint256) {
(uint160 sqrtP,,,) = poolManager.getSlot0(factory.poolKeyOf(coin).toId());
// price = coins per native = sqrtP^2 / 2^192
return FullMath.mulDiv(FullMath.mulDiv(amount, 1 << 96, sqrtP), 1 << 96, sqrtP);
}
/// @notice true when an after-hours order from here to `dstEid` is possible right now (this chain closed, the
/// destination open for at least MIN_DEST_OPEN more)
function canRoute(uint32 dstEid) public view returns (bool) {
Chain memory c = chains[dstEid];
return dstEid != localEid && c.router != address(0) && !hook.isOpenNow()
&& Sessions.isOpen(c.sessionStart, c.sessionEnd, block.timestamp)
&& Sessions.nextChange(c.sessionStart, c.sessionEnd, block.timestamp) - block.timestamp >= MIN_DEST_OPEN;
}
function _checkRoute(address coin, uint32 dstEid) internal view returns (Chain memory dst) {
if (!factory.isCoin(coin)) revert UnknownCoin();
dst = chains[dstEid];
if (dstEid == localEid || dst.router == address(0)) revert UnknownChain(dstEid);
if (hook.isOpenNow()) revert LocalMarketOpen();
if (!Sessions.isOpen(dst.sessionStart, dst.sessionEnd, block.timestamp)) revert DestinationClosed(dstEid);
if (Sessions.nextChange(dst.sessionStart, dst.sessionEnd, block.timestamp) - block.timestamp < MIN_DEST_OPEN) {
revert DestinationClosingSoon(dstEid);
}
}
function _sendNative(address to, uint256 amount) internal {
(bool ok,) = to.call{value: amount}("");
if (!ok) revert TransferFailed();
}
function _sendNativeSoft(address to, uint256 amount) internal {
(bool ok,) = to.call{value: amount}("");
if (!ok) {
(ok,) = address(vault).call{value: amount}("");
}
}
function _b32(address a) internal pure returns (bytes32) {
return bytes32(uint256(uint160(a)));
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
"openzeppelin-contracts/=node_modules/@openzeppelin/contracts/",
"@layerzerolabs/=node_modules/@layerzerolabs/",
"solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"permit2/=lib/v4-periphery/lib/permit2/",
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@axelar-network/=node_modules/@axelar-network/",
"@chainlink/=node_modules/@chainlink/",
"@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@eth-optimism/=node_modules/@eth-optimism/",
"ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat-deploy/=node_modules/hardhat-deploy/",
"hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
"v4-core/=lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.