Source Code
Overview
ETH Balance
0 ETH
Eth Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x1cde0D85...036C46173 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
Gateway
Compiler Version
v0.8.25+commit.b61c2a91
Optimization Enabled:
Yes with 800 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {MerkleProof} from "openzeppelin/utils/cryptography/MerkleProof.sol"; import {Ownable} from "openzeppelin/access/Ownable.sol"; import {Verification} from "./Verification.sol"; import {Assets} from "./Assets.sol"; import {AgentExecutor} from "./AgentExecutor.sol"; import {Agent} from "./Agent.sol"; import { Channel, ChannelID, InboundMessage, OperatingMode, ParaID, Command, MultiAddress, Ticket, Costs, AgentExecuteCommand } from "./Types.sol"; import {Upgrade} from "./Upgrade.sol"; import {IInitializable} from "./interfaces/IInitializable.sol"; import {IUpgradable} from "./interfaces/IUpgradable.sol"; import {ERC1967} from "./utils/ERC1967.sol"; import {Address} from "./utils/Address.sol"; import {SafeNativeTransfer} from "./utils/SafeTransfer.sol"; import {Call} from "./utils/Call.sol"; import {Math} from "./utils/Math.sol"; import {ScaleCodec} from "./utils/ScaleCodec.sol"; import { AgentExecuteParams, UpgradeParams, CreateAgentParams, CreateChannelParams, UpdateChannelParams, SetOperatingModeParams, TransferNativeFromAgentParams, SetTokenTransferFeesParams, SetPricingParametersParams, RegisterForeignTokenParams, MintForeignTokenParams, TransferNativeTokenParams } from "./Params.sol"; import {CoreStorage} from "./storage/CoreStorage.sol"; import {PricingStorage} from "./storage/PricingStorage.sol"; import {AssetsStorage} from "./storage/AssetsStorage.sol"; import {OperatorStorage} from "./storage/OperatorStorage.sol"; import {GatewayCoreStorage} from "./storage/GatewayCoreStorage.sol"; import {UD60x18, ud60x18, convert} from "prb/math/src/UD60x18.sol"; import {Operators} from "./Operators.sol"; import {IOGateway} from "./interfaces/IOGateway.sol"; import {IMiddlewareBasic} from "./interfaces/IMiddlewareBasic.sol"; contract Gateway is IOGateway, IInitializable, IUpgradable { using Address for address; using SafeNativeTransfer for address payable; address public immutable AGENT_EXECUTOR; // Verification state address public immutable BEEFY_CLIENT; // BridgeHub ParaID internal immutable BRIDGE_HUB_PARA_ID; bytes4 internal immutable BRIDGE_HUB_PARA_ID_ENCODED; bytes32 internal immutable BRIDGE_HUB_AGENT_ID; // ChannelIDs ChannelID internal constant PRIMARY_GOVERNANCE_CHANNEL_ID = ChannelID.wrap(bytes32(uint256(1))); ChannelID internal constant SECONDARY_GOVERNANCE_CHANNEL_ID = ChannelID.wrap(bytes32(uint256(2))); // Gas used for: // 1. Mapping a command id to an implementation function // 2. Calling implementation function uint256 DISPATCH_OVERHEAD_GAS = 10_000; // The maximum fee that can be sent to a destination parachain to pay for execution (DOT). // Has two functions: // * Reduces the ability of users to perform arbitrage using a favourable exchange rate // * Prevents users from mistakenly providing too much fees, which would drain AssetHub's // sovereign account here on Ethereum. uint128 internal immutable MAX_DESTINATION_FEE; uint8 internal immutable FOREIGN_TOKEN_DECIMALS; error InvalidProof(); error InvalidNonce(); error NotEnoughGas(); error FeePaymentToLow(); error Unauthorized(); error Disabled(); error AgentAlreadyCreated(); error AgentDoesNotExist(); error ChannelAlreadyCreated(); error ChannelDoesNotExist(); error InvalidChannelUpdate(); error InvalidAgentExecutionPayload(); error InvalidConstructorParams(); error TokenNotRegistered(); error CantSetMiddlewareToZeroAddress(); error CantSetMiddlewareToSameAddress(); error MiddlewareNotSet(); error EUnableToProcessRewardsB( uint256 epoch, uint256 eraIndex, address tokenAddress, uint256 totalPointsToken, uint256 totalTokensInflated, bytes32 rewardsRoot, bytes errorBytes ); error EUnableToProcessRewardsS( uint256 epoch, uint256 eraIndex, address tokenAddress, uint256 totalPointsToken, uint256 totalTokensInflated, bytes32 rewardsRoot, string errorString ); // Message handlers can only be dispatched by the gateway itself modifier onlySelf() { if (msg.sender != address(this)) { revert Unauthorized(); } _; } // Can only be called by the owner of the contract. modifier onlyOwner() { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); if (msg.sender != layout.owner) { revert Unauthorized(); } _; } // Can only be called by the middleware modifier onlyMiddleware() { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); if (msg.sender != layout.middleware) { revert Unauthorized(); } _; } constructor( address beefyClient, address agentExecutor, ParaID bridgeHubParaID, bytes32 bridgeHubAgentID, uint8 foreignTokenDecimals, uint128 maxDestinationFee ) { if (bridgeHubParaID == ParaID.wrap(0) || bridgeHubAgentID == 0) { revert InvalidConstructorParams(); } BEEFY_CLIENT = beefyClient; AGENT_EXECUTOR = agentExecutor; BRIDGE_HUB_PARA_ID_ENCODED = ScaleCodec.encodeU32(uint32(ParaID.unwrap(bridgeHubParaID))); BRIDGE_HUB_PARA_ID = bridgeHubParaID; BRIDGE_HUB_AGENT_ID = bridgeHubAgentID; FOREIGN_TOKEN_DECIMALS = foreignTokenDecimals; MAX_DESTINATION_FEE = maxDestinationFee; } /// @dev Submit a message from Polkadot for verification and dispatch /// @param message A message produced by the OutboundQueue pallet on BridgeHub /// @param leafProof A message proof used to verify that the message is in the merkle tree committed by the OutboundQueue pallet /// @param headerProof A proof that the commitment is included in parachain header that was finalized by BEEFY. function submitV1( InboundMessage calldata message, bytes32[] calldata leafProof, Verification.Proof calldata headerProof ) external { uint256 startGas = gasleft(); Channel storage channel = _ensureChannel(message.channelID); // Ensure this message is not being replayed if (message.nonce != channel.inboundNonce + 1) { revert InvalidNonce(); } // Increment nonce for origin. // This also prevents the re-entrancy case in which a malicious party tries to re-enter by calling `submitInbound` // again with the same (message, leafProof, headerProof) arguments. channel.inboundNonce++; // Produce the commitment (message root) by applying the leaf proof to the message leaf bytes32 leafHash = keccak256(abi.encode(message)); bytes32 commitment = MerkleProof.processProof(leafProof, leafHash); // Verify that the commitment is included in a parachain header finalized by BEEFY. if (!_verifyCommitment(commitment, headerProof)) { revert InvalidProof(); } // Make sure relayers provide enough gas so that inner message dispatch // does not run out of gas. uint256 maxDispatchGas = message.maxDispatchGas; if (gasleft() < maxDispatchGas + DISPATCH_OVERHEAD_GAS) { revert NotEnoughGas(); } bool success = true; // Dispatch message to a handler if (message.command == Command.AgentExecute) { try Gateway(this).agentExecute{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.CreateAgent) { try Gateway(this).createAgent{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.CreateChannel) { try Gateway(this).createChannel{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.UpdateChannel) { try Gateway(this).updateChannel{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.SetOperatingMode) { try Gateway(this).setOperatingMode{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.TransferNativeFromAgent) { try Gateway(this).transferNativeFromAgent{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.Upgrade) { try Gateway(this).upgrade{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.SetTokenTransferFees) { try Gateway(this).setTokenTransferFees{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.SetPricingParameters) { try Gateway(this).setPricingParameters{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.TransferNativeToken) { try Gateway(this).transferNativeToken{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.RegisterForeignToken) { try Gateway(this).registerForeignToken{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.MintForeignToken) { try Gateway(this).mintForeignToken{gas: maxDispatchGas}(message.params) {} catch { success = false; } } else if (message.command == Command.ReportSlashes) { // We need to put all this inside a generic try-catch, since we dont want to revert decoding nor anything try Gateway(this).reportSlashes{gas: maxDispatchGas}(message.params) {} catch Error(string memory err) { emit UnableToProcessSlashMessageS(err); success = false; } catch (bytes memory err) { emit UnableToProcessSlashMessageB(err); success = false; } } else if (message.command == Command.ReportRewards) { try Gateway(this).sendRewards{gas: maxDispatchGas}(message.params) {} catch Error(string memory err) { emit UnableToProcessRewardsMessageS(err); success = false; } catch (bytes memory err) { emit UnableToProcessRewardsMessageB(err); success = false; } } else { success = false; emit NotImplementedCommand(message.command); } // Calculate a gas refund, capped to protect against huge spikes in `tx.gasprice` // that could drain funds unnecessarily. During these spikes, relayers should back off. uint256 gasUsed = _transactionBaseGas() + (startGas - gasleft()); uint256 refund = gasUsed * Math.min(tx.gasprice, message.maxFeePerGas); // Add the reward to the refund amount. If the sum is more than the funds available // in the channel agent, then reduce the total amount uint256 amount = Math.min(refund + message.reward, address(channel.agent).balance); // Do the payment if there funds available in the agent if (amount > _dustThreshold()) { _transferNativeFromAgent(channel.agent, payable(msg.sender), amount); } emit InboundMessageDispatched(message.channelID, message.nonce, message.id, success); } /** * Getters */ function operatingMode() external view returns (OperatingMode) { return CoreStorage.layout().mode; } function channelOperatingModeOf(ChannelID channelID) external view returns (OperatingMode) { Channel storage ch = _ensureChannel(channelID); return ch.mode; } function channelNoncesOf(ChannelID channelID) external view returns (uint64, uint64) { Channel storage ch = _ensureChannel(channelID); return (ch.inboundNonce, ch.outboundNonce); } function agentOf(bytes32 agentID) external view returns (address) { return _ensureAgent(agentID); } function pricingParameters() external view returns (UD60x18, uint128) { PricingStorage.Layout storage pricing = PricingStorage.layout(); return (pricing.exchangeRate, pricing.deliveryCost); } function implementation() public view returns (address) { return ERC1967.load(); } /** * Handlers */ // Execute code within an agent function agentExecute(bytes calldata data) external onlySelf { AgentExecuteParams memory params = abi.decode(data, (AgentExecuteParams)); address agent = _ensureAgent(params.agentID); if (params.payload.length == 0) { revert InvalidAgentExecutionPayload(); } (AgentExecuteCommand command, bytes memory commandParams) = abi.decode(params.payload, (AgentExecuteCommand, bytes)); if (command == AgentExecuteCommand.TransferToken) { (address token, address recipient, uint128 amount) = abi.decode(commandParams, (address, address, uint128)); Assets.transferNativeToken(AGENT_EXECUTOR, agent, token, recipient, amount); } } /// @dev Create an agent for a consensus system on Polkadot function createAgent(bytes calldata data) external onlySelf { CoreStorage.Layout storage $ = CoreStorage.layout(); CreateAgentParams memory params = abi.decode(data, (CreateAgentParams)); // Ensure we don't overwrite an existing agent if (address($.agents[params.agentID]) != address(0)) { revert AgentAlreadyCreated(); } address payable agent = payable(new Agent(params.agentID)); $.agents[params.agentID] = agent; emit AgentCreated(params.agentID, agent); } /// @dev Create a messaging channel for a Polkadot parachain function createChannel(bytes calldata data) external onlySelf { CoreStorage.Layout storage $ = CoreStorage.layout(); CreateChannelParams memory params = abi.decode(data, (CreateChannelParams)); // Ensure that specified agent actually exists address agent = _ensureAgent(params.agentID); // Ensure channel has not already been created Channel storage ch = $.channels[params.channelID]; if (address(ch.agent) != address(0)) { revert ChannelAlreadyCreated(); } ch.mode = params.mode; ch.agent = agent; ch.inboundNonce = 0; ch.outboundNonce = 0; emit ChannelCreated(params.channelID); } /// @dev Update the configuration for a channel function updateChannel(bytes calldata data) external onlySelf { UpdateChannelParams memory params = abi.decode(data, (UpdateChannelParams)); Channel storage ch = _ensureChannel(params.channelID); // Extra sanity checks when updating the primary governance channel, which should never be halted. if (params.channelID == PRIMARY_GOVERNANCE_CHANNEL_ID && (params.mode != OperatingMode.Normal)) { revert InvalidChannelUpdate(); } ch.mode = params.mode; emit ChannelUpdated(params.channelID); } /// @dev Perform an upgrade of the gateway function upgrade(bytes calldata data) external onlySelf { UpgradeParams memory params = abi.decode(data, (UpgradeParams)); Upgrade.upgrade(params.impl, params.implCodeHash, params.initParams); } // @dev Set the operating mode of the gateway function setOperatingMode(bytes calldata data) external onlySelf { CoreStorage.Layout storage $ = CoreStorage.layout(); SetOperatingModeParams memory params = abi.decode(data, (SetOperatingModeParams)); $.mode = params.mode; emit OperatingModeChanged(params.mode); } // @dev Transfer funds from an agent to a recipient account function transferNativeFromAgent(bytes calldata data) external onlySelf { TransferNativeFromAgentParams memory params = abi.decode(data, (TransferNativeFromAgentParams)); address agent = _ensureAgent(params.agentID); _transferNativeFromAgent(agent, payable(params.recipient), params.amount); emit AgentFundsWithdrawn(params.agentID, params.recipient, params.amount); } // @dev Set token fees of the gateway function setTokenTransferFees(bytes calldata data) external onlySelf { AssetsStorage.Layout storage $ = AssetsStorage.layout(); SetTokenTransferFeesParams memory params = abi.decode(data, (SetTokenTransferFeesParams)); $.assetHubCreateAssetFee = params.assetHubCreateAssetFee; $.assetHubReserveTransferFee = params.assetHubReserveTransferFee; $.registerTokenFee = params.registerTokenFee; emit TokenTransferFeesChanged(); } // @dev Set pricing params of the gateway function setPricingParameters(bytes calldata data) external onlySelf { PricingStorage.Layout storage pricing = PricingStorage.layout(); SetPricingParametersParams memory params = abi.decode(data, (SetPricingParametersParams)); pricing.exchangeRate = params.exchangeRate; pricing.deliveryCost = params.deliveryCost; pricing.multiplier = params.multiplier; emit PricingParametersChanged(); } /** * Assets */ // @dev Register a new fungible Polkadot token for an agent function registerForeignToken(bytes calldata data) external onlySelf { RegisterForeignTokenParams memory params = abi.decode(data, (RegisterForeignTokenParams)); Assets.registerForeignToken(params.foreignTokenID, params.name, params.symbol, params.decimals); } // @dev Mint foreign token from polkadot function mintForeignToken(bytes calldata data) external onlySelf { MintForeignTokenParams memory params = abi.decode(data, (MintForeignTokenParams)); Assets.mintForeignToken(params.foreignTokenID, params.recipient, params.amount); } // @dev Transfer Ethereum native token back from polkadot function transferNativeToken(bytes calldata data) external onlySelf { TransferNativeTokenParams memory params = abi.decode(data, (TransferNativeTokenParams)); address agent = _ensureAgent(params.agentID); Assets.transferNativeToken(AGENT_EXECUTOR, agent, params.token, params.recipient, params.amount); } // @dev Mint foreign token from polkadot function reportSlashes(bytes calldata data) external onlySelf { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); address middlewareAddress = layout.middleware; // Dont process message if we dont have a middleware set if (middlewareAddress == address(0)) { revert MiddlewareNotSet(); } // Decode (IOGateway.SlashParams memory slashes) = abi.decode(data, (IOGateway.SlashParams)); IMiddlewareBasic middleware = IMiddlewareBasic(middlewareAddress); // At most it will be 10, defined by // https://github.com/moondance-labs/tanssi/blob/88e59e6e5afb198947690487f286b9ad7cd4cde6/chains/orchestrator-relays/runtime/dancelight/src/lib.rs#L1446 for (uint256 i = 0; i < slashes.slashes.length; ++i) { Slash memory slash = slashes.slashes[i]; try middleware.slash(uint48(slash.epoch), slash.operatorKey, slash.slashFraction) {} catch Error(string memory err) { emit UnableToProcessIndividualSlashS(slash.operatorKey, slash.slashFraction, slash.epoch, err); continue; } catch (bytes memory err) { emit UnableToProcessIndividualSlashB(slash.operatorKey, slash.slashFraction, slash.epoch, err); continue; } } } function sendRewards(bytes calldata data) external onlySelf { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); address middlewareAddress = layout.middleware; // Dont process message if we dont have a middleware set if (middlewareAddress == address(0)) { revert MiddlewareNotSet(); } ( uint256 epoch, uint256 eraIndex, uint256 totalPointsToken, uint256 totalTokensInflated, bytes32 rewardsRoot, bytes32 foreignTokenId ) = abi.decode(data, (uint256, uint256, uint256, uint256, bytes32, bytes32)); Assets.mintForeignToken(foreignTokenId, middlewareAddress, totalTokensInflated); address tokenAddress = Assets.tokenAddressOf(foreignTokenId); try IMiddlewareBasic(middlewareAddress).distributeRewards( epoch, eraIndex, totalPointsToken, totalTokensInflated, rewardsRoot, tokenAddress ) {} catch Error(string memory err) { revert EUnableToProcessRewardsS( epoch, eraIndex, tokenAddress, totalPointsToken, totalTokensInflated, rewardsRoot, err ); } catch (bytes memory err) { revert EUnableToProcessRewardsB( epoch, eraIndex, tokenAddress, totalPointsToken, totalTokensInflated, rewardsRoot, err ); } } function isTokenRegistered(address token) external view returns (bool) { return Assets.isTokenRegistered(token); } function queryForeignTokenID(address token) external view returns (bytes32) { return AssetsStorage.layout().tokenRegistry[token].foreignID; } // Total fee for registering a token function quoteRegisterTokenFee() external view returns (uint256) { return _calculateFee(Assets.registerTokenCosts()); } // Register an Ethereum-native token in the gateway and on AssetHub function registerToken(address token) external payable { _submitOutbound(Assets.registerToken(token)); } // Total fee for sending a token function quoteSendTokenFee(address token, ParaID destinationChain, uint128 destinationFee) external view returns (uint256) { return _calculateFee(Assets.sendTokenCosts(token, destinationChain, destinationFee, MAX_DESTINATION_FEE)); } // Transfer ERC20 tokens to a Polkadot parachain function sendToken( address token, ParaID destinationChain, MultiAddress calldata destinationAddress, uint128 destinationFee, uint128 amount ) external payable { Ticket memory ticket = Assets.sendToken( token, msg.sender, destinationChain, destinationAddress, destinationFee, MAX_DESTINATION_FEE, amount ); _submitOutbound(ticket); } // @dev Get token address by tokenID function tokenAddressOf(bytes32 tokenID) external view returns (address) { return Assets.tokenAddressOf(tokenID); } function sendOperatorsData(bytes32[] calldata data, uint48 epoch) external onlyMiddleware { Ticket memory ticket = Operators.encodeOperatorsData(data, epoch); _submitOutboundToChannel(PRIMARY_GOVERNANCE_CHANNEL_ID, ticket.payload); } /** * Internal functions */ // Best-effort attempt at estimating the base gas use of `submitInbound` transaction, outside the block of // code that is metered. // This includes: // * Cost paid for every transaction: 21000 gas // * Cost of calldata: Zero byte = 4 gas, Non-zero byte = 16 gas // * Cost of code inside submitInitial that is not metered: 14_698 // // The major cost of calldata are the merkle proofs, which should dominate anything else (including the message payload) // Since the merkle proofs are hashes, they are much more likely to be composed of more non-zero bytes than zero bytes. // // Reference: Ethereum Yellow Paper function _transactionBaseGas() internal pure returns (uint256) { return 21_000 + 14_698 + (msg.data.length * 16); } // Verify that a message commitment is considered finalized by our BEEFY light client. function _verifyCommitment(bytes32 commitment, Verification.Proof calldata proof) internal view virtual returns (bool) { return Verification.verifyCommitment(BEEFY_CLIENT, BRIDGE_HUB_PARA_ID_ENCODED, commitment, proof); } // Convert foreign currency to native currency (ROC/KSM/DOT -> ETH) function _convertToNative(UD60x18 exchangeRate, UD60x18 multiplier, UD60x18 amount) internal view returns (uint256) { UD60x18 ethDecimals = convert(1e18); UD60x18 foreignDecimals = convert(10).pow(convert(uint256(FOREIGN_TOKEN_DECIMALS))); UD60x18 nativeAmount = multiplier.mul(amount).mul(exchangeRate).div(foreignDecimals).mul(ethDecimals); return convert(nativeAmount); } // Calculate the fee for accepting an outbound message function _calculateFee(Costs memory costs) internal view returns (uint256) { PricingStorage.Layout storage pricing = PricingStorage.layout(); UD60x18 amount = convert(pricing.deliveryCost + costs.foreign); return costs.native + _convertToNative(pricing.exchangeRate, pricing.multiplier, amount); } // Submit an outbound message to Polkadot, after taking fees function _submitOutbound(Ticket memory ticket) internal { ChannelID channelID = ticket.dest.into(); Channel storage channel = _ensureChannel(channelID); // Ensure outbound messaging is allowed _ensureOutboundMessagingEnabled(channel); // Destination fee always in DOT uint256 fee = _calculateFee(ticket.costs); // Ensure the user has enough funds for this message to be accepted if (msg.value < fee) { revert FeePaymentToLow(); } channel.outboundNonce = channel.outboundNonce + 1; // Deposit total fee into agent's contract payable(channel.agent).safeNativeTransfer(fee); // Reimburse excess fee payment if (msg.value > fee) { payable(msg.sender).safeNativeTransfer(msg.value - fee); } // Generate a unique ID for this message bytes32 messageID = keccak256(abi.encodePacked(channelID, channel.outboundNonce)); emit OutboundMessageAccepted(channelID, channel.outboundNonce, messageID, ticket.payload); } // Submit an outbound message to a specific channel. // Doesn't handle fees. function _submitOutboundToChannel(ChannelID channelID, bytes memory payload) internal { Channel storage channel = _ensureChannel(channelID); // Ensure outbound messaging is allowed _ensureOutboundMessagingEnabled(channel); // Increase channel nonce channel.outboundNonce = channel.outboundNonce + 1; // Generate a unique ID for this message bytes32 messageID = keccak256(abi.encodePacked(channelID, channel.outboundNonce)); // Emit event for bridge emit OutboundMessageAccepted(channelID, channel.outboundNonce, messageID, payload); } /// @dev Outbound message can be disabled globally or on a per-channel basis. function _ensureOutboundMessagingEnabled(Channel storage ch) internal view { CoreStorage.Layout storage $ = CoreStorage.layout(); if ($.mode != OperatingMode.Normal || ch.mode != OperatingMode.Normal) { revert Disabled(); } } /// @dev Ensure that the specified parachain has a channel allocated function _ensureChannel(ChannelID channelID) internal view returns (Channel storage ch) { ch = CoreStorage.layout().channels[channelID]; // A channel always has an agent specified. if (ch.agent == address(0)) { revert ChannelDoesNotExist(); } } /// @dev Ensure that the specified agentID has a corresponding contract function _ensureAgent(bytes32 agentID) internal view returns (address agent) { agent = CoreStorage.layout().agents[agentID]; if (agent == address(0)) { revert AgentDoesNotExist(); } } /// @dev Invoke some code within an agent function _invokeOnAgent(address agent, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = (Agent(payable(agent)).invoke(AGENT_EXECUTOR, data)); return Call.verifyResult(success, returndata); } /// @dev Transfer ether from an agent function _transferNativeFromAgent(address agent, address payable recipient, uint256 amount) internal { bytes memory call = abi.encodeCall(AgentExecutor.transferNative, (recipient, amount)); _invokeOnAgent(agent, call); } /// @dev Define the dust threshold as the minimum cost to transfer ether between accounts function _dustThreshold() internal view returns (uint256) { return 21_000 * tx.gasprice; } /** * Upgrades */ // Initial configuration for bridge struct Config { OperatingMode mode; /// @dev The fee charged to users for submitting outbound messages (DOT) uint128 deliveryCost; /// @dev The ETH/DOT exchange rate UD60x18 exchangeRate; ParaID assetHubParaID; bytes32 assetHubAgentID; /// @dev The extra fee charged for registering tokens (DOT) uint128 assetHubCreateAssetFee; /// @dev The extra fee charged for sending tokens (DOT) uint128 assetHubReserveTransferFee; /// @dev extra fee to discourage spamming uint256 registerTokenFee; /// @dev Fee multiplier UD60x18 multiplier; /// @dev Optional rescueOperator address rescueOperator; } /// Initialize storage within the `GatewayProxy` contract using this initializer. /// /// This initializer cannot be called externally via the proxy as the function selector /// is overshadowed in the proxy. /// /// This implementation is only intended to initialize storage for initial deployments /// of the `GatewayProxy` contract to transient or long-lived testnets. /// /// The `GatewayProxy` deployed to Ethereum mainnet already has its storage initialized. /// When its logic contract needs to upgraded, a new logic contract should be developed /// that inherits from this base `Gateway` contract. Particularly, the `initialize` function /// must be overriden to ensure selective initialization of storage fields relevant /// to the upgrade. /// /// ```solidity /// contract Gateway202508 is Gateway { /// function initialize(bytes calldata data) external override { /// if (ERC1967.load() == address(0)) { /// revert Unauthorized(); /// } /// # Initialization routines here... /// } /// } /// ``` /// function initialize(bytes calldata data) external virtual { // Ensure that arbitrary users cannot initialize storage in this logic contract. if (ERC1967.load() == address(0)) { revert Unauthorized(); } CoreStorage.Layout storage core = CoreStorage.layout(); Config memory config = abi.decode(data, (Config)); _transferOwnership(msg.sender); core.mode = config.mode; // Initialize agent for BridgeHub address bridgeHubAgent = address(new Agent(BRIDGE_HUB_AGENT_ID)); core.agents[BRIDGE_HUB_AGENT_ID] = bridgeHubAgent; core.agentAddresses[bridgeHubAgent] = BRIDGE_HUB_AGENT_ID; // Initialize channel for primary governance track core.channels[PRIMARY_GOVERNANCE_CHANNEL_ID] = Channel({mode: OperatingMode.Normal, agent: bridgeHubAgent, inboundNonce: 0, outboundNonce: 0}); // Initialize channel for secondary governance track core.channels[SECONDARY_GOVERNANCE_CHANNEL_ID] = Channel({mode: OperatingMode.Normal, agent: bridgeHubAgent, inboundNonce: 0, outboundNonce: 0}); // Initialize agent for for AssetHub address assetHubAgent = address(new Agent(config.assetHubAgentID)); core.agents[config.assetHubAgentID] = assetHubAgent; core.agentAddresses[assetHubAgent] = config.assetHubAgentID; // Initialize channel for AssetHub core.channels[config.assetHubParaID.into()] = Channel({mode: OperatingMode.Normal, agent: assetHubAgent, inboundNonce: 0, outboundNonce: 0}); // Initialize pricing storage PricingStorage.Layout storage pricing = PricingStorage.layout(); pricing.exchangeRate = config.exchangeRate; pricing.deliveryCost = config.deliveryCost; pricing.multiplier = config.multiplier; // Initialize assets storage AssetsStorage.Layout storage assets = AssetsStorage.layout(); assets.assetHubParaID = config.assetHubParaID; assets.assetHubAgent = assetHubAgent; assets.registerTokenFee = config.registerTokenFee; assets.assetHubCreateAssetFee = config.assetHubCreateAssetFee; assets.assetHubReserveTransferFee = config.assetHubReserveTransferFee; // Initialize operator storage OperatorStorage.Layout storage operatorStorage = OperatorStorage.layout(); operatorStorage.operator = config.rescueOperator; } function _transferOwnership(address newOwner) internal { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); address oldOwner = layout.owner; layout.owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } function transferOwnership(address newOwner) external onlyOwner { _transferOwnership(newOwner); } /// Changes the middleware address. function setMiddleware(address middleware) external onlyOwner { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); address oldMiddleware = layout.middleware; if (middleware == address(0)) { revert CantSetMiddlewareToZeroAddress(); } if (middleware == oldMiddleware) { revert CantSetMiddlewareToSameAddress(); } layout.middleware = middleware; emit MiddlewareChanged(oldMiddleware, middleware); } function s_middleware() external view returns (address) { GatewayCoreStorage.Layout storage layout = GatewayCoreStorage.layout(); return layout.middleware; } }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*
* _Available since v4.7._
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*
* _Available since v4.7._
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* _Available since v4.7._
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
require(proofPos == proofLen, "MerkleProof: invalid multiproof");
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
require(proofPos == proofLen, "MerkleProof: invalid multiproof");
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {SubstrateMerkleProof} from "./utils/SubstrateMerkleProof.sol"; import {BeefyClient} from "./BeefyClient.sol"; import {ScaleCodec} from "./utils/ScaleCodec.sol"; import {SubstrateTypes} from "./SubstrateTypes.sol"; library Verification { /// @dev Merkle proof for parachain header finalized by BEEFY /// Reference: https://github.com/paritytech/polkadot/blob/09b61286da11921a3dda0a8e4015ceb9ef9cffca/runtime/rococo/src/lib.rs#L1312 struct HeadProof { // The leaf index of the parachain being proven uint256 pos; // The number of leaves in the merkle tree uint256 width; // The proof items bytes32[] proof; } /// @dev An MMRLeaf without the `leaf_extra` field. /// Reference: https://github.com/paritytech/substrate/blob/14e0a0b628f9154c5a2c870062c3aac7df8983ed/primitives/consensus/beefy/src/mmr.rs#L52 struct MMRLeafPartial { uint8 version; uint32 parentNumber; bytes32 parentHash; uint64 nextAuthoritySetID; uint32 nextAuthoritySetLen; bytes32 nextAuthoritySetRoot; } /// @dev Parachain header /// References: /// * https://paritytech.github.io/substrate/master/sp_runtime/generic/struct.Header.html /// * https://github.com/paritytech/substrate/blob/14e0a0b628f9154c5a2c870062c3aac7df8983ed/primitives/runtime/src/generic/header.rs#L41 struct ParachainHeader { bytes32 parentHash; uint256 number; bytes32 stateRoot; bytes32 extrinsicsRoot; DigestItem[] digestItems; } /// @dev Represents a digest item within a parachain header. /// References: /// * https://paritytech.github.io/substrate/master/sp_runtime/generic/enum.DigestItem.html /// * https://github.com/paritytech/substrate/blob/14e0a0b628f9154c5a2c870062c3aac7df8983ed/primitives/runtime/src/generic/digest.rs#L75 struct DigestItem { uint256 kind; bytes4 consensusEngineID; bytes data; } /// @dev A chain of proofs struct Proof { // The MMR leaf to be proven MMRLeafPartial leafPartial; // The MMR leaf prove bytes32[] leafProof; // Parachain heads root bytes32 parachainHeadsRoot; // The order in which proof items should be combined uint256 leafProofOrder; } error InvalidParachainHeader(); /// @dev IDs of enum variants of DigestItem /// Reference: https://github.com/paritytech/substrate/blob/14e0a0b628f9154c5a2c870062c3aac7df8983ed/primitives/runtime/src/generic/digest.rs#L201 uint256 public constant DIGEST_ITEM_OTHER = 0; uint256 public constant DIGEST_ITEM_CONSENSUS = 4; uint256 public constant DIGEST_ITEM_SEAL = 5; uint256 public constant DIGEST_ITEM_PRERUNTIME = 6; uint256 public constant DIGEST_ITEM_RUNTIME_ENVIRONMENT_UPDATED = 8; /// @dev Enum variant ID for CustomDigestItem::Snowbridge bytes1 public constant DIGEST_ITEM_OTHER_SNOWBRIDGE = 0x00; /// @dev Verify the message commitment by applying several proofs /// /// 1. First check that the commitment is included in the digest items of the parachain header /// 2. Generate the root of the parachain heads merkle tree /// 3. Construct an MMR leaf containing the parachain heads root. /// 4. Verify that the MMR leaf is included in the MMR maintained by the BEEFY light client. /// /// Background info: /// /// In the Polkadot relay chain, for every block: /// 1. A merkle root of finalized parachain headers is constructed: /// https://github.com/paritytech/polkadot/blob/09b61286da11921a3dda0a8e4015ceb9ef9cffca/runtime/rococo/src/lib.rs#L1312. /// 2. An MMR leaf is produced, containing this parachain headers root, and is then inserted into the /// MMR maintained by the `merkle-mountain-range` pallet: /// https://github.com/paritytech/substrate/tree/master/frame/merkle-mountain-range /// /// @param beefyClient The address of the BEEFY light client /// @param encodedParaID The SCALE-encoded parachain ID of BridgeHub /// @param messageCommitment The message commitment root expected to be contained within the /// digest of BridgeHub parachain header. /// @param proof The chain of proofs described above function verifyCommitment( address beefyClient, bytes4 encodedParaID, bytes32 messageCommitment, Proof calldata proof ) external view returns (bool) { bytes32 leafHash = createMMRLeaf(proof.leafPartial, proof.parachainHeadsRoot, messageCommitment); // Verify that the MMR leaf is part of the MMR maintained by the BEEFY light client return BeefyClient(beefyClient).verifyMMRLeafProof(leafHash, proof.leafProof, proof.leafProofOrder); } // Verify that a message commitment is in the header digest function isCommitmentInHeaderDigest(bytes32 messageCommitment, ParachainHeader calldata header) internal pure returns (bool) { for (uint256 i = 0; i < header.digestItems.length; i++) { if ( header.digestItems[i].kind == DIGEST_ITEM_OTHER && header.digestItems[i].data.length == 33 && header.digestItems[i].data[0] == DIGEST_ITEM_OTHER_SNOWBRIDGE && messageCommitment == bytes32(header.digestItems[i].data[1:]) ) { return true; } } return false; } // SCALE-Encodes: Vec<DigestItem> // Reference: https://github.com/paritytech/substrate/blob/14e0a0b628f9154c5a2c870062c3aac7df8983ed/primitives/runtime/src/generic/digest.rs#L40 function encodeDigestItems(DigestItem[] calldata digestItems) internal pure returns (bytes memory) { // encode all digest items into a buffer bytes memory accum = hex""; for (uint256 i = 0; i < digestItems.length; i++) { accum = bytes.concat(accum, encodeDigestItem(digestItems[i])); } // Encode number of digest items, followed by encoded digest items return bytes.concat(ScaleCodec.checkedEncodeCompactU32(digestItems.length), accum); } function encodeDigestItem(DigestItem calldata digestItem) internal pure returns (bytes memory) { if ( digestItem.kind == DIGEST_ITEM_PRERUNTIME || digestItem.kind == DIGEST_ITEM_CONSENSUS || digestItem.kind == DIGEST_ITEM_SEAL ) { return bytes.concat( bytes1(uint8(digestItem.kind)), digestItem.consensusEngineID, ScaleCodec.checkedEncodeCompactU32(digestItem.data.length), digestItem.data ); } else if (digestItem.kind == DIGEST_ITEM_OTHER) { return bytes.concat( bytes1(uint8(DIGEST_ITEM_OTHER)), ScaleCodec.checkedEncodeCompactU32(digestItem.data.length), digestItem.data ); } else if (digestItem.kind == DIGEST_ITEM_RUNTIME_ENVIRONMENT_UPDATED) { return bytes.concat(bytes1(uint8(DIGEST_ITEM_RUNTIME_ENVIRONMENT_UPDATED))); } else { revert InvalidParachainHeader(); } } // Creates a keccak hash of a SCALE-encoded parachain header function createParachainHeaderMerkleLeaf(bytes4 encodedParaID, ParachainHeader calldata header) internal pure returns (bytes32) { // Hash of encoded parachain header merkle leaf return keccak256(createParachainHeader(encodedParaID, header)); } function createParachainHeader(bytes4 encodedParaID, ParachainHeader calldata header) internal pure returns (bytes memory) { bytes memory encodedHeader = bytes.concat( // H256 header.parentHash, // Compact unsigned int ScaleCodec.checkedEncodeCompactU32(header.number), // H256 header.stateRoot, // H256 header.extrinsicsRoot, // Vec<DigestItem> encodeDigestItems(header.digestItems) ); return bytes.concat( // u32 encodedParaID, // length of encoded header ScaleCodec.checkedEncodeCompactU32(encodedHeader.length), encodedHeader ); } // SCALE-encode: MMRLeaf // Reference: https://github.com/paritytech/substrate/blob/14e0a0b628f9154c5a2c870062c3aac7df8983ed/primitives/consensus/beefy/src/mmr.rs#L52 function createMMRLeaf(MMRLeafPartial memory leaf, bytes32 parachainHeadsRoot, bytes32 messageCommitment) internal pure returns (bytes32) { bytes memory encodedLeaf = bytes.concat( ScaleCodec.encodeU8(leaf.version), ScaleCodec.encodeU32(leaf.parentNumber), leaf.parentHash, ScaleCodec.encodeU64(leaf.nextAuthoritySetID), ScaleCodec.encodeU32(leaf.nextAuthoritySetLen), leaf.nextAuthoritySetRoot, parachainHeadsRoot, messageCommitment ); return keccak256(encodedLeaf); } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {IERC20} from "./interfaces/IERC20.sol"; import {IGateway} from "./interfaces/IGateway.sol"; import {SafeTokenTransferFrom} from "./utils/SafeTransfer.sol"; import {AssetsStorage, TokenInfo} from "./storage/AssetsStorage.sol"; import {CoreStorage} from "./storage/CoreStorage.sol"; import {SubstrateTypes} from "./SubstrateTypes.sol"; import {ParaID, MultiAddress, Ticket, Costs} from "./Types.sol"; import {Address} from "./utils/Address.sol"; import {AgentExecutor} from "./AgentExecutor.sol"; import {Agent} from "./Agent.sol"; import {Call} from "./utils/Call.sol"; import {Token} from "./Token.sol"; /// @title Library for implementing Ethereum->Polkadot ERC20 transfers. library Assets { using Address for address; using SafeTokenTransferFrom for IERC20; /* Errors */ error InvalidToken(); error InvalidAmount(); error InvalidDestination(); error TokenNotRegistered(); error Unsupported(); error InvalidDestinationFee(); error AgentDoesNotExist(); error TokenAlreadyRegistered(); error TokenMintFailed(); error TokenTransferFailed(); function isTokenRegistered(address token) external view returns (bool) { return AssetsStorage.layout().tokenRegistry[token].isRegistered; } /// @dev transfer tokens from the sender to the specified agent function _transferToAgent(address agent, address token, address sender, uint128 amount) internal { if (!token.isContract()) { revert InvalidToken(); } if (amount == 0) { revert InvalidAmount(); } IERC20(token).safeTransferFrom(sender, agent, amount); } function sendTokenCosts( address token, ParaID destinationChain, uint128 destinationChainFee, uint128 maxDestinationChainFee ) external view returns (Costs memory costs) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); TokenInfo storage info = $.tokenRegistry[token]; if (!info.isRegistered) { revert TokenNotRegistered(); } return _sendTokenCosts(destinationChain, destinationChainFee, maxDestinationChainFee); } function _sendTokenCosts(ParaID destinationChain, uint128 destinationChainFee, uint128 maxDestinationChainFee) internal view returns (Costs memory costs) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); if ($.assetHubParaID == destinationChain) { costs.foreign = $.assetHubReserveTransferFee; } else { // Reduce the ability for users to perform arbitrage by exploiting a // favourable exchange rate. For example supplying Ether // and gaining a more valuable amount of DOT on the destination chain. // // Also prevents users from mistakenly sending more fees than would be required // which has negative effects like draining AssetHub's sovereign account. // // For safety, `maxDestinationChainFee` should be less valuable // than the gas cost to send tokens. if (destinationChainFee > maxDestinationChainFee) { revert InvalidDestinationFee(); } // If the final destination chain is not AssetHub, then the fee needs to additionally // include the cost of executing an XCM on the final destination parachain. costs.foreign = $.assetHubReserveTransferFee + destinationChainFee; } // We don't charge any extra fees beyond delivery costs costs.native = 0; } function sendToken( address token, address sender, ParaID destinationChain, MultiAddress calldata destinationAddress, uint128 destinationChainFee, uint128 maxDestinationChainFee, uint128 amount ) external returns (Ticket memory ticket) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); TokenInfo storage info = $.tokenRegistry[token]; if (!info.isRegistered) { revert TokenNotRegistered(); } if (info.foreignID == bytes32(0)) { return _sendNativeToken( token, sender, destinationChain, destinationAddress, destinationChainFee, maxDestinationChainFee, amount ); } else { return _sendForeignToken( info.foreignID, token, sender, destinationChain, destinationAddress, destinationChainFee, maxDestinationChainFee, amount ); } } function _sendNativeToken( address token, address sender, ParaID destinationChain, MultiAddress calldata destinationAddress, uint128 destinationChainFee, uint128 maxDestinationChainFee, uint128 amount ) internal returns (Ticket memory ticket) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); // Lock the funds into AssetHub's agent contract _transferToAgent($.assetHubAgent, token, sender, amount); ticket.dest = $.assetHubParaID; ticket.costs = _sendTokenCosts(destinationChain, destinationChainFee, maxDestinationChainFee); // Construct a message payload if (destinationChain == $.assetHubParaID) { // The funds will be minted into the receiver's account on AssetHub if (destinationAddress.isAddress32()) { // The receiver has a 32-byte account ID ticket.payload = SubstrateTypes.SendTokenToAssetHubAddress32( token, destinationAddress.asAddress32(), $.assetHubReserveTransferFee, amount ); } else { // AssetHub does not support 20-byte account IDs revert Unsupported(); } } else { if (destinationChainFee == 0) { revert InvalidDestinationFee(); } // The funds will be minted into sovereign account of the destination parachain on AssetHub, // and then reserve-transferred to the receiver's account on the destination parachain. if (destinationAddress.isAddress32()) { // The receiver has a 32-byte account ID ticket.payload = SubstrateTypes.SendTokenToAddress32( token, destinationChain, destinationAddress.asAddress32(), $.assetHubReserveTransferFee, destinationChainFee, amount ); } else if (destinationAddress.isAddress20()) { // The receiver has a 20-byte account ID ticket.payload = SubstrateTypes.SendTokenToAddress20( token, destinationChain, destinationAddress.asAddress20(), $.assetHubReserveTransferFee, destinationChainFee, amount ); } else { revert Unsupported(); } } emit IGateway.TokenSent(token, sender, destinationChain, destinationAddress, amount); } // @dev Transfer Polkadot-native tokens back to Polkadot function _sendForeignToken( bytes32 foreignID, address token, address sender, ParaID destinationChain, MultiAddress calldata destinationAddress, uint128 destinationChainFee, uint128 maxDestinationChainFee, uint128 amount ) internal returns (Ticket memory ticket) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); Token(token).burn(sender, amount); ticket.dest = $.assetHubParaID; ticket.costs = _sendTokenCosts(destinationChain, destinationChainFee, maxDestinationChainFee); // Construct a message payload if (destinationChain == $.assetHubParaID && destinationAddress.isAddress32()) { // The funds will be minted into the receiver's account on AssetHub // The receiver has a 32-byte account ID ticket.payload = SubstrateTypes.SendForeignTokenToAssetHubAddress32( foreignID, destinationAddress.asAddress32(), $.assetHubReserveTransferFee, amount ); } else { revert Unsupported(); } emit IGateway.TokenSent(token, sender, destinationChain, destinationAddress, amount); } function registerTokenCosts() external view returns (Costs memory costs) { return _registerTokenCosts(); } function _registerTokenCosts() internal view returns (Costs memory costs) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); // Cost of registering this asset on AssetHub costs.foreign = $.assetHubCreateAssetFee; // Extra fee to prevent spamming costs.native = $.registerTokenFee; } /// @dev Registers a token (only native tokens at this time) /// @param token The ERC20 token address. function registerToken(address token) external returns (Ticket memory ticket) { if (!token.isContract()) { revert InvalidToken(); } AssetsStorage.Layout storage $ = AssetsStorage.layout(); // NOTE: Explicitly allow a token to be re-registered. This offers resiliency // in case a previous registration attempt of the same token failed on the remote side. // It means that registration can be retried. TokenInfo storage info = $.tokenRegistry[token]; info.isRegistered = true; ticket.dest = $.assetHubParaID; ticket.costs = _registerTokenCosts(); ticket.payload = SubstrateTypes.RegisterToken(token, $.assetHubCreateAssetFee); emit IGateway.TokenRegistrationSent(token); } // @dev Register a new fungible Polkadot token for an agent function registerForeignToken(bytes32 foreignTokenID, string memory name, string memory symbol, uint8 decimals) external { AssetsStorage.Layout storage $ = AssetsStorage.layout(); if ($.tokenAddressOf[foreignTokenID] != address(0)) { revert TokenAlreadyRegistered(); } Token token = new Token(name, symbol, decimals); TokenInfo memory info = TokenInfo({isRegistered: true, foreignID: foreignTokenID}); $.tokenAddressOf[foreignTokenID] = address(token); $.tokenRegistry[address(token)] = info; emit IGateway.ForeignTokenRegistered(foreignTokenID, address(token)); } // @dev Mint foreign token from Polkadot function mintForeignToken(bytes32 foreignTokenID, address recipient, uint256 amount) external { address token = _ensureTokenAddressOf(foreignTokenID); Token(token).mint(recipient, amount); } // @dev Transfer ERC20 to `recipient` function transferNativeToken(address executor, address agent, address token, address recipient, uint128 amount) external { bytes memory call = abi.encodeCall(AgentExecutor.transferToken, (token, recipient, amount)); (bool success,) = Agent(payable(agent)).invoke(executor, call); if (!success) { revert TokenTransferFailed(); } } // @dev Get token address by tokenID function tokenAddressOf(bytes32 tokenID) external view returns (address) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); return $.tokenAddressOf[tokenID]; } // @dev Get token address by tokenID function _ensureTokenAddressOf(bytes32 tokenID) internal view returns (address) { AssetsStorage.Layout storage $ = AssetsStorage.layout(); if ($.tokenAddressOf[tokenID] == address(0)) { revert TokenNotRegistered(); } return $.tokenAddressOf[tokenID]; } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {AgentExecuteCommand, ParaID} from "./Types.sol"; import {SubstrateTypes} from "./SubstrateTypes.sol"; import {IERC20} from "./interfaces/IERC20.sol"; import {SafeTokenTransfer, SafeNativeTransfer} from "./utils/SafeTransfer.sol"; /// @title Code which will run within an `Agent` using `delegatecall`. /// @dev This is a singleton contract, meaning that all agents will execute the same code. contract AgentExecutor { using SafeTokenTransfer for IERC20; using SafeNativeTransfer for address payable; /// @dev Transfer ether to `recipient`. Unlike `_transferToken` This logic is not nested within `execute`, /// as the gateway needs to control an agent's ether balance directly. /// function transferNative(address payable recipient, uint256 amount) external { recipient.safeNativeTransfer(amount); } /// @dev Transfer ERC20 to `recipient`. Only callable via `execute`. function transferToken(address token, address recipient, uint128 amount) external { _transferToken(token, recipient, amount); } /// @dev Transfer ERC20 to `recipient`. Only callable via `execute`. function _transferToken(address token, address recipient, uint128 amount) internal { IERC20(token).safeTransfer(recipient, amount); } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; /// @title An agent contract that acts on behalf of a consensus system on Polkadot /// @dev Instances of this contract act as an agents for arbitrary consensus systems on Polkadot. These consensus systems /// can include toplevel parachains as as well as nested consensus systems within a parachain. contract Agent { error Unauthorized(); /// @dev The unique ID for this agent, derived from the MultiLocation of the corresponding consensus system on Polkadot bytes32 public immutable AGENT_ID; /// @dev The gateway contract controlling this agent address public immutable GATEWAY; constructor(bytes32 agentID) { AGENT_ID = agentID; GATEWAY = msg.sender; } /// @dev Agents can receive ether permissionlessly. /// This is important, as agents for top-level parachains also act as sovereign accounts from which message relayers /// are rewarded. receive() external payable {} /// @dev Allow the gateway to invoke some code within the context of this agent /// using `delegatecall`. Typically this code will be provided by `AgentExecutor.sol`. function invoke(address executor, bytes calldata data) external returns (bool, bytes memory) { if (msg.sender != GATEWAY) { revert Unauthorized(); } return executor.delegatecall(data); } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import { MultiAddress, multiAddressFromUint32, multiAddressFromBytes32, multiAddressFromBytes20 } from "./MultiAddress.sol"; import {UD60x18} from "prb/math/src/UD60x18.sol"; type ParaID is uint32; using {ParaIDEq as ==, ParaIDNe as !=, into} for ParaID global; function ParaIDEq(ParaID a, ParaID b) pure returns (bool) { return ParaID.unwrap(a) == ParaID.unwrap(b); } function ParaIDNe(ParaID a, ParaID b) pure returns (bool) { return !ParaIDEq(a, b); } function into(ParaID paraID) pure returns (ChannelID) { return ChannelID.wrap(keccak256(abi.encodePacked("para", ParaID.unwrap(paraID)))); } type ChannelID is bytes32; using {ChannelIDEq as ==, ChannelIDNe as !=} for ChannelID global; function ChannelIDEq(ChannelID a, ChannelID b) pure returns (bool) { return ChannelID.unwrap(a) == ChannelID.unwrap(b); } function ChannelIDNe(ChannelID a, ChannelID b) pure returns (bool) { return !ChannelIDEq(a, b); } /// @dev A messaging channel for a Polkadot parachain struct Channel { /// @dev The operating mode for this channel. Can be used to /// disable messaging on a per-channel basis. OperatingMode mode; /// @dev The current nonce for the inbound lane uint64 inboundNonce; /// @dev The current node for the outbound lane uint64 outboundNonce; /// @dev The address of the agent of the parachain owning this channel address agent; } /// @dev Inbound message from a Polkadot parachain (via BridgeHub) struct InboundMessage { /// @dev The parachain from which this message originated ChannelID channelID; /// @dev The channel nonce uint64 nonce; /// @dev The command to execute Command command; /// @dev The Parameters for the command bytes params; /// @dev The maximum gas allowed for message dispatch uint64 maxDispatchGas; /// @dev The maximum fee per gas uint256 maxFeePerGas; /// @dev The reward for message submission uint256 reward; /// @dev ID for this message bytes32 id; } enum OperatingMode { Normal, RejectingOutboundMessages } /// @dev Messages from Polkadot take the form of these commands. enum Command { AgentExecute, Upgrade, CreateAgent, CreateChannel, UpdateChannel, SetOperatingMode, TransferNativeFromAgent, SetTokenTransferFees, SetPricingParameters, TransferNativeToken, RegisterForeignToken, MintForeignToken, /// @dev Below enums are reserved in case upstream snowbridge adds more commands Reserved12, Reserved13, Reserved14, Reserved15, Reserved16, Reserved17, Reserved18, Reserved19, Reserved20, Reserved21, Reserved22, Reserved23, Reserved24, Reserved25, Reserved26, Reserved27, Reserved28, Reserved29, Reserved30, Reserved31, Test, ReportRewards, ReportSlashes } /// @dev DEPRECATED enum AgentExecuteCommand { TransferToken } /// @dev Application-level costs for a message struct Costs { /// @dev Costs in foreign currency uint256 foreign; /// @dev Costs in native currency uint256 native; } struct Ticket { ParaID dest; Costs costs; bytes payload; } struct TokenInfo { bool isRegistered; bytes32 foreignID; }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {ERC1967} from "./utils/ERC1967.sol"; import {Call} from "./utils/Call.sol"; import {Address} from "./utils/Address.sol"; import {IInitializable} from "./interfaces/IInitializable.sol"; import {IUpgradable} from "./interfaces/IUpgradable.sol"; /// @dev Upgrades implementation contract library Upgrade { using Address for address; function upgrade(address impl, bytes32 implCodeHash, bytes memory initializerParams) internal { // Verify that the implementation is actually a contract if (!impl.isContract()) { revert IUpgradable.InvalidContract(); } // As a sanity check, ensure that the codehash of implementation contract // matches the codehash in the upgrade proposal if (impl.codehash != implCodeHash) { revert IUpgradable.InvalidCodeHash(); } // Update the proxy with the address of the new implementation ERC1967.store(impl); // Call the initializer (bool success, bytes memory returndata) = impl.delegatecall(abi.encodeCall(IInitializable.initialize, initializerParams)); Call.verifyResult(success, returndata); emit IUpgradable.Upgraded(impl); } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; /** * @title Initialization of gateway logic contracts */ interface IInitializable { function initialize(bytes calldata data) external; }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; interface IUpgradable { // The new implementation address is a not a contract error InvalidContract(); // The supplied codehash does not match the new implementation codehash error InvalidCodeHash(); // The implementation contract was upgraded event Upgraded(address indexed implementation); }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; /// @title Minimal implementation of ERC1967 storage slot library ERC1967 { // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) bytes32 public constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; function load() internal view returns (address implementation) { assembly { implementation := sload(_IMPLEMENTATION_SLOT) } } function store(address implementation) internal { assembly { sstore(_IMPLEMENTATION_SLOT, implementation) } } }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 Axelar Network // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; library Address { // Checks whether `account` is a contract function isContract(address account) internal view returns (bool) { // https://eips.ethereum.org/EIPS/eip-1052 // keccak256('') == 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 return account.codehash != bytes32(0) && account.codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; } }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 Axelar Network // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {IERC20} from "../interfaces/IERC20.sol"; error TokenTransferFailed(); error NativeTransferFailed(); library SafeTokenCall { function safeCall(IERC20 token, bytes memory callData) internal { (bool success, bytes memory returnData) = address(token).call(callData); bool transferred = success && (returnData.length == uint256(0) || abi.decode(returnData, (bool))); if (!transferred || address(token).code.length == 0) { revert TokenTransferFailed(); } } } library SafeTokenTransfer { function safeTransfer(IERC20 token, address receiver, uint256 amount) internal { SafeTokenCall.safeCall(token, abi.encodeCall(IERC20.transfer, (receiver, amount))); } } library SafeTokenTransferFrom { function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal { SafeTokenCall.safeCall(token, abi.encodeCall(IERC20.transferFrom, (from, to, amount))); } } library SafeNativeTransfer { function safeNativeTransfer(address payable receiver, uint256 amount) internal { bool success; assembly { success := call(gas(), receiver, amount, 0, 0, 0, 0) } if (!success) { revert NativeTransferFailed(); } } }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 OpenZeppelin // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; // Derived from OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) library Call { function verifyResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(); } } } }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 OpenZeppelin // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> // Code from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol pragma solidity 0.8.25; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } /** * @dev Safely adds two unsigned 16-bit integers, preventing overflow by saturating to max uint16. */ function saturatingAdd(uint16 a, uint16 b) internal pure returns (uint16) { unchecked { uint16 c = a + b; if (c < a) { return 0xFFFF; } return c; } } /** * @dev Safely subtracts two unsigned 256-bit integers, preventing overflow by saturating to min uint256. */ function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { if (b >= a) { return 0; } return a - b; } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; library ScaleCodec { error UnsupportedCompactEncoding(); uint256 internal constant MAX_COMPACT_ENCODABLE_UINT = 2 ** 30 - 1; // Sources: // * https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity/50528 // * https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel function reverse256(uint256 input) internal pure returns (uint256 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } function reverse128(uint128 input) internal pure returns (uint128 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = (v >> 64) | (v << 64); } function reverse64(uint64 input) internal pure returns (uint64 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = (v >> 32) | (v << 32); } function reverse32(uint32 input) internal pure returns (uint32 v) { v = input; // swap bytes v = ((v & 0xFF00FF00) >> 8) | ((v & 0x00FF00FF) << 8); // swap 2-byte long pairs v = (v >> 16) | (v << 16); } function reverse16(uint16 input) internal pure returns (uint16 v) { v = input; // swap bytes v = (v >> 8) | (v << 8); } function encodeU256(uint256 input) internal pure returns (bytes32) { return bytes32(reverse256(input)); } function encodeU128(uint128 input) internal pure returns (bytes16) { return bytes16(reverse128(input)); } function encodeU64(uint64 input) internal pure returns (bytes8) { return bytes8(reverse64(input)); } function encodeU32(uint32 input) internal pure returns (bytes4) { return bytes4(reverse32(input)); } function encodeU16(uint16 input) internal pure returns (bytes2) { return bytes2(reverse16(input)); } function encodeU8(uint8 input) internal pure returns (bytes1) { return bytes1(input); } // Supports compact encoding of integers in [0, uint32.MAX] function encodeCompactU32(uint32 value) internal pure returns (bytes memory) { if (value <= 2 ** 6 - 1) { // add single byte flag return abi.encodePacked(uint8(value << 2)); } else if (value <= 2 ** 14 - 1) { // add two byte flag and create little endian encoding return abi.encodePacked(ScaleCodec.reverse16(uint16(((value << 2) + 1)))); } else if (value <= 2 ** 30 - 1) { // add four byte flag and create little endian encoding return abi.encodePacked(ScaleCodec.reverse32(uint32((value << 2)) + 2)); } else { return abi.encodePacked(uint8(3), ScaleCodec.reverse32(value)); } } function checkedEncodeCompactU32(uint256 value) internal pure returns (bytes memory) { if (value > type(uint32).max) { revert UnsupportedCompactEncoding(); } return encodeCompactU32(uint32(value)); } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {ChannelID, OperatingMode} from "./Types.sol"; import {UD60x18} from "prb/math/src/UD60x18.sol"; // Payload for AgentExecute struct AgentExecuteParams { bytes32 agentID; bytes payload; } // Payload for CreateAgent struct CreateAgentParams { /// @dev The agent ID of the consensus system bytes32 agentID; } // Payload for CreateChannel struct CreateChannelParams { /// @dev The channel ID ChannelID channelID; /// @dev The agent ID bytes32 agentID; /// @dev Initial operating mode OperatingMode mode; } // Payload for UpdateChannel struct UpdateChannelParams { /// @dev The parachain used to identify the channel to update ChannelID channelID; /// @dev The new operating mode OperatingMode mode; } // Payload for Upgrade struct UpgradeParams { /// @dev The address of the implementation contract address impl; /// @dev the codehash of the new implementation contract. /// Used to ensure the implementation isn't updated while /// the upgrade is in flight bytes32 implCodeHash; /// @dev parameters used to upgrade storage of the gateway bytes initParams; } // Payload for SetOperatingMode struct SetOperatingModeParams { /// @dev The new operating mode OperatingMode mode; } // Payload for TransferNativeFromAgent struct TransferNativeFromAgentParams { /// @dev The ID of the agent to transfer funds from bytes32 agentID; /// @dev The recipient of the funds address recipient; /// @dev The amount to transfer uint256 amount; } // Payload for SetTokenTransferFees struct SetTokenTransferFeesParams { /// @dev The remote fee (DOT) for registering a token on AssetHub uint128 assetHubCreateAssetFee; /// @dev The remote fee (DOT) for send tokens to AssetHub uint128 assetHubReserveTransferFee; /// @dev extra fee to register an asset and discourage spamming (Ether) uint256 registerTokenFee; } // Payload for SetPricingParameters struct SetPricingParametersParams { /// @dev The ETH/DOT exchange rate UD60x18 exchangeRate; /// @dev The cost of delivering messages to BridgeHub in DOT uint128 deliveryCost; /// @dev Fee multiplier UD60x18 multiplier; } // Payload for RegisterForeignToken struct RegisterForeignTokenParams { /// @dev The token ID (hash of stable location id of token) bytes32 foreignTokenID; /// @dev The name of the token string name; /// @dev The symbol of the token string symbol; /// @dev The decimal of the token uint8 decimals; } // Payload for MintForeignToken struct MintForeignTokenParams { /// @dev The token ID bytes32 foreignTokenID; /// @dev The address of the recipient address recipient; /// @dev The amount to mint with uint256 amount; } // Payload for TransferToken struct TransferNativeTokenParams { /// @dev The agent ID of the consensus system bytes32 agentID; /// @dev The token address address token; /// @dev The address of the recipient address recipient; /// @dev The amount to mint with uint128 amount; }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {Channel, OperatingMode, ChannelID, ParaID} from "../Types.sol"; library CoreStorage { struct Layout { // Operating mode: OperatingMode mode; // Message channels mapping(ChannelID channelID => Channel) channels; // Agents mapping(bytes32 agentID => address) agents; // Agent addresses mapping(address agent => bytes32 agentID) agentAddresses; } bytes32 internal constant SLOT = keccak256("org.snowbridge.storage.core"); function layout() internal pure returns (Layout storage $) { bytes32 slot = SLOT; assembly { $.slot := slot } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {UD60x18} from "prb/math/src/UD60x18.sol"; library PricingStorage { struct Layout { /// @dev The ETH/DOT exchange rate UD60x18 exchangeRate; /// @dev The cost of delivering messages to BridgeHub in DOT uint128 deliveryCost; /// @dev Fee multiplier UD60x18 multiplier; } bytes32 internal constant SLOT = keccak256("org.snowbridge.storage.pricing"); function layout() internal pure returns (Layout storage $) { bytes32 slot = SLOT; assembly { $.slot := slot } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {TokenInfo, ParaID} from "../Types.sol"; library AssetsStorage { struct Layout { // Native token registry by token address mapping(address token => TokenInfo) tokenRegistry; address assetHubAgent; ParaID assetHubParaID; // XCM fee charged by AssetHub for registering a token (DOT) uint128 assetHubCreateAssetFee; // XCM fee charged by AssetHub for receiving a token from the Gateway (DOT) uint128 assetHubReserveTransferFee; // Extra fee for registering a token, to discourage spamming (Ether) uint256 registerTokenFee; // Foreign token registry by token ID mapping(bytes32 foreignID => address) tokenAddressOf; } bytes32 internal constant SLOT = keccak256("org.snowbridge.storage.assets"); function layout() internal pure returns (Layout storage $) { bytes32 slot = SLOT; assembly { $.slot := slot } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; library OperatorStorage { struct Layout { address operator; } bytes32 internal constant SLOT = keccak256("org.snowbridge.storage.operator"); function layout() internal pure returns (Layout storage $) { bytes32 slot = SLOT; assembly { $.slot := slot } } }
//SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>
pragma solidity 0.8.25;
library GatewayCoreStorage {
struct Layout {
// Owner of the gateway for configuration purposes.
address owner;
// Address of the Symbiotic middleware to properly execute messages.
address middleware;
}
bytes32 internal constant SLOT = keccak256("tanssi-bridge-relayer.gateway.core");
function layout() internal pure returns (Layout storage ptr) {
bytes32 slot = SLOT;
assembly {
ptr.slot := slot
}
}
}// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; /* ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ████████╗██╗ ██╗ ██╔══██╗██╔══██╗██╔══██╗████╗ ████║██╔══██╗╚══██╔══╝██║ ██║ ██████╔╝██████╔╝██████╔╝██╔████╔██║███████║ ██║ ███████║ ██╔═══╝ ██╔══██╗██╔══██╗██║╚██╔╝██║██╔══██║ ██║ ██╔══██║ ██║ ██║ ██║██████╔╝██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║ ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ██╗ ██╗██████╗ ██████╗ ██████╗ ██╗ ██╗ ██╗ █████╗ ██║ ██║██╔══██╗██╔════╝ ██╔═████╗╚██╗██╔╝███║██╔══██╗ ██║ ██║██║ ██║███████╗ ██║██╔██║ ╚███╔╝ ╚██║╚█████╔╝ ██║ ██║██║ ██║██╔═══██╗████╔╝██║ ██╔██╗ ██║██╔══██╗ ╚██████╔╝██████╔╝╚██████╔╝╚██████╔╝██╔╝ ██╗ ██║╚█████╔╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚════╝ */ import "./ud60x18/Casting.sol"; import "./ud60x18/Constants.sol"; import "./ud60x18/Conversions.sol"; import "./ud60x18/Errors.sol"; import "./ud60x18/Helpers.sol"; import "./ud60x18/Math.sol"; import "./ud60x18/ValueType.sol";
//SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>
pragma solidity 0.8.25;
import {console2} from "forge-std/console2.sol";
import {BeefyClient} from "./BeefyClient.sol";
import {ScaleCodec} from "./utils/ScaleCodec.sol";
import {OSubstrateTypes} from "./libraries/OSubstrateTypes.sol";
import {MultiAddress, Ticket, Costs, ParaID} from "./Types.sol";
import {IOGateway} from "./interfaces/IOGateway.sol";
library Operators {
error Operators__OperatorsLengthTooLong();
error Operators__OperatorsKeysCannotBeEmpty();
uint16 private constant MAX_OPERATORS = 1000;
function encodeOperatorsData(bytes32[] calldata operatorsKeys, uint48 epoch)
internal
returns (Ticket memory ticket)
{
if (operatorsKeys.length == 0) {
revert Operators__OperatorsKeysCannotBeEmpty();
}
uint256 validatorsKeysLength = operatorsKeys.length;
if (validatorsKeysLength > MAX_OPERATORS) {
revert Operators__OperatorsLengthTooLong();
}
// TODO: This is a type from Snowbridge, do we want our own simplified Ticket type?
ticket.dest = ParaID.wrap(0);
// TODO For now mock it to 0
ticket.costs = Costs(0, 0);
ticket.payload = OSubstrateTypes.EncodedOperatorsData(operatorsKeys, uint32(validatorsKeysLength), epoch);
emit IOGateway.OperatorsDataCreated(validatorsKeysLength, ticket.payload);
}
}//SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>
pragma solidity ^0.8.0;
import {ParaID, Command} from "../Types.sol";
import {IGateway} from "./IGateway.sol";
interface IOGateway is IGateway {
// Emitted when operators data has been created
event OperatorsDataCreated(uint256 indexed validatorsCount, bytes payload);
// Emitted when owner of the gateway is changed.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// Emitted when the middleware contract address is changed by the owner.
event MiddlewareChanged(address indexed previousMiddleware, address indexed newMiddleware);
// Emitted when the middleware fails to apply an individual slash
event UnableToProcessIndividualSlashB(
bytes32 indexed operatorKey, uint256 slashFranction, uint256 indexed epoch, bytes error
);
// Emitted when the middleware fails to apply an individual slash
event UnableToProcessIndividualSlashS(
bytes32 indexed operatorKey, uint256 slashFranction, uint256 indexed epoch, string error
);
// Emitted when the middleware fails to apply the slash message
event UnableToProcessSlashMessageB(bytes error);
// Emitted when the middleware fails to apply the slash message
event UnableToProcessSlashMessageS(string error);
// Emitted when the middleware fails to apply the slash message
event UnableToProcessRewardsMessageB(bytes error);
// Emitted when the middleware fails to apply the slash message
event UnableToProcessRewardsMessageS(string error);
// Emitted when a non accepted command is received
event NotImplementedCommand(Command command);
// Slash struct, used to decode slashes, which are identified by
// operatorKey to be slashed
// slashFraction to be applied as parts per billion
// epoch identifying when the slash happened
struct Slash {
bytes32 operatorKey;
uint256 slashFraction;
uint256 epoch;
}
struct SlashParams {
uint256 eraIndex;
Slash[] slashes;
}
function s_middleware() external view returns (address);
function reportSlashes(bytes calldata data) external;
function sendRewards(bytes calldata data) external;
function sendOperatorsData(bytes32[] calldata data, uint48 epoch) external;
function setMiddleware(address middleware) external;
}//SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>
pragma solidity ^0.8.0;
interface IMiddlewareBasic {
/**
* @notice Distribute rewards for a specific era contained in an epoch by providing a Merkle root, total points, total amount of tokens and the token address of the rewards.
* @param epoch network epoch of the middleware
* @param eraIndex era index of Starlight's rewards distribution
* @param totalPointsToken total amount of points for the reward distribution
* @param amount amount of tokens to distribute
* @param root Merkle root of the reward distribution
* @param tokenAddress The token address of the rewards
* @dev This function is called by the gateway only
* @dev Emit DistributeRewards event.
*/
function distributeRewards(
uint256 epoch,
uint256 eraIndex,
uint256 totalPointsToken,
uint256 amount,
bytes32 root,
address tokenAddress
) external;
/**
* @notice Slashes an operator's stake
* @dev Only the owner can call this function
* @dev This function first updates the stake cache for the target epoch
* @param epoch The epoch number
* @param operatorKey The operator key to slash
* @param percentage Percentage to slash, represented as parts per billion.
*/
function slash(uint48 epoch, bytes32 operatorKey, uint256 percentage) external;
/**
* @notice Determines which epoch a timestamp belongs to
* @param timestamp The timestamp to check
* @return epoch The corresponding epoch number
*/
function getEpochAtTs(uint48 timestamp) external view returns (uint48 epoch);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; // Used to verify merkle proofs generated by https://github.com/paritytech/substrate/tree/master/utils/binary-merkle-tree library SubstrateMerkleProof { /** * @notice Verify that a specific leaf element is part of the Merkle Tree at a specific position in the tree * * The tree would have been constructed using * https://paritytech.github.io/substrate/master/binary_merkle_tree/fn.merkle_root.html * * This implementation adapted from * https://paritytech.github.io/substrate/master/binary_merkle_tree/fn.verify_proof.html * * @param root the root of the merkle tree * @param leaf the leaf which needs to be proven * @param position the position of the leaf, index starting with 0 * @param width the width or number of leaves in the tree * @param proof the array of proofs to help verify the leaf's membership, ordered from leaf to root * @return a boolean value representing the success or failure of the operation */ function verify(bytes32 root, bytes32 leaf, uint256 position, uint256 width, bytes32[] calldata proof) internal pure returns (bool) { if (position >= width) { return false; } return root == computeRoot(leaf, position, width, proof); } function computeRoot(bytes32 leaf, uint256 position, uint256 width, bytes32[] calldata proof) internal pure returns (bytes32) { bytes32 node = leaf; unchecked { for (uint256 i = 0; i < proof.length; i++) { if (position & 1 == 1 || position + 1 == width) { node = efficientHash(proof[i], node); } else { node = efficientHash(node, proof[i]); } position = position >> 1; width = ((width - 1) >> 1) + 1; } return node; } } function efficientHash(bytes32 a, bytes32 b) internal pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {ECDSA} from "openzeppelin/utils/cryptography/ECDSA.sol"; import {SubstrateMerkleProof} from "./utils/SubstrateMerkleProof.sol"; import {Bitfield} from "./utils/Bitfield.sol"; import {Uint16Array, createUint16Array} from "./utils/Uint16Array.sol"; import {Math} from "./utils/Math.sol"; import {MMRProof} from "./utils/MMRProof.sol"; import {ScaleCodec} from "./utils/ScaleCodec.sol"; /** * @title BeefyClient * * High-level documentation at https://docs.snowbridge.network/architecture/verification/polkadot * * To submit new commitments, relayers must call the following methods sequentially: * 1. submitInitial: Setup the session for the interactive submission * 2. commitPrevRandao: Commit to a random seed for generating a validator subsampling * 3. createFinalBitfield: Generate the validator subsampling * 4. submitFinal: Complete submission after providing the request validator signatures * */ contract BeefyClient { using Math for uint16; using Math for uint256; /* Events */ /** * @dev Emitted when the MMR root is updated * @param mmrRoot the updated MMR root * @param blockNumber the beefy block number of the updated MMR root */ event NewMMRRoot(bytes32 mmrRoot, uint64 blockNumber); /** * @dev Emitted when a new ticket has been created * @param relayer The relayer who created the ticket * @param blockNumber the parent block number of the candidate MMR root */ event NewTicket(address relayer, uint64 blockNumber); /* Types */ /** * @dev The Commitment, with its payload, is the core thing we are trying to verify with * this contract. It contains an MMR root that commits to the polkadot history, including * past blocks and parachain blocks and can be used to verify both polkadot and parachain blocks. */ struct Commitment { // Relay chain block number uint32 blockNumber; // ID of the validator set that signed the commitment uint64 validatorSetID; // The payload of the new commitment in beefy justifications (in // our case, this is a new MMR root for all past polkadot blocks) PayloadItem[] payload; } /** * @dev Each PayloadItem is a piece of data signed by validators at a particular block. */ struct PayloadItem { // An ID that references a description of the data in the payload item. // Known payload ids can be found [upstream](https://github.com/paritytech/substrate/blob/fe1f8ba1c4f23931ae89c1ada35efb3d908b50f5/primitives/consensus/beefy/src/payload.rs#L27). bytes2 payloadID; // The contents of the payload item bytes data; } /** * @dev The ValidatorProof is a proof used to verify a commitment signature */ struct ValidatorProof { // The parity bit to specify the intended solution uint8 v; // The x component on the secp256k1 curve bytes32 r; // The challenge solution bytes32 s; // Leaf index of the validator address in the merkle tree uint256 index; // Validator address address account; // Merkle proof for the validator bytes32[] proof; } /** * @dev A ticket tracks working state for the interactive submission of new commitments */ struct Ticket { // The block number this ticket was issued uint64 blockNumber; // Length of the validator set that signed the commitment uint32 validatorSetLen; // The number of signatures required uint32 numRequiredSignatures; // The PREVRANDAO seed selected for this ticket session uint256 prevRandao; // Hash of a bitfield claiming which validators have signed bytes32 bitfieldHash; } /// @dev The MMRLeaf describes the leaf structure of the MMR struct MMRLeaf { // Version of the leaf type uint8 version; // Parent number of the block this leaf describes uint32 parentNumber; // Parent hash of the block this leaf describes bytes32 parentHash; // Validator set id that will be part of consensus for the next block uint64 nextAuthoritySetID; // Length of that validator set uint32 nextAuthoritySetLen; // Merkle root of all public keys in that validator set bytes32 nextAuthoritySetRoot; // Merkle root of all parachain headers in this block bytes32 parachainHeadsRoot; // Message commitment bytes32 messageCommitment; } /** * @dev The ValidatorSet describes a BEEFY validator set */ struct ValidatorSet { // Identifier for the set uint128 id; // Number of validators in the set uint128 length; // Merkle root of BEEFY validator addresses bytes32 root; } /** * @dev The ValidatorSetState describes a BEEFY validator set along with signature usage counters */ struct ValidatorSetState { // Identifier for the set uint128 id; // Number of validators in the set uint128 length; // Merkle root of BEEFY validator addresses bytes32 root; // Number of times a validator signature has been used Uint16Array usageCounters; } /* State */ /// @dev The latest verified MMR root bytes32 public latestMMRRoot; /// @dev The block number in the relay chain in which the latest MMR root was emitted uint64 public latestBeefyBlock; /// @dev State of the current validator set ValidatorSetState public currentValidatorSet; /// @dev State of the next validator set ValidatorSetState public nextValidatorSet; /// @dev Pending tickets for commitment submission mapping(bytes32 ticketID => Ticket) public tickets; /* Constants */ /** * @dev Beefy payload id for MMR Root payload items: * https://github.com/paritytech/substrate/blob/fe1f8ba1c4f23931ae89c1ada35efb3d908b50f5/primitives/consensus/beefy/src/payload.rs#L33 */ bytes2 public constant MMR_ROOT_ID = bytes2("mh"); /** * @dev Minimum delay in number of blocks that a relayer must wait between calling * submitInitial and commitPrevRandao. In production this should be set to MAX_SEED_LOOKAHEAD: * https://eth2book.info/altair/part3/config/preset#max_seed_lookahead */ uint256 public immutable randaoCommitDelay; /** * @dev after randaoCommitDelay is reached, relayer must * call commitPrevRandao within this number of blocks. * Without this expiration, relayers can roll the dice infinitely to get the subsampling * they desire. */ uint256 public immutable randaoCommitExpiration; /** * @dev Minimum number of signatures required to validate a new commitment. This parameter * is calculated based on `randaoCommitExpiration`. See ~/scripts/beefy_signature_sampling.py * for the calculation. */ uint256 public immutable minNumRequiredSignatures; /* Errors */ error InvalidBitfield(); error InvalidBitfieldLength(); error InvalidCommitment(); error InvalidMMRLeaf(); error InvalidMMRLeafProof(); error InvalidMMRRootLength(); error InvalidSignature(); error InvalidTicket(); error InvalidValidatorProof(); error InvalidValidatorProofLength(); error CommitmentNotRelevant(); error NotEnoughClaims(); error PrevRandaoAlreadyCaptured(); error PrevRandaoNotCaptured(); error StaleCommitment(); error TicketExpired(); error WaitPeriodNotOver(); constructor( uint256 _randaoCommitDelay, uint256 _randaoCommitExpiration, uint256 _minNumRequiredSignatures, uint64 _initialBeefyBlock, ValidatorSet memory _initialValidatorSet, ValidatorSet memory _nextValidatorSet ) { if (_nextValidatorSet.id != _initialValidatorSet.id + 1) { revert("invalid-constructor-params"); } randaoCommitDelay = _randaoCommitDelay; randaoCommitExpiration = _randaoCommitExpiration; minNumRequiredSignatures = _minNumRequiredSignatures; latestBeefyBlock = _initialBeefyBlock; currentValidatorSet.id = _initialValidatorSet.id; currentValidatorSet.length = _initialValidatorSet.length; currentValidatorSet.root = _initialValidatorSet.root; currentValidatorSet.usageCounters = createUint16Array(currentValidatorSet.length); nextValidatorSet.id = _nextValidatorSet.id; nextValidatorSet.length = _nextValidatorSet.length; nextValidatorSet.root = _nextValidatorSet.root; nextValidatorSet.usageCounters = createUint16Array(nextValidatorSet.length); } /* External Functions */ /** * @dev Begin submission of commitment * @param commitment contains the commitment signed by the validators * @param bitfield a bitfield claiming which validators have signed the commitment * @param proof a proof that a single validator from currentValidatorSet has signed the commitment */ function submitInitial(Commitment calldata commitment, uint256[] calldata bitfield, ValidatorProof calldata proof) external { if (commitment.blockNumber <= latestBeefyBlock) { revert StaleCommitment(); } ValidatorSetState storage vset; uint16 signatureUsageCount; if (commitment.validatorSetID == currentValidatorSet.id) { signatureUsageCount = currentValidatorSet.usageCounters.get(proof.index); currentValidatorSet.usageCounters.set(proof.index, signatureUsageCount.saturatingAdd(1)); vset = currentValidatorSet; } else if (commitment.validatorSetID == nextValidatorSet.id) { signatureUsageCount = nextValidatorSet.usageCounters.get(proof.index); nextValidatorSet.usageCounters.set(proof.index, signatureUsageCount.saturatingAdd(1)); vset = nextValidatorSet; } else { revert InvalidCommitment(); } // Check if merkle proof is valid based on the validatorSetRoot and if proof is included in bitfield if (!isValidatorInSet(vset, proof.account, proof.index, proof.proof) || !Bitfield.isSet(bitfield, proof.index)) { revert InvalidValidatorProof(); } // Check if validatorSignature is correct, ie. check if it matches // the signature of senderPublicKey on the commitmentHash bytes32 commitmentHash = keccak256(encodeCommitment(commitment)); if (ECDSA.recover(commitmentHash, proof.v, proof.r, proof.s) != proof.account) { revert InvalidSignature(); } // For the initial submission, the supplied bitfield should claim that more than // two thirds of the validator set have sign the commitment if (Bitfield.countSetBits(bitfield) < computeQuorum(vset.length)) { revert NotEnoughClaims(); } tickets[createTicketID(msg.sender, commitmentHash)] = Ticket({ blockNumber: uint64(block.number), validatorSetLen: uint32(vset.length), numRequiredSignatures: uint32( computeNumRequiredSignatures(vset.length, signatureUsageCount, minNumRequiredSignatures) ), prevRandao: 0, bitfieldHash: keccak256(abi.encodePacked(bitfield)) }); emit NewTicket(msg.sender, commitment.blockNumber); } /** * @dev Capture PREVRANDAO * @param commitmentHash contains the commitmentHash signed by the validators */ function commitPrevRandao(bytes32 commitmentHash) external { bytes32 ticketID = createTicketID(msg.sender, commitmentHash); Ticket storage ticket = tickets[ticketID]; if (ticket.blockNumber == 0) { revert InvalidTicket(); } if (ticket.prevRandao != 0) { revert PrevRandaoAlreadyCaptured(); } // relayer must wait `randaoCommitDelay` blocks if (block.number < ticket.blockNumber + randaoCommitDelay) { revert WaitPeriodNotOver(); } // relayer can capture within `randaoCommitExpiration` blocks if (block.number > ticket.blockNumber + randaoCommitDelay + randaoCommitExpiration) { delete tickets[ticketID]; revert TicketExpired(); } // Post-merge, the difficulty opcode now returns PREVRANDAO ticket.prevRandao = block.prevrandao; } /** * @dev Submit a commitment and leaf for final verification * @param commitment contains the full commitment that was used for the commitmentHash * @param bitfield claiming which validators have signed the commitment * @param proofs a struct containing the data needed to verify all validator signatures * @param leaf an MMR leaf provable using the MMR root in the commitment payload * @param leafProof an MMR leaf proof * @param leafProofOrder a bitfield describing the order of each item (left vs right) */ function submitFinal( Commitment calldata commitment, uint256[] calldata bitfield, ValidatorProof[] calldata proofs, MMRLeaf calldata leaf, bytes32[] calldata leafProof, uint256 leafProofOrder ) external { bytes32 commitmentHash = keccak256(encodeCommitment(commitment)); bytes32 ticketID = createTicketID(msg.sender, commitmentHash); validateTicket(ticketID, commitment, bitfield); bool is_next_session = false; ValidatorSetState storage vset; if (commitment.validatorSetID == nextValidatorSet.id) { is_next_session = true; vset = nextValidatorSet; } else if (commitment.validatorSetID == currentValidatorSet.id) { vset = currentValidatorSet; } else { revert InvalidCommitment(); } verifyCommitment(commitmentHash, ticketID, bitfield, vset, proofs); bytes32 newMMRRoot = ensureProvidesMMRRoot(commitment); if (is_next_session) { if (leaf.nextAuthoritySetID != nextValidatorSet.id + 1) { revert InvalidMMRLeaf(); } bool leafIsValid = MMRProof.verifyLeafProof(newMMRRoot, keccak256(encodeMMRLeaf(leaf)), leafProof, leafProofOrder); if (!leafIsValid) { revert InvalidMMRLeafProof(); } currentValidatorSet = nextValidatorSet; nextValidatorSet.id = leaf.nextAuthoritySetID; nextValidatorSet.length = leaf.nextAuthoritySetLen; nextValidatorSet.root = leaf.nextAuthoritySetRoot; nextValidatorSet.usageCounters = createUint16Array(leaf.nextAuthoritySetLen); } latestMMRRoot = newMMRRoot; latestBeefyBlock = commitment.blockNumber; delete tickets[ticketID]; emit NewMMRRoot(newMMRRoot, commitment.blockNumber); } /** * @dev Verify that the supplied MMR leaf is included in the latest verified MMR root. * @param leafHash contains the merkle leaf to be verified * @param proof contains simplified mmr proof * @param proofOrder a bitfield describing the order of each item (left vs right) */ function verifyMMRLeafProof(bytes32 leafHash, bytes32[] calldata proof, uint256 proofOrder) external view returns (bool) { return MMRProof.verifyLeafProof(latestMMRRoot, leafHash, proof, proofOrder); } /** * @dev Helper to create an initial validator bitfield. * @param bitsToSet contains indexes of all signed validators, should be deduplicated * @param length of validator set */ function createInitialBitfield(uint256[] calldata bitsToSet, uint256 length) external pure returns (uint256[] memory) { if (length < bitsToSet.length) { revert InvalidBitfieldLength(); } return Bitfield.createBitfield(bitsToSet, length); } /** * @dev Helper to create a final bitfield, with subsampled validator selections * @param commitmentHash contains the commitmentHash signed by the validators * @param bitfield claiming which validators have signed the commitment */ function createFinalBitfield(bytes32 commitmentHash, uint256[] calldata bitfield) external view returns (uint256[] memory) { Ticket storage ticket = tickets[createTicketID(msg.sender, commitmentHash)]; if (ticket.bitfieldHash != keccak256(abi.encodePacked(bitfield))) { revert InvalidBitfield(); } return Bitfield.subsample(ticket.prevRandao, bitfield, ticket.numRequiredSignatures, ticket.validatorSetLen); } /* Internal Functions */ // Creates a unique ticket ID for a new interactive prover-verifier session function createTicketID(address account, bytes32 commitmentHash) internal pure returns (bytes32 value) { assembly { mstore(0x00, account) mstore(0x20, commitmentHash) value := keccak256(0x0, 0x40) } } /** * @dev Calculates the number of required signatures for `submitFinal`. * @param validatorSetLen The length of the validator set * @param signatureUsageCount A counter of the number of times the validator signature was previously used in a call to `submitInitial` within the session. * @param minRequiredSignatures The minimum amount of signatures to verify */ // For more details on the calculation, read the following: // 1. https://docs.snowbridge.network/architecture/verification/polkadot#signature-sampling // 2. https://hackmd.io/9OedC7icR5m-in_moUZ_WQ function computeNumRequiredSignatures( uint256 validatorSetLen, uint256 signatureUsageCount, uint256 minRequiredSignatures ) internal pure returns (uint256) { // Start with the minimum number of signatures. uint256 numRequiredSignatures = minRequiredSignatures; // Add signatures based on the number of validators in the validator set. numRequiredSignatures += Math.log2(validatorSetLen, Math.Rounding.Ceil); // Add signatures based on the signature usage count. numRequiredSignatures += 1 + (2 * Math.log2(signatureUsageCount, Math.Rounding.Ceil)); // Never require more signatures than a 2/3 majority return Math.min(numRequiredSignatures, computeQuorum(validatorSetLen)); } /** * @dev Calculates 2/3 majority required for quorum for a given number of validators. * @param numValidators The number of validators in the validator set. */ function computeQuorum(uint256 numValidators) internal pure returns (uint256) { return numValidators - (numValidators - 1) / 3; } /** * @dev Verify commitment using the supplied signature proofs */ function verifyCommitment( bytes32 commitmentHash, bytes32 ticketID, uint256[] calldata bitfield, ValidatorSetState storage vset, ValidatorProof[] calldata proofs ) internal view { Ticket storage ticket = tickets[ticketID]; // Verify that enough signature proofs have been supplied uint256 numRequiredSignatures = ticket.numRequiredSignatures; if (proofs.length != numRequiredSignatures) { revert InvalidValidatorProofLength(); } // Generate final bitfield indicating which validators need to be included in the proofs. uint256[] memory finalbitfield = Bitfield.subsample(ticket.prevRandao, bitfield, numRequiredSignatures, vset.length); for (uint256 i = 0; i < proofs.length; i++) { ValidatorProof calldata proof = proofs[i]; // Check that validator is in bitfield if (!Bitfield.isSet(finalbitfield, proof.index)) { revert InvalidValidatorProof(); } // Check that validator is actually in a validator set if (!isValidatorInSet(vset, proof.account, proof.index, proof.proof)) { revert InvalidValidatorProof(); } // Check that validator signed the commitment if (ECDSA.recover(commitmentHash, proof.v, proof.r, proof.s) != proof.account) { revert InvalidSignature(); } // Ensure no validator can appear more than once in bitfield Bitfield.unset(finalbitfield, proof.index); } } // Ensure that the commitment provides a new MMR root function ensureProvidesMMRRoot(Commitment calldata commitment) internal pure returns (bytes32) { for (uint256 i = 0; i < commitment.payload.length; i++) { if (commitment.payload[i].payloadID == MMR_ROOT_ID) { if (commitment.payload[i].data.length != 32) { revert InvalidMMRRootLength(); } else { return bytes32(commitment.payload[i].data); } } } revert CommitmentNotRelevant(); } function encodeCommitment(Commitment calldata commitment) internal pure returns (bytes memory) { return bytes.concat( encodeCommitmentPayload(commitment.payload), ScaleCodec.encodeU32(commitment.blockNumber), ScaleCodec.encodeU64(commitment.validatorSetID) ); } function encodeCommitmentPayload(PayloadItem[] calldata items) internal pure returns (bytes memory) { bytes memory payload = ScaleCodec.checkedEncodeCompactU32(items.length); for (uint256 i = 0; i < items.length; i++) { payload = bytes.concat( payload, items[i].payloadID, ScaleCodec.checkedEncodeCompactU32(items[i].data.length), items[i].data ); } return payload; } function encodeMMRLeaf(MMRLeaf calldata leaf) internal pure returns (bytes memory) { return bytes.concat( ScaleCodec.encodeU8(leaf.version), ScaleCodec.encodeU32(leaf.parentNumber), leaf.parentHash, ScaleCodec.encodeU64(leaf.nextAuthoritySetID), ScaleCodec.encodeU32(leaf.nextAuthoritySetLen), leaf.nextAuthoritySetRoot, leaf.parachainHeadsRoot, leaf.messageCommitment ); } /** * @dev Checks if a validators address is a member of the merkle tree * @param vset The validator set * @param account The address of the validator to check for inclusion in `vset`. * @param index The leaf index of the account in the merkle tree of validator set addresses. * @param proof Merkle proof required for validation of the address * @return true if the validator is in the set */ function isValidatorInSet(ValidatorSetState storage vset, address account, uint256 index, bytes32[] calldata proof) internal view returns (bool) { bytes32 hashedLeaf = keccak256(abi.encodePacked(account)); return SubstrateMerkleProof.verify(vset.root, hashedLeaf, index, vset.length, proof); } /** * @dev Basic validation of a ticket for submitFinal */ function validateTicket(bytes32 ticketID, Commitment calldata commitment, uint256[] calldata bitfield) internal view { Ticket storage ticket = tickets[ticketID]; if (ticket.blockNumber == 0) { // submitInitial hasn't been called yet revert InvalidTicket(); } if (ticket.prevRandao == 0) { // commitPrevRandao hasn't been called yet revert PrevRandaoNotCaptured(); } if (commitment.blockNumber <= latestBeefyBlock) { // ticket is obsolete revert StaleCommitment(); } if (ticket.bitfieldHash != keccak256(abi.encodePacked(bitfield))) { // The provided claims bitfield isn't the same one that was // passed to submitInitial revert InvalidBitfield(); } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {ScaleCodec} from "./utils/ScaleCodec.sol"; import {ParaID} from "./Types.sol"; /** * @title SCALE encoders for common Substrate types */ library SubstrateTypes { error UnsupportedCompactEncoding(); /** * @dev Encodes `MultiAddress::Id`: https://crates.parity.io/sp_runtime/enum.MultiAddress.html#variant.Id * @return bytes SCALE-encoded bytes */ // solhint-disable-next-line func-name-mixedcase function MultiAddressWithID(bytes32 account) internal pure returns (bytes memory) { return bytes.concat(hex"00", account); } /** * @dev Encodes `H160`: https://crates.parity.io/sp_core/struct.H160.html * @return bytes SCALE-encoded bytes */ // solhint-disable-next-line func-name-mixedcase function H160(address account) internal pure returns (bytes memory) { return abi.encodePacked(account); } function VecU8(bytes memory input) internal pure returns (bytes memory) { return bytes.concat(ScaleCodec.checkedEncodeCompactU32(input.length), input); } /** * @dev Encodes `Option::None`: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None * @return bytes SCALE-encoded bytes */ // solhint-disable-next-line func-name-mixedcase function None() internal pure returns (bytes memory) { return hex"00"; } // solhint-disable-next-line func-name-mixedcase function OptionParaID(ParaID v) internal pure returns (bytes memory) { if (ParaID.unwrap(v) == 0) { return hex"00"; } else { return bytes.concat(bytes1(0x01), ScaleCodec.encodeU32(uint32(ParaID.unwrap(v)))); } } /** * @dev SCALE-encodes `router_primitives::inbound::VersionedMessage` containing payload * `NativeTokensMessage::Create` */ // solhint-disable-next-line func-name-mixedcase function RegisterToken(address token, uint128 fee) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x00), SubstrateTypes.H160(token), ScaleCodec.encodeU128(fee) ); } /** * @dev SCALE-encodes `router_primitives::inbound::VersionedMessage` containing payload * `NativeTokensMessage::Mint` */ // destination is AccountID32 address on AssetHub function SendTokenToAssetHubAddress32(address token, bytes32 recipient, uint128 xcmFee, uint128 amount) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x01), SubstrateTypes.H160(token), bytes1(0x00), recipient, ScaleCodec.encodeU128(amount), ScaleCodec.encodeU128(xcmFee) ); } // destination is AccountID32 address function SendTokenToAddress32( address token, ParaID paraID, bytes32 recipient, uint128 xcmFee, uint128 destinationXcmFee, uint128 amount ) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x01), SubstrateTypes.H160(token), bytes1(0x01), ScaleCodec.encodeU32(uint32(ParaID.unwrap(paraID))), recipient, ScaleCodec.encodeU128(destinationXcmFee), ScaleCodec.encodeU128(amount), ScaleCodec.encodeU128(xcmFee) ); } // destination is AccountID20 address function SendTokenToAddress20( address token, ParaID paraID, bytes20 recipient, uint128 xcmFee, uint128 destinationXcmFee, uint128 amount ) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x01), SubstrateTypes.H160(token), bytes1(0x02), ScaleCodec.encodeU32(uint32(ParaID.unwrap(paraID))), recipient, ScaleCodec.encodeU128(destinationXcmFee), ScaleCodec.encodeU128(amount), ScaleCodec.encodeU128(xcmFee) ); } function SendForeignTokenToAssetHubAddress32(bytes32 tokenID, bytes32 recipient, uint128 xcmFee, uint128 amount) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x02), tokenID, bytes1(0x00), recipient, ScaleCodec.encodeU128(amount), ScaleCodec.encodeU128(xcmFee) ); } // destination is AccountID32 address function SendForeignTokenToAddress32( bytes32 tokenID, ParaID paraID, bytes32 recipient, uint128 xcmFee, uint128 destinationXcmFee, uint128 amount ) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x02), tokenID, bytes1(0x01), ScaleCodec.encodeU32(uint32(ParaID.unwrap(paraID))), recipient, ScaleCodec.encodeU128(destinationXcmFee), ScaleCodec.encodeU128(amount), ScaleCodec.encodeU128(xcmFee) ); } // destination is AccountID20 address function SendForeignTokenToAddress20( bytes32 tokenID, ParaID paraID, bytes20 recipient, uint128 xcmFee, uint128 destinationXcmFee, uint128 amount ) internal view returns (bytes memory) { return bytes.concat( bytes1(0x00), ScaleCodec.encodeU64(uint64(block.chainid)), bytes1(0x02), tokenID, bytes1(0x02), ScaleCodec.encodeU32(uint32(ParaID.unwrap(paraID))), recipient, ScaleCodec.encodeU128(destinationXcmFee), ScaleCodec.encodeU128(amount), ScaleCodec.encodeU128(xcmFee) ); } }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 Axelar Network // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { error InvalidAccount(); error InsufficientBalance(address sender, uint256 balance, uint256 needed); error InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {OperatingMode, InboundMessage, ParaID, ChannelID, MultiAddress} from "../Types.sol"; import {Verification} from "../Verification.sol"; import {UD60x18} from "prb/math/src/UD60x18.sol"; interface IGateway { /** * Events */ // Emitted when inbound message has been dispatched event InboundMessageDispatched(ChannelID indexed channelID, uint64 nonce, bytes32 indexed messageID, bool success); // Emitted when an outbound message has been accepted for delivery to a Polkadot parachain event OutboundMessageAccepted(ChannelID indexed channelID, uint64 nonce, bytes32 indexed messageID, bytes payload); // Emitted when an agent has been created for a consensus system on Polkadot event AgentCreated(bytes32 agentID, address agent); // Emitted when a channel has been created event ChannelCreated(ChannelID indexed channelID); // Emitted when a channel has been updated event ChannelUpdated(ChannelID indexed channelID); // Emitted when the operating mode is changed event OperatingModeChanged(OperatingMode mode); // Emitted when pricing params updated event PricingParametersChanged(); // Emitted when funds are withdrawn from an agent event AgentFundsWithdrawn(bytes32 indexed agentID, address indexed recipient, uint256 amount); // Emitted when foreign token from polkadot registed event ForeignTokenRegistered(bytes32 indexed tokenID, address token); /** * Getters */ function operatingMode() external view returns (OperatingMode); function channelOperatingModeOf(ChannelID channelID) external view returns (OperatingMode); function channelNoncesOf(ChannelID channelID) external view returns (uint64, uint64); function agentOf(bytes32 agentID) external view returns (address); function pricingParameters() external view returns (UD60x18, uint128); function implementation() external view returns (address); /** * Messaging */ // Submit a message from a Polkadot network function submitV1( InboundMessage calldata message, bytes32[] calldata leafProof, Verification.Proof calldata headerProof ) external; /** * Token Transfers */ // @dev Emitted when the fees updated event TokenTransferFeesChanged(); /// @dev Emitted once the funds are locked and an outbound message is successfully queued. event TokenSent( address indexed token, address indexed sender, ParaID indexed destinationChain, MultiAddress destinationAddress, uint128 amount ); /// @dev Emitted when a command is sent to register a new wrapped token on AssetHub event TokenRegistrationSent(address token); /// @dev Check whether a token is registered function isTokenRegistered(address token) external view returns (bool); /// @dev Get token id of an ERC20 contract address. function queryForeignTokenID(address token) external view returns (bytes32); /// @dev Quote a fee in Ether for registering a token, covering /// 1. Delivery costs to BridgeHub /// 2. XCM Execution costs on AssetHub function quoteRegisterTokenFee() external view returns (uint256); /// @dev Register an ERC20 token and create a wrapped derivative on AssetHub in the `ForeignAssets` pallet. function registerToken(address token) external payable; /// @dev Quote a fee in Ether for sending a token /// 1. Delivery costs to BridgeHub /// 2. XCM execution costs on destinationChain function quoteSendTokenFee(address token, ParaID destinationChain, uint128 destinationFee) external view returns (uint256); /// @dev Send ERC20 tokens to parachain `destinationChain` and deposit into account `destinationAddress` function sendToken( address token, ParaID destinationChain, MultiAddress calldata destinationAddress, uint128 destinationFee, uint128 amount ) external payable; }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 Axelar Network // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {IERC20} from "./interfaces/IERC20.sol"; import {IERC20Permit} from "./interfaces/IERC20Permit.sol"; import {TokenLib} from "./TokenLib.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * This supply mechanism has been added in {ERC20Permit-mint}. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is conventional and does * not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to these events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract Token is IERC20, IERC20Permit { using TokenLib for TokenLib.Token; address public immutable GATEWAY; bytes32 public immutable DOMAIN_SEPARATOR; uint8 public immutable decimals; string public name; string public symbol; TokenLib.Token token; error Unauthorized(); /** * @dev Sets the values for {name}, {symbol}, and {decimals}. */ constructor(string memory _name, string memory _symbol, uint8 _decimals) { name = _name; symbol = _symbol; decimals = _decimals; GATEWAY = msg.sender; DOMAIN_SEPARATOR = keccak256( abi.encode( TokenLib.DOMAIN_TYPE_SIGNATURE_HASH, keccak256(bytes(_name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } modifier onlyGateway() { if (msg.sender != GATEWAY) { revert Unauthorized(); } _; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. Can only be called by the owner. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function mint(address account, uint256 amount) external onlyGateway { token.mint(account, amount); } /** * @dev Destroys `amount` tokens from the account. */ function burn(address account, uint256 amount) external onlyGateway { token.burn(account, amount); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { return token.transfer(msg.sender, recipient, amount); } /** * @dev See {IERC20-approve}. * * NOTE: Prefer the {increaseAllowance} and {decreaseAllowance} methods, as * they aren't vulnerable to the frontrunning attack described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { return token.approve(msg.sender, spender, amount); } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { return token.transferFrom(sender, recipient, amount); } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { return token.increaseAllowance(spender, addedValue); } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { return token.decreaseAllowance(spender, subtractedValue); } function permit(address issuer, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { token.permit(DOMAIN_SEPARATOR, issuer, spender, value, deadline, v, r, s); } function balanceOf(address account) external view returns (uint256) { return token.balance[account]; } function nonces(address account) external view returns (uint256) { return token.nonces[account]; } function totalSupply() external view returns (uint256) { return token.totalSupply; } function allowance(address owner, address spender) external view returns (uint256) { return token.allowance[owner][spender]; } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; using {isIndex, asIndex, isAddress32, asAddress32, isAddress20, asAddress20} for MultiAddress global; /// @dev An address for an on-chain account struct MultiAddress { Kind kind; bytes data; } enum Kind { Index, Address32, Address20 } function isIndex(MultiAddress calldata multiAddress) pure returns (bool) { return multiAddress.kind == Kind.Index; } function asIndex(MultiAddress calldata multiAddress) pure returns (uint32) { return abi.decode(multiAddress.data, (uint32)); } function isAddress32(MultiAddress calldata multiAddress) pure returns (bool) { return multiAddress.kind == Kind.Address32; } function asAddress32(MultiAddress calldata multiAddress) pure returns (bytes32) { return bytes32(multiAddress.data); } function isAddress20(MultiAddress calldata multiAddress) pure returns (bool) { return multiAddress.kind == Kind.Address20; } function asAddress20(MultiAddress calldata multiAddress) pure returns (bytes20) { return bytes20(multiAddress.data); } function multiAddressFromUint32(uint32 id) pure returns (MultiAddress memory) { return MultiAddress({kind: Kind.Index, data: abi.encode(id)}); } function multiAddressFromBytes32(bytes32 id) pure returns (MultiAddress memory) { return MultiAddress({kind: Kind.Address32, data: bytes.concat(id)}); } function multiAddressFromBytes20(bytes20 id) pure returns (MultiAddress memory) { return MultiAddress({kind: Kind.Address20, data: bytes.concat(id)}); }
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(int256(uMAX_SD1x18))) {
revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(uint64(xUint)));
}
/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_UD2x18`.
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uMAX_UD2x18) {
revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(xUint));
}
/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_SD59x18`.
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > uint256(uMAX_SD59x18)) {
revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
}
result = SD59x18.wrap(int256(xUint));
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT128`.
function intoUint128(UD60x18 x) pure returns (uint128 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT128) {
revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
}
result = uint128(xUint);
}
/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(UD60x18 x) pure returns (uint40 result) {
uint256 xUint = UD60x18.unwrap(x);
if (xUint > MAX_UINT40) {
revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}
/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x);
}
/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);
/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);
/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);
/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);
/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);
/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);
/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);
/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Converts a UD60x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The UD60x18 number to convert.
/// @return result The same number in basic integer form.
function convert(UD60x18 x) pure returns (uint256 result) {
result = UD60x18.unwrap(x) / uUNIT;
}
/// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UD60x18 / UNIT`.
///
/// @param x The basic integer to convert.
/// @param result The same number converted to UD60x18.
function convert(uint256 x) pure returns (UD60x18 result) {
if (x > uMAX_UD60x18 / uUNIT) {
revert PRBMath_UD60x18_Convert_Overflow(x);
}
unchecked {
result = UD60x18.wrap(x * uUNIT);
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD60x18 } from "./ValueType.sol";
/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);
/// @notice Thrown when taking the logarithm of a number less than 1.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);
/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
// This wouldn't work if x could be negative.
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_UD60x18,
uMAX_WHOLE_UD60x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
//
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
unchecked {
result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to `MAX_WHOLE_UD60x18`.
///
/// @param x The UD60x18 number to ceil.
/// @param result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint > uMAX_WHOLE_UD60x18) {
revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
}
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `UNIT - remainder`.
let delta := sub(uUNIT, remainder)
// Equivalent to `x + remainder > 0 ? delta : 0`.
result := add(x, mul(delta, gt(remainder, 0)))
}
}
/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @param result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x must be less than 133_084258667509499441.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xUint > uEXP_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
uint256 doubleUnitProduct = xUint * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x must be less than 192e18.
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xUint > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
result = wrap(Common.exp2(x_192x64));
}
/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @param result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
// Equivalent to `x % UNIT`.
let remainder := mod(x, uUNIT)
// Equivalent to `x - remainder > 0 ? remainder : 0)`.
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @param result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
assembly ("memory-safe") {
result := mod(x, uUNIT)
}
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
if (xUint == 0 || yUint == 0) {
return ZERO;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xyUint = xUint * yUint;
if (xyUint / xUint != yUint) {
revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
result = wrap(Common.sqrt(xyUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
unchecked {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~196_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
default { result := uMAX_UD60x18 }
}
if (result.unwrap() == uMAX_UD60x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x must be greater than zero.
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
if (xUint < uUNIT) {
revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
}
unchecked {
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(xUint / uUNIT);
// This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n
// n is at most 255 and UNIT is 1e18.
uint256 resultUint = n * uUNIT;
// Calculate $y = x * 2^{-n}$.
uint256 y = xUint >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultUint);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
uint256 DOUBLE_UNIT = 2e18;
for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultUint += delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
result = wrap(resultUint);
}
}
/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}
/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
uint256 yUint = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xUint == 0) {
return yUint == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xUint == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yUint == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yUint == uUNIT) {
return x;
}
// If x is greater than `UNIT`, use the standard formula.
if (xUint > uUNIT) {
result = exp2(mul(log2(x), y));
}
// Conversely, if x is less than `UNIT`, use the equivalent formula.
else {
UD60x18 i = wrap(uUNIT_SQUARED / xUint);
UD60x18 w = exp2(mul(log2(i), y));
result = wrap(uUNIT_SQUARED / w.unwrap());
}
}
/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
// Calculate the first iteration of the loop in advance.
uint256 xUint = x.unwrap();
uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
for (y >>= 1; y > 0; y >>= 1) {
xUint = Common.mulDiv18(xUint, xUint);
// Equivalent to `y % 2 == 1`.
if (y & 1 > 0) {
resultUint = Common.mulDiv18(resultUint, xUint);
}
}
result = wrap(resultUint);
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must be less than `MAX_UD60x18 / UNIT`.
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = x.unwrap();
unchecked {
if (xUint > uMAX_UD60x18 / uUNIT) {
revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
}
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
// In this case, the two numbers are both the square root.
result = wrap(Common.sqrt(xUint * uUNIT));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD1x18,
Casting.intoUD2x18,
Casting.intoSD59x18,
Casting.intoUint128,
Casting.intoUint256,
Casting.intoUint40,
Casting.unwrap
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.ln,
Math.log10,
Math.log2,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.xor
} for UD60x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.or as |,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.sub as -,
Helpers.xor as ^
} for UD60x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
/// @dev The original console.sol uses `int` and `uint` for computing function selectors, but it should
/// use `int256` and `uint256`. This modified version fixes that. This version is recommended
/// over `console.sol` if you don't need compatibility with Hardhat as the logs will show up in
/// forge stack traces. If you do need compatibility with Hardhat, you must use `console.sol`.
/// Reference: https://github.com/NomicFoundation/hardhat/issues/2178
library console2 {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _castLogPayloadViewToPure(
function(bytes memory) internal view fnIn
) internal pure returns (function(bytes memory) internal pure fnOut) {
assembly {
fnOut := fnIn
}
}
function _sendLogPayload(bytes memory payload) internal pure {
_castLogPayloadViewToPure(_sendLogPayloadView)(payload);
}
function _sendLogPayloadView(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
/// @solidity memory-safe-assembly
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal pure {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
}
function logUint(uint256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
}
function logString(string memory p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
}
function log(int256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
}
function log(string memory p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint256 p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1));
}
function log(uint256 p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1));
}
function log(uint256 p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1));
}
function log(uint256 p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1));
}
function log(string memory p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1));
}
function log(string memory p0, int256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1));
}
function log(string memory p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1));
}
function log(bool p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1));
}
function log(address p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint256 p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2));
}
function log(uint256 p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2));
}
function log(uint256 p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2));
}
function log(uint256 p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2));
}
function log(uint256 p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2));
}
function log(uint256 p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2));
}
function log(uint256 p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2));
}
function log(uint256 p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2));
}
function log(uint256 p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2));
}
function log(bool p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2));
}
function log(bool p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2));
}
function log(bool p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2));
}
function log(address p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2));
}
function log(address p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2));
}
function log(address p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}//SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>
pragma solidity 0.8.25;
import {ScaleCodec} from "../utils/ScaleCodec.sol";
import {ParaID} from "../Types.sol";
library OSubstrateTypes {
enum Message {
V0
}
enum OutboundCommandV1 {
ReceiveValidators
}
function EncodedOperatorsData(bytes32[] calldata operatorsKeys, uint32 operatorsCount, uint48 epoch)
internal
pure
returns (bytes memory)
{
bytes memory operatorsFlattened = new bytes(operatorsCount * 32);
for (uint32 i = 0; i < operatorsCount; i++) {
for (uint32 j = 0; j < 32; j++) {
operatorsFlattened[i * 32 + j] = operatorsKeys[i][j];
}
}
return bytes.concat(
bytes4(0x70150038),
bytes1(uint8(Message.V0)),
bytes1(uint8(OutboundCommandV1.ReceiveValidators)),
ScaleCodec.encodeCompactU32(operatorsCount),
operatorsFlattened,
ScaleCodec.encodeU64(uint64(epoch))
);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {Bits} from "./Bits.sol"; library Bitfield { using Bits for uint256; /** * @dev Constants used to efficiently calculate the hamming weight of a bitfield. See * https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation for an explanation of those constants. */ uint256 internal constant M1 = 0x5555555555555555555555555555555555555555555555555555555555555555; uint256 internal constant M2 = 0x3333333333333333333333333333333333333333333333333333333333333333; uint256 internal constant M4 = 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f; uint256 internal constant M8 = 0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff; uint256 internal constant M16 = 0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff; uint256 internal constant M32 = 0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff; uint256 internal constant M64 = 0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff; uint256 internal constant M128 = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; uint256 internal constant ONE = uint256(1); /** * @notice Core subsampling algorithm. Draws a random number, derives an index in the bitfield, and sets the bit if it is in the `prior` and not * yet set. Repeats that `n` times. * @param seed Source of randomness for selecting validator signatures. * @param prior Bitfield indicating which validators claim to have signed the commitment. * @param n Number of unique bits in prior that must be set in the result. Must be <= number of set bits in `prior`. * @param length Length of the bitfield prior to draw bits from. Must be <= prior.length * 256. */ function subsample(uint256 seed, uint256[] memory prior, uint256 n, uint256 length) internal pure returns (uint256[] memory bitfield) { bitfield = new uint256[](prior.length); uint256 found = 0; for (uint256 i = 0; found < n;) { uint256 index = makeIndex(seed, i, length); // require randomly selected bit to be set in prior and not yet set in bitfield if (!isSet(prior, index) || isSet(bitfield, index)) { unchecked { i++; } continue; } set(bitfield, index); unchecked { found++; i++; } } return bitfield; } /** * @dev Helper to create a bitfield. */ function createBitfield(uint256[] calldata bitsToSet, uint256 length) internal pure returns (uint256[] memory bitfield) { // Calculate length of uint256 array based on rounding up to number of uint256 needed uint256 arrayLength = (length + 255) / 256; bitfield = new uint256[](arrayLength); for (uint256 i = 0; i < bitsToSet.length; i++) { set(bitfield, bitsToSet[i]); } return bitfield; } /** * @notice Calculates the number of set bits by using the hamming weight of the bitfield. * The algorithm below is implemented after https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation. * Further improvements are possible, see the article above. */ function countSetBits(uint256[] memory self) internal pure returns (uint256) { unchecked { uint256 count = 0; for (uint256 i = 0; i < self.length; i++) { uint256 x = self[i]; x = (x & M1) + ((x >> 1) & M1); //put count of each 2 bits into those 2 bits x = (x & M2) + ((x >> 2) & M2); //put count of each 4 bits into those 4 bits x = (x & M4) + ((x >> 4) & M4); //put count of each 8 bits into those 8 bits x = (x & M8) + ((x >> 8) & M8); //put count of each 16 bits into those 16 bits x = (x & M16) + ((x >> 16) & M16); //put count of each 32 bits into those 32 bits x = (x & M32) + ((x >> 32) & M32); //put count of each 64 bits into those 64 bits x = (x & M64) + ((x >> 64) & M64); //put count of each 128 bits into those 128 bits x = (x & M128) + ((x >> 128) & M128); //put count of each 256 bits into those 256 bits count += x; } return count; } } function isSet(uint256[] memory self, uint256 index) internal pure returns (bool) { uint256 element = index >> 8; return self[element].bit(uint8(index)) == 1; } function set(uint256[] memory self, uint256 index) internal pure { uint256 element = index >> 8; self[element] = self[element].setBit(uint8(index)); } function unset(uint256[] memory self, uint256 index) internal pure { uint256 element = index >> 8; self[element] = self[element].clearBit(uint8(index)); } function makeIndex(uint256 seed, uint256 iteration, uint256 length) internal pure returns (uint256 index) { assembly { mstore(0x00, seed) mstore(0x20, iteration) index := mod(keccak256(0x00, 0x40), length) } } }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; /** * @title A utility library for 16 bit counters packed in 256 bit array. * @dev The BeefyClient needs to store a count of how many times a validators signature is used. In solidity * a uint16 would take up as much space as a uin256 in storage, making storing counters for 1000 validators * expensive in terms of gas. The BeefyClient only needs 16 bits per counter. This library allows us to pack * 16 uint16 into a single uint256 and save 16x storage. * * Layout of 32 counters (2 uint256) * We store all counts in a single large uint256 array and convert from index from the logical uint16 array * to the physical uint256 array. * * 0 1 2 * uint256[] |-- -- -- -- -- -- -- -- -- -- -- -- YY -- -- --|-- -- -- -- -- -- XX -- -- -- -- -- -- -- -- --| * uint16[] |--|--|--|--|--|--|--|--|--|--|--|--|YY|--|--|--|--|--|--|--|--|--|XX|--|--|--|--|--|--|--|--|--| * 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 * * Logical Index Layout * We use the first 4 * |-------...---------|----| * 256 4 0 * ^index ^bit-index * * In the above table counter YY is at logical index 12 in the uint16 array. It will convert to a physical * index of 0 in the physical uint256 array and then to bit-index of 192 to 207 of that uint256. In the * above table counter XX is at logical index 22. It will convert to a physical index of 1 in the array and * then to bit-index 96 to 111 of uint256[1]. */ using {get, set} for Uint16Array global; error IndexOutOfBounds(); /** * @dev stores the backing array and the length. */ struct Uint16Array { uint256[] data; uint256 length; } /** * @dev Creates a new counter which can store at least `length` counters. * @param length The amount of counters. */ function createUint16Array(uint256 length) pure returns (Uint16Array memory) { // create space for `length` elements and round up if needed. uint256 bufferLength = length / 16 + (length % 16 == 0 ? 0 : 1); return Uint16Array({data: new uint256[](bufferLength), length: length}); } /** * @dev Gets the counter at the logical index * @param self The array. * @param index The logical index. */ function get(Uint16Array storage self, uint256 index) view returns (uint16) { if (index >= self.length) { revert IndexOutOfBounds(); } // Right-shift the index by 4. This truncates the first 4 bits (bit-index) leaving us with the index // into the array. uint256 element = index >> 4; // Mask out the first 4 bits of the logical index to give us the bit-index. uint8 inside = uint8(index) & 0x0F; // find the element in the array, shift until its bit index and mask to only take the first 16 bits. return uint16((self.data[element] >> (16 * inside)) & 0xFFFF); } /** * @dev Sets the counter at the logical index. * @param self The array. * @param index The logical index of the counter in the array. * @param value The value to set the counter to. */ function set(Uint16Array storage self, uint256 index, uint16 value) { if (index >= self.length) { revert IndexOutOfBounds(); } // Right-shift the index by 4. This truncates the first 4 bits (bit-index) leaving us with the index // into the array. uint256 element = index >> 4; // Mask out the first 4 bytes of the logical index to give us the bit-index. uint8 inside = uint8(index) & 0x0F; // Create a zero mask which will clear the existing value at the bit-index. uint256 zero = ~(uint256(0xFFFF) << (16 * inside)); // Shift the value to the bit index. uint256 shiftedValue = uint256(value) << (16 * inside); // Take the element, apply the zero mask to clear the existing value, and then apply the shifted value with bitwise or. self.data[element] = self.data[element] & zero | shiftedValue; }
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; library MMRProof { error ProofSizeExceeded(); uint256 internal constant MAXIMUM_PROOF_SIZE = 256; /** * @dev Verify inclusion of a leaf in an MMR * @param root MMR root hash * @param leafHash leaf hash * @param proof an array of hashes * @param proofOrder a bitfield describing the order of each item (left vs right) */ function verifyLeafProof(bytes32 root, bytes32 leafHash, bytes32[] calldata proof, uint256 proofOrder) internal pure returns (bool) { // Size of the proof is bounded, since `proofOrder` can only contain `MAXIMUM_PROOF_SIZE` orderings. if (proof.length > MAXIMUM_PROOF_SIZE) { revert ProofSizeExceeded(); } bytes32 acc = leafHash; for (uint256 i = 0; i < proof.length; i++) { acc = hashPairs(acc, proof[i], (proofOrder >> i) & 1); } return root == acc; } function hashPairs(bytes32 x, bytes32 y, uint256 order) internal pure returns (bytes32 value) { assembly { switch order case 0 { mstore(0x00, x) mstore(0x20, y) } default { mstore(0x00, y) mstore(0x20, x) } value := keccak256(0x0, 0x40) } } }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 Axelar Network // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; interface IERC20Permit { error PermitExpired(); error InvalidS(); error InvalidV(); error InvalidSignature(); function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address account) external view returns (uint256); function permit(address issuer, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; }
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2023 Axelar Network // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> pragma solidity 0.8.25; import {IERC20} from "./interfaces/IERC20.sol"; import {IERC20Permit} from "./interfaces/IERC20Permit.sol"; library TokenLib { // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)') bytes32 internal constant DOMAIN_TYPE_SIGNATURE_HASH = bytes32(0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f); // keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)') bytes32 internal constant PERMIT_SIGNATURE_HASH = bytes32(0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9); string internal constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; struct Token { mapping(address account => uint256) balance; mapping(address account => mapping(address spender => uint256)) allowance; mapping(address token => uint256) nonces; uint256 totalSupply; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(Token storage token, address sender, address recipient, uint256 amount) external returns (bool) { _transfer(token, sender, recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function mint(Token storage token, address account, uint256 amount) external { if (account == address(0)) { revert IERC20.InvalidAccount(); } _update(token, address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function burn(Token storage token, address account, uint256 amount) external { if (account == address(0)) { revert IERC20.InvalidAccount(); } _update(token, account, address(0), amount); } /** * @dev See {IERC20-approve}. * * NOTE: Prefer the {increaseAllowance} and {decreaseAllowance} methods, as * they aren't vulnerable to the frontrunning attack described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(Token storage token, address owner, address spender, uint256 amount) external returns (bool) { _approve(token, owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(Token storage token, address sender, address recipient, uint256 amount) external returns (bool) { uint256 _allowance = token.allowance[sender][msg.sender]; if (_allowance != type(uint256).max) { if (_allowance < amount) { revert IERC20.InsufficientAllowance(msg.sender, _allowance, amount); } unchecked { _approve(token, sender, msg.sender, _allowance - amount); } } _transfer(token, sender, recipient, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(Token storage token, address spender, uint256 addedValue) external returns (bool) { uint256 _allowance = token.allowance[msg.sender][spender]; if (_allowance != type(uint256).max) { _approve(token, msg.sender, spender, _allowance + addedValue); } return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(Token storage token, address spender, uint256 subtractedValue) external returns (bool) { uint256 _allowance = token.allowance[msg.sender][spender]; if (_allowance != type(uint256).max) { if (_allowance < subtractedValue) { revert IERC20.InsufficientAllowance(msg.sender, _allowance, subtractedValue); } unchecked { _approve(token, msg.sender, spender, _allowance - subtractedValue); } } return true; } function permit( Token storage token, bytes32 domainSeparator, address issuer, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { if (block.timestamp > deadline) revert IERC20Permit.PermitExpired(); if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert IERC20Permit.InvalidS(); } if (v != 27 && v != 28) revert IERC20Permit.InvalidV(); bytes32 digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, domainSeparator, keccak256(abi.encode(PERMIT_SIGNATURE_HASH, issuer, spender, value, token.nonces[issuer]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); if (recoveredAddress != issuer) revert IERC20Permit.InvalidSignature(); // _approve will revert if issuer is address(0x0) _approve(token, issuer, spender, value); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(Token storage token, address sender, address recipient, uint256 amount) internal { if (sender == address(0) || recipient == address(0)) { revert IERC20.InvalidAccount(); } _update(token, sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(Token storage token, address owner, address spender, uint256 amount) internal { if (owner == address(0) || spender == address(0)) { revert IERC20.InvalidAccount(); } token.allowance[owner][spender] = amount; emit IERC20.Approval(owner, spender, amount); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(Token storage token, address from, address to, uint256 value) internal { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows token.totalSupply += value; } else { uint256 fromBalance = token.balance[from]; if (fromBalance < value) { revert IERC20.InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. token.balance[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. token.totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. token.balance[to] += value; } } emit IERC20.Transfer(from, to, value); } }
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
// Common.sol
//
// Common mathematical functions needed by both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();
/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
/*//////////////////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;
/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;
/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;
/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;
/*//////////////////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
//
// 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
// 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
// a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
// we know that `x & 0xFF` is also 1.
if (x & 0xFF00000000000000 > 0) {
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
}
if (x & 0xFF000000000000 > 0) {
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
}
if (x & 0xFF0000000000 > 0) {
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
}
if (x & 0xFF00000000 > 0) {
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
}
if (x & 0xFF000000 > 0) {
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
}
if (x & 0xFF0000 > 0) {
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
}
if (x & 0xFF00 > 0) {
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
}
if (x & 0xFF > 0) {
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
}
// In the code snippet below, two operations are executed simultaneously:
//
// 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
// accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
// 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
//
// The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
// integer part, $2^n$.
result *= UNIT;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
/// x >>= 128;
/// result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
// 2^128
assembly ("memory-safe") {
let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^64
assembly ("memory-safe") {
let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^32
assembly ("memory-safe") {
let factor := shl(5, gt(x, 0xFFFFFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^16
assembly ("memory-safe") {
let factor := shl(4, gt(x, 0xFFFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^8
assembly ("memory-safe") {
let factor := shl(3, gt(x, 0xFF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^4
assembly ("memory-safe") {
let factor := shl(2, gt(x, 0xF))
x := shr(factor, x)
result := or(result, factor)
}
// 2^2
assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
// 2^1
// No need to shift x any more.
assembly ("memory-safe") {
let factor := gt(x, 0x1)
result := or(result, factor)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
return prod0 / denominator;
}
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath_MulDiv_Overflow(x, y, denominator);
}
////////////////////////////////////////////////////////////////////////////
// 512 by 256 division
////////////////////////////////////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using the mulmod Yul instruction.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512-bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
// Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
// because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
// For more detail, see https://cs.stackexchange.com/q/138556/92363.
uint256 lpotdod = denominator & (~denominator + 1);
uint256 flippedLpotdod;
assembly ("memory-safe") {
// Factor powers of two out of denominator.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
// `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
// However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * flippedLpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
}
}
/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
/// x * y = MAX\_UINT256 * UNIT \\
/// (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
return prod0 / UNIT;
}
}
if (prod1 >= UNIT) {
revert PRBMath_MulDiv18_Overflow(x, y);
}
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(x, y, UNIT)
result :=
mul(
or(
div(sub(prod0, remainder), UNIT_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
),
UNIT_INVERSE
)
}
}
/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath_MulDivSigned_InputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 xAbs;
uint256 yAbs;
uint256 dAbs;
unchecked {
xAbs = x < 0 ? uint256(-x) : uint256(x);
yAbs = y < 0 ? uint256(-y) : uint256(y);
dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of x*y÷denominator. The result must fit in int256.
uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
if (resultAbs > uint256(type(int256).max)) {
revert PRBMath_MulDivSigned_Overflow(x, y);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly ("memory-safe") {
// "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
// If there are, the result should be negative. Otherwise, it should be positive.
unchecked {
result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
//
// We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
//
// $$
// msb(x) <= x <= 2*msb(x)$
// $$
//
// We write $msb(x)$ as $2^k$, and we get:
//
// $$
// k = log_2(x)
// $$
//
// Thus, we can write the initial inequality as:
//
// $$
// 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
// sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
// 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
// $$
//
// Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 2 ** 128) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 2 ** 64) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 2 ** 32) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 2 ** 16) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 2 ** 8) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 2 ** 4) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 2 ** 2) {
result <<= 1;
}
// At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
// most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision
// doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of
// precision into the expected uint128 result.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
// If x is not a perfect square, round the result toward zero.
uint256 roundedResult = x / result;
if (result >= roundedResult) {
result = roundedResult;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);
/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);
/// @dev The maximum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);
/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int256 constant uUNIT = 1e18;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD59x18,
Casting.intoUD2x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for SD1x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
// NOTICE: the "u" prefix stands for "unwrapped".
/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);
/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);
/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);
/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);
/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);
/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);
/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);
/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);
/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);
/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);
/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);
/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);
/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;
/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoInt256,
Casting.intoSD1x18,
Casting.intoUD2x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Math.abs,
Math.avg,
Math.ceil,
Math.div,
Math.exp,
Math.exp2,
Math.floor,
Math.frac,
Math.gm,
Math.inv,
Math.log10,
Math.log2,
Math.ln,
Math.mul,
Math.pow,
Math.powu,
Math.sqrt
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
using {
Helpers.add,
Helpers.and,
Helpers.eq,
Helpers.gt,
Helpers.gte,
Helpers.isZero,
Helpers.lshift,
Helpers.lt,
Helpers.lte,
Helpers.mod,
Helpers.neq,
Helpers.not,
Helpers.or,
Helpers.rshift,
Helpers.sub,
Helpers.uncheckedAdd,
Helpers.uncheckedSub,
Helpers.uncheckedUnary,
Helpers.xor
} for SD59x18 global;
/*//////////////////////////////////////////////////////////////////////////
OPERATORS
//////////////////////////////////////////////////////////////////////////*/
// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
Helpers.add as +,
Helpers.and2 as &,
Math.div as /,
Helpers.eq as ==,
Helpers.gt as >,
Helpers.gte as >=,
Helpers.lt as <,
Helpers.lte as <=,
Helpers.mod as %,
Math.mul as *,
Helpers.neq as !=,
Helpers.not as ~,
Helpers.or as |,
Helpers.sub as -,
Helpers.unary as -,
Helpers.xor as ^
} for SD59x18 global;// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);
/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);
/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);
/// @dev The unit number, which gives the decimal precision of UD2x18.
uint256 constant uUNIT = 1e18;
UD2x18 constant UNIT = UD2x18.wrap(1e18);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Casting.sol" as Casting;
/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;
/*//////////////////////////////////////////////////////////////////////////
CASTING
//////////////////////////////////////////////////////////////////////////*/
using {
Casting.intoSD1x18,
Casting.intoSD59x18,
Casting.intoUD60x18,
Casting.intoUint256,
Casting.intoUint128,
Casting.intoUint40,
Casting.unwrap
} for UD2x18 global;// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: 2023 Snowfork <[email protected]> // Code from https://github.com/ethereum/solidity-examples pragma solidity 0.8.25; library Bits { uint256 internal constant ONE = uint256(1); uint256 internal constant ONES = type(uint256).max; // Sets the bit at the given 'index' in 'self' to '1'. // Returns the modified value. function setBit(uint256 self, uint8 index) internal pure returns (uint256) { return self | (ONE << index); } // Sets the bit at the given 'index' in 'self' to '0'. // Returns the modified value. function clearBit(uint256 self, uint8 index) internal pure returns (uint256) { return self & ~(ONE << index); } // Sets the bit at the given 'index' in 'self' to: // '1' - if the bit is '0' // '0' - if the bit is '1' // Returns the modified value. function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ (ONE << index); } // Get the value of the bit at the given 'index' in 'self'. function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8((self >> index) & 1); } // Check if the bit at the given 'index' in 'self' is set. // Returns: // 'true' - if the value of the bit is '1' // 'false' - if the value of the bit is '0' function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return (self >> index) & 1 == 1; } // Checks if the bit at the given 'index' in 'self' is equal to the corresponding // bit in 'other'. // Returns: // 'true' - if both bits are '0' or both bits are '1' // 'false' - otherwise function bitEqual(uint256 self, uint256 other, uint8 index) internal pure returns (bool) { return ((self ^ other) >> index) & 1 == 0; } // Get the bitwise NOT of the bit at the given 'index' in 'self'. function bitNot(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(1 - ((self >> index) & 1)); } // Computes the bitwise AND of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitAnd(uint256 self, uint256 other, uint8 index) internal pure returns (uint8) { return uint8(((self & other) >> index) & 1); } // Computes the bitwise OR of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitOr(uint256 self, uint256 other, uint8 index) internal pure returns (uint8) { return uint8(((self | other) >> index) & 1); } // Computes the bitwise XOR of the bit at the given 'index' in 'self', and the // corresponding bit in 'other', and returns the value. function bitXor(uint256 self, uint256 other, uint8 index) internal pure returns (uint8) { return uint8(((self ^ other) >> index) & 1); } // Gets 'numBits' consecutive bits from 'self', starting from the bit at 'startIndex'. // Returns the bits as a 'uint'. // Requires that: // - '0 < numBits <= 256' // - 'startIndex < 256' // - 'numBits + startIndex <= 256' function bits(uint256 self, uint8 startIndex, uint16 numBits) internal pure returns (uint256) { require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256, "out of bounds"); return (self >> startIndex) & (ONES >> (256 - numBits)); } // Computes the index of the highest bit set in 'self'. // Returns the highest bit set as an 'uint8'. // Requires that 'self != 0'. function highestBitSet(uint256 self) internal pure returns (uint8 highest) { require(self != 0, "should not be zero"); uint256 val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & (((ONE << i) - 1) << i) != 0) { highest += i; val >>= i; } } } // Computes the index of the lowest bit set in 'self'. // Returns the lowest bit set as an 'uint8'. // Requires that 'self != 0'. function lowestBitSet(uint256 self) internal pure returns (uint8 lowest) { require(self != 0, "should not be zero"); uint256 val = self; for (uint8 i = 128; i >= 1; i >>= 1) { if (val & ((ONE << i) - 1) == 0) { lowest += i; val >>= i; } } } }
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";
/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because the domain of SD1x18 is a subset of SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}
/// @notice Casts an SD1x18 number into UD2x18.
/// - x must be positive.
function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD2x18_Underflow(x);
}
result = UD2x18.wrap(uint64(xInt));
}
/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x must be positive.
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x must be positive.
function intoUint256(SD1x18 x) pure returns (uint256 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
}
result = uint256(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x must be positive.
function intoUint128(SD1x18 x) pure returns (uint128 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
}
result = uint128(uint64(xInt));
}
/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(SD1x18 x) pure returns (uint40 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
}
if (xInt > int64(uint64(Common.MAX_UINT40))) {
revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
}
result = uint40(uint64(xInt));
}
/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}
/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
result = SD1x18.unwrap(x);
}
/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
result = SD1x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x must be greater than or equal to `uMIN_SD1x18`.
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < uMIN_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
}
if (xInt > uMAX_SD1x18) {
revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(xInt));
}
/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `uMAX_UD2x18`.
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
}
if (xInt > int256(uint256(uMAX_UD2x18))) {
revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
}
result = UD2x18.wrap(uint64(uint256(xInt)));
}
/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x must be positive.
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
}
result = UD60x18.wrap(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x must be positive.
function intoUint256(SD59x18 x) pure returns (uint256 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
}
result = uint256(xInt);
}
/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `uMAX_UINT128`.
function intoUint128(SD59x18 x) pure returns (uint128 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT128))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
}
result = uint128(uint256(xInt));
}
/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(SD59x18 x) pure returns (uint40 result) {
int256 xInt = SD59x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
}
if (xInt > int256(uint256(MAX_UINT40))) {
revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
}
result = uint40(uint256(xInt));
}
/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}
/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
result = SD59x18.unwrap(x);
}
/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(x);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() + y.unwrap());
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
return wrap(x.unwrap() & bits);
}
/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
return wrap(x.unwrap() & y.unwrap());
}
/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() == y.unwrap();
}
/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() > y.unwrap();
}
/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() >= y.unwrap();
}
/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
result = x.unwrap() == 0;
}
/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() << bits);
}
/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() < y.unwrap();
}
/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() <= y.unwrap();
}
/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % y.unwrap());
}
/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = x.unwrap() != y.unwrap();
}
/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(~x.unwrap());
}
/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() | y.unwrap());
}
/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
result = wrap(x.unwrap() >> bits);
}
/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() - y.unwrap());
}
/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(-x.unwrap());
}
/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() + y.unwrap());
}
}
/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
unchecked {
result = wrap(x.unwrap() - y.unwrap());
}
}
/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
unchecked {
result = wrap(-x.unwrap());
}
}
/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
result = wrap(x.unwrap() ^ y.unwrap());
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
uEXP_MAX_INPUT,
uEXP2_MAX_INPUT,
uHALF_UNIT,
uLOG2_10,
uLOG2_E,
uMAX_SD59x18,
uMAX_WHOLE_SD59x18,
uMIN_SD59x18,
uMIN_WHOLE_SD59x18,
UNIT,
uUNIT,
uUNIT_SQUARED,
ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";
/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x must be greater than `MIN_SD59x18`.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @param result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
}
result = xInt < 0 ? wrap(-xInt) : x;
}
/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
unchecked {
// This operation is equivalent to `x / 2 + y / 2`, and it can never overflow.
int256 sum = (xInt >> 1) + (yInt >> 1);
if (sum < 0) {
// If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
// rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
assembly ("memory-safe") {
result := add(sum, and(or(xInt, yInt), 1))
}
} else {
// Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
result = wrap(sum + (xInt & yInt & 1));
}
}
}
/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to `MAX_WHOLE_SD59x18`.
///
/// @param x The SD59x18 number to ceil.
/// @param result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt > uMAX_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt > 0) {
resultInt += uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @param result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x must be less than 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
// This check prevents values greater than 192e18 from being passed to {exp2}.
if (xInt > uEXP_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
}
unchecked {
// Inline the fixed-point multiplication to save gas.
int256 doubleUnitProduct = xInt * uLOG2_E;
result = exp2(wrap(doubleUnitProduct / uUNIT));
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x is less than -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x must be less than 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
// The inverse of any number less than this is truncated to zero.
if (xInt < -59_794705707972522261) {
return ZERO;
}
unchecked {
// Inline the fixed-point inversion to save gas.
result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
}
} else {
// Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = uint256((xInt << 64) / uUNIT);
// It is safe to cast the result to int256 due to the checks above.
result = wrap(int256(Common.exp2(x_192x64)));
}
}
}
/// @notice Yields the greatest whole number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be greater than or equal to `MIN_WHOLE_SD59x18`.
///
/// @param x The SD59x18 number to floor.
/// @param result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < uMIN_WHOLE_SD59x18) {
revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
}
int256 remainder = xInt % uUNIT;
if (remainder == 0) {
result = x;
} else {
unchecked {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
int256 resultInt = xInt - remainder;
if (xInt < 0) {
resultInt -= uUNIT;
}
result = wrap(resultInt);
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @param result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(x.unwrap() % uUNIT);
}
/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == 0 || yInt == 0) {
return ZERO;
}
unchecked {
// Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
int256 xyInt = xInt * yInt;
if (xyInt / xInt != yInt) {
revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
}
// The product must not be negative, since complex numbers are not supported.
if (xyInt < 0) {
revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
}
// We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
// during multiplication. See the comments in {Common.sqrt}.
uint256 resultUint = Common.sqrt(uint256(xyInt));
result = wrap(int256(resultUint));
}
}
/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
result = wrap(uUNIT_SQUARED / x.unwrap());
}
/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
// Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
// {log2} can return is ~195_205294292027477728.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}
/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
// Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
// prettier-ignore
assembly ("memory-safe") {
switch x
case 1 { result := mul(uUNIT, sub(0, 18)) }
case 10 { result := mul(uUNIT, sub(1, 18)) }
case 100 { result := mul(uUNIT, sub(2, 18)) }
case 1000 { result := mul(uUNIT, sub(3, 18)) }
case 10000 { result := mul(uUNIT, sub(4, 18)) }
case 100000 { result := mul(uUNIT, sub(5, 18)) }
case 1000000 { result := mul(uUNIT, sub(6, 18)) }
case 10000000 { result := mul(uUNIT, sub(7, 18)) }
case 100000000 { result := mul(uUNIT, sub(8, 18)) }
case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := uUNIT }
case 100000000000000000000 { result := mul(uUNIT, 2) }
case 1000000000000000000000 { result := mul(uUNIT, 3) }
case 10000000000000000000000 { result := mul(uUNIT, 4) }
case 100000000000000000000000 { result := mul(uUNIT, 5) }
case 1000000000000000000000000 { result := mul(uUNIT, 6) }
case 10000000000000000000000000 { result := mul(uUNIT, 7) }
case 100000000000000000000000000 { result := mul(uUNIT, 8) }
case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
default { result := uMAX_SD59x18 }
}
if (result.unwrap() == uMAX_SD59x18) {
unchecked {
// Inline the fixed-point division to save gas.
result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
}
}
}
/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x must be greater than zero.
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt <= 0) {
revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
}
unchecked {
int256 sign;
if (xInt >= uUNIT) {
sign = 1;
} else {
sign = -1;
// Inline the fixed-point inversion to save gas.
xInt = uUNIT_SQUARED / xInt;
}
// Calculate the integer part of the logarithm.
uint256 n = Common.msb(uint256(xInt / uUNIT));
// This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
// because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
int256 resultInt = int256(n) * uUNIT;
// Calculate $y = x * 2^{-n}$.
int256 y = xInt >> n;
// If y is the unit number, the fractional part is zero.
if (y == uUNIT) {
return wrap(resultInt * sign);
}
// Calculate the fractional part via the iterative approximation.
// The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
int256 DOUBLE_UNIT = 2e18;
for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
y = (y * y) / uUNIT;
// Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
if (y >= DOUBLE_UNIT) {
// Add the 2^{-m} factor to the logarithm.
resultInt = resultInt + delta;
// Halve y, which corresponds to z/2 in the Wikipedia article.
y >>= 1;
}
}
resultInt *= sign;
result = wrap(resultInt);
}
}
/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 xAbs;
uint256 yAbs;
unchecked {
xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
}
// Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
}
// Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
// negative, 0 for positive or zero).
bool sameSign = (xInt ^ yInt) > -1;
// If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
unchecked {
result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
}
}
/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
int256 yInt = y.unwrap();
// If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
if (xInt == 0) {
return yInt == 0 ? UNIT : ZERO;
}
// If x is `UNIT`, the result is always `UNIT`.
else if (xInt == uUNIT) {
return UNIT;
}
// If y is zero, the result is always `UNIT`.
if (yInt == 0) {
return UNIT;
}
// If y is `UNIT`, the result is always x.
else if (yInt == uUNIT) {
return x;
}
// Calculate the result using the formula.
result = exp2(mul(log2(x), y));
}
/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
uint256 xAbs = uint256(abs(x).unwrap());
// Calculate the first iteration of the loop in advance.
uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);
// Equivalent to `for(y /= 2; y > 0; y /= 2)`.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = Common.mulDiv18(xAbs, xAbs);
// Equivalent to `y % 2 == 1`.
if (yAux & 1 > 0) {
resultAbs = Common.mulDiv18(resultAbs, xAbs);
}
}
// The result must fit in SD59x18.
if (resultAbs > uint256(uMAX_SD59x18)) {
revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
}
unchecked {
// Is the base negative and the exponent odd? If yes, the result should be negative.
int256 resultInt = int256(resultAbs);
bool isNegative = x.unwrap() < 0 && y & 1 == 1;
if (isNegative) {
resultInt = -resultInt;
}
result = wrap(resultInt);
}
}
/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x cannot be negative, since complex numbers are not supported.
/// - x must be less than `MAX_SD59x18 / UNIT`.
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
int256 xInt = x.unwrap();
if (xInt < 0) {
revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
}
if (xInt > uMAX_SD59x18 / uUNIT) {
revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
}
unchecked {
// Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
// In this case, the two numbers are both the square root.
uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
result = wrap(int256(resultUint));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";
/// @notice Casts a UD2x18 number into SD1x18.
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) {
uint64 xUint = UD2x18.unwrap(x);
if (xUint > uint64(uMAX_SD1x18)) {
revert Errors.PRBMath_UD2x18_IntoSD1x18_Overflow(x);
}
result = SD1x18.wrap(int64(xUint));
}
/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}
/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
result = UD60x18.wrap(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
result = uint128(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
result = uint256(UD2x18.unwrap(x));
}
/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(UD2x18 x) pure returns (uint40 result) {
uint64 xUint = UD2x18.unwrap(x);
if (xUint > uint64(Common.MAX_UINT40)) {
revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
}
result = uint40(xUint);
}
/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}
/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
result = UD2x18.unwrap(x);
}
/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
result = UD2x18.wrap(x);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD1x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD2x18.
error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);
/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);
/// @notice Thrown when trying to cast a SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { SD59x18 } from "./ValueType.sol";
/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();
/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);
/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);
/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);
/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();
/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);
/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);
/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);
/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);
/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);
/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);
/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);
/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();
/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);
/// @notice Thrown when raising a number to a power and hte intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);
/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);
/// @notice Thrown when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;
import { UD2x18 } from "./ValueType.sol";
/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in SD1x18.
error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x);
/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);{
"remappings": [
"canonical-weth/=lib/canonical-weth/contracts/",
"ds-test/=lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"prb/math/=lib/prb-math/",
"@prb/test/=lib/prb-math/lib/prb-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"prb-math/=lib/prb-math/src/",
"prb-test/=lib/prb-math/lib/prb-test/src/"
],
"optimizer": {
"enabled": true,
"runs": 800
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false,
"libraries": {
"src/Assets.sol": {
"Assets": "0xC441915f909b16b8559C326c6582f0bFA8D7976c"
},
"src/TokenLib.sol": {
"TokenLib": "0xf887310A5D1eDeE69c153EEE83287b7B2F2c63d3"
},
"src/Verification.sol": {
"Verification": "0x759701B01b2FA18f8D6031F98480FFB64Ba3f43F"
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"beefyClient","type":"address"},{"internalType":"address","name":"agentExecutor","type":"address"},{"internalType":"ParaID","name":"bridgeHubParaID","type":"uint32"},{"internalType":"bytes32","name":"bridgeHubAgentID","type":"bytes32"},{"internalType":"uint8","name":"foreignTokenDecimals","type":"uint8"},{"internalType":"uint128","name":"maxDestinationFee","type":"uint128"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AgentAlreadyCreated","type":"error"},{"inputs":[],"name":"AgentDoesNotExist","type":"error"},{"inputs":[],"name":"CantSetMiddlewareToSameAddress","type":"error"},{"inputs":[],"name":"CantSetMiddlewareToZeroAddress","type":"error"},{"inputs":[],"name":"ChannelAlreadyCreated","type":"error"},{"inputs":[],"name":"ChannelDoesNotExist","type":"error"},{"inputs":[],"name":"Disabled","type":"error"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"uint256","name":"eraIndex","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"totalPointsToken","type":"uint256"},{"internalType":"uint256","name":"totalTokensInflated","type":"uint256"},{"internalType":"bytes32","name":"rewardsRoot","type":"bytes32"},{"internalType":"bytes","name":"errorBytes","type":"bytes"}],"name":"EUnableToProcessRewardsB","type":"error"},{"inputs":[{"internalType":"uint256","name":"epoch","type":"uint256"},{"internalType":"uint256","name":"eraIndex","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"totalPointsToken","type":"uint256"},{"internalType":"uint256","name":"totalTokensInflated","type":"uint256"},{"internalType":"bytes32","name":"rewardsRoot","type":"bytes32"},{"internalType":"string","name":"errorString","type":"string"}],"name":"EUnableToProcessRewardsS","type":"error"},{"inputs":[],"name":"FeePaymentToLow","type":"error"},{"inputs":[],"name":"InvalidAgentExecutionPayload","type":"error"},{"inputs":[],"name":"InvalidChannelUpdate","type":"error"},{"inputs":[],"name":"InvalidCodeHash","type":"error"},{"inputs":[],"name":"InvalidConstructorParams","type":"error"},{"inputs":[],"name":"InvalidContract","type":"error"},{"inputs":[],"name":"InvalidNonce","type":"error"},{"inputs":[],"name":"InvalidProof","type":"error"},{"inputs":[],"name":"MiddlewareNotSet","type":"error"},{"inputs":[],"name":"NativeTransferFailed","type":"error"},{"inputs":[],"name":"NotEnoughGas","type":"error"},{"inputs":[],"name":"Operators__OperatorsKeysCannotBeEmpty","type":"error"},{"inputs":[],"name":"Operators__OperatorsLengthTooLong","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"name":"PRBMath_MulDiv18_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"PRBMath_UD60x18_Convert_Overflow","type":"error"},{"inputs":[{"internalType":"UD60x18","name":"x","type":"uint256"}],"name":"PRBMath_UD60x18_Exp2_InputTooBig","type":"error"},{"inputs":[{"internalType":"UD60x18","name":"x","type":"uint256"}],"name":"PRBMath_UD60x18_Log_InputTooSmall","type":"error"},{"inputs":[],"name":"TokenNotRegistered","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"agentID","type":"bytes32"},{"indexed":false,"internalType":"address","name":"agent","type":"address"}],"name":"AgentCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"agentID","type":"bytes32"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AgentFundsWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"ChannelID","name":"channelID","type":"bytes32"}],"name":"ChannelCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"ChannelID","name":"channelID","type":"bytes32"}],"name":"ChannelUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"tokenID","type":"bytes32"},{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"ForeignTokenRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"ChannelID","name":"channelID","type":"bytes32"},{"indexed":false,"internalType":"uint64","name":"nonce","type":"uint64"},{"indexed":true,"internalType":"bytes32","name":"messageID","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"success","type":"bool"}],"name":"InboundMessageDispatched","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousMiddleware","type":"address"},{"indexed":true,"internalType":"address","name":"newMiddleware","type":"address"}],"name":"MiddlewareChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"enum Command","name":"command","type":"uint8"}],"name":"NotImplementedCommand","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"enum OperatingMode","name":"mode","type":"uint8"}],"name":"OperatingModeChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"validatorsCount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"payload","type":"bytes"}],"name":"OperatorsDataCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"ChannelID","name":"channelID","type":"bytes32"},{"indexed":false,"internalType":"uint64","name":"nonce","type":"uint64"},{"indexed":true,"internalType":"bytes32","name":"messageID","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"payload","type":"bytes"}],"name":"OutboundMessageAccepted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[],"name":"PricingParametersChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"TokenRegistrationSent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"ParaID","name":"destinationChain","type":"uint32"},{"components":[{"internalType":"enum Kind","name":"kind","type":"uint8"},{"internalType":"bytes","name":"data","type":"bytes"}],"indexed":false,"internalType":"struct MultiAddress","name":"destinationAddress","type":"tuple"},{"indexed":false,"internalType":"uint128","name":"amount","type":"uint128"}],"name":"TokenSent","type":"event"},{"anonymous":false,"inputs":[],"name":"TokenTransferFeesChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"operatorKey","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"slashFranction","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"error","type":"bytes"}],"name":"UnableToProcessIndividualSlashB","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"operatorKey","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"slashFranction","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"epoch","type":"uint256"},{"indexed":false,"internalType":"string","name":"error","type":"string"}],"name":"UnableToProcessIndividualSlashS","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"error","type":"bytes"}],"name":"UnableToProcessRewardsMessageB","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"error","type":"string"}],"name":"UnableToProcessRewardsMessageS","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"error","type":"bytes"}],"name":"UnableToProcessSlashMessageB","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"error","type":"string"}],"name":"UnableToProcessSlashMessageS","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"AGENT_EXECUTOR","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BEEFY_CLIENT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"agentExecute","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"agentID","type":"bytes32"}],"name":"agentOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"ChannelID","name":"channelID","type":"bytes32"}],"name":"channelNoncesOf","outputs":[{"internalType":"uint64","name":"","type":"uint64"},{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"ChannelID","name":"channelID","type":"bytes32"}],"name":"channelOperatingModeOf","outputs":[{"internalType":"enum OperatingMode","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"createAgent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"createChannel","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"isTokenRegistered","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"mintForeignToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operatingMode","outputs":[{"internalType":"enum OperatingMode","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pricingParameters","outputs":[{"internalType":"UD60x18","name":"","type":"uint256"},{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"queryForeignTokenID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"quoteRegisterTokenFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"ParaID","name":"destinationChain","type":"uint32"},{"internalType":"uint128","name":"destinationFee","type":"uint128"}],"name":"quoteSendTokenFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"registerForeignToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"registerToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"reportSlashes","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"s_middleware","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"data","type":"bytes32[]"},{"internalType":"uint48","name":"epoch","type":"uint48"}],"name":"sendOperatorsData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"sendRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"ParaID","name":"destinationChain","type":"uint32"},{"components":[{"internalType":"enum Kind","name":"kind","type":"uint8"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct MultiAddress","name":"destinationAddress","type":"tuple"},{"internalType":"uint128","name":"destinationFee","type":"uint128"},{"internalType":"uint128","name":"amount","type":"uint128"}],"name":"sendToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"middleware","type":"address"}],"name":"setMiddleware","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"setOperatingMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"setPricingParameters","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"setTokenTransferFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"ChannelID","name":"channelID","type":"bytes32"},{"internalType":"uint64","name":"nonce","type":"uint64"},{"internalType":"enum Command","name":"command","type":"uint8"},{"internalType":"bytes","name":"params","type":"bytes"},{"internalType":"uint64","name":"maxDispatchGas","type":"uint64"},{"internalType":"uint256","name":"maxFeePerGas","type":"uint256"},{"internalType":"uint256","name":"reward","type":"uint256"},{"internalType":"bytes32","name":"id","type":"bytes32"}],"internalType":"struct InboundMessage","name":"message","type":"tuple"},{"internalType":"bytes32[]","name":"leafProof","type":"bytes32[]"},{"components":[{"components":[{"internalType":"uint8","name":"version","type":"uint8"},{"internalType":"uint32","name":"parentNumber","type":"uint32"},{"internalType":"bytes32","name":"parentHash","type":"bytes32"},{"internalType":"uint64","name":"nextAuthoritySetID","type":"uint64"},{"internalType":"uint32","name":"nextAuthoritySetLen","type":"uint32"},{"internalType":"bytes32","name":"nextAuthoritySetRoot","type":"bytes32"}],"internalType":"struct Verification.MMRLeafPartial","name":"leafPartial","type":"tuple"},{"internalType":"bytes32[]","name":"leafProof","type":"bytes32[]"},{"internalType":"bytes32","name":"parachainHeadsRoot","type":"bytes32"},{"internalType":"uint256","name":"leafProofOrder","type":"uint256"}],"internalType":"struct Verification.Proof","name":"headerProof","type":"tuple"}],"name":"submitV1","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"tokenID","type":"bytes32"}],"name":"tokenAddressOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"transferNativeFromAgent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"transferNativeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"updateChannel","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgrade","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
0x6101606040526127105f55348015610015575f80fd5b50604051615df1380380615df1833981016040819052610034916100f0565b63ffffffff84161580610045575082155b1561006357604051631510b77f60e01b815260040160405180910390fd5b6001600160a01b0386811660a0528516608052600884811b63ff00ff001662ff00ff9186901c9190911617601081811b91901c1760e01b6001600160e01b03191660e05263ffffffff90931660c0526101009190915260ff16610140526001600160801b0316610120525061017b9050565b80516001600160a01b03811681146100eb575f80fd5b919050565b5f805f805f8060c08789031215610105575f80fd5b61010e876100d5565b955061011c602088016100d5565b9450604087015163ffffffff81168114610134575f80fd5b60608801516080890151919550935060ff81168114610151575f80fd5b60a08801519092506001600160801b038116811461016d575f80fd5b809150509295509295509295565b60805160a05160c05160e051610100516101205161014051615bfe6101f35f395f61351801525f8181611bf80152611eaa01525f818161164f015261169c01525f612f2001525f50505f81816105620152612efe01525f8181610452015281816114f801528181611f79015261341f0152615bfe5ff3fe608060405260043610610229575f3560e01c80635e6dae2611610131578063ae8a4d98116100ac578063c3b8ec8e1161007c578063f2fde38b11610062578063f2fde38b1461072d578063fbebbc2c1461074c578063fe61cc491461076b575f80fd5b8063c3b8ec8e146106ef578063c45578b51461070e575f80fd5b8063ae8a4d981461063c578063afce33c41461065b578063b7d8e1a91461067a578063be8d42c014610699575f80fd5b8063928bc49d116101015780639a870c8b116100e75780639a870c8b146105c25780639acd53ef146105e1578063a8bd41cd14610600575f80fd5b8063928bc49d1461058457806393dbdf1d146105a3575f80fd5b80635e6dae26146104f1578063805ce31d146105105780638257f3d51461053257806390ffc4f914610551575f80fd5b80632a6c3229116101c1578063423e69b611610191578063520548341161017757806352054834146104ab5780635b2e9c4c146104be5780635c60da1b146104dd575f80fd5b8063423e69b614610441578063439fab911461048c575f80fd5b80632a6c32291461038f5780632ab9b512146103ce57806335ede969146103ed57806338004f691461040c575f80fd5b80630c86ea46116101fc5780630c86ea461461030357806317abcf6014610322578063253946451461034157806326aa101f14610360575f80fd5b8063017b73111461022d5780630705f4651461024e57806309824a80146102835780630b61764614610296575b5f80fd5b348015610238575f80fd5b5061024c6102473660046144bd565b61078a565b005b348015610259575f80fd5b5061026d610268366004614528565b610840565b60405161027a9190614553565b60405180910390f35b61024c61029136600461458c565b610856565b3480156102a1575f80fd5b507f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f6547f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f754604080519283526001600160801b0390911660208301520161027a565b34801561030e575f80fd5b5061024c61031d3660046144bd565b6108dd565b34801561032d575f80fd5b5061024c61033c3660046144bd565b610997565b34801561034c575f80fd5b5061024c61035b3660046144bd565b610ac1565b34801561036b575f80fd5b5061037f61037a36600461458c565b610b0a565b604051901515815260200161027a565b34801561039a575f80fd5b506103ae6103a9366004614528565b610b8c565b604080516001600160401b0393841681529290911660208301520161027a565b3480156103d9575f80fd5b5061024c6103e83660046145ee565b610bba565b3480156103f8575f80fd5b5061024c6104073660046144bd565b611434565b348015610417575f80fd5b507e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5460ff1661026d565b34801561044c575f80fd5b506104747f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200161027a565b348015610497575f80fd5b5061024c6104a63660046144bd565b6115a3565b61024c6104b93660046146bd565b611bbd565b3480156104c9575f80fd5b5061024c6104d83660046144bd565b611c6e565b3480156104e8575f80fd5b50610474611d15565b3480156104fc575f80fd5b5061047461050b366004614528565b611d43565b34801561051b575f80fd5b50610524611d4d565b60405190815260200161027a565b34801561053d575f80fd5b5061024c61054c3660046144bd565b611dc0565b34801561055c575f80fd5b506104747f000000000000000000000000000000000000000000000000000000000000000081565b34801561058f575f80fd5b5061052461059e366004614745565b611e70565b3480156105ae575f80fd5b5061024c6105bd3660046144bd565b611f18565b3480156105cd575f80fd5b5061024c6105dc3660046144bd565b612018565b3480156105ec575f80fd5b5061024c6105fb36600461478d565b6120bd565b34801561060b575f80fd5b507fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68546001600160a01b0316610474565b348015610647575f80fd5b5061024c6106563660046144bd565b61214e565b348015610666575f80fd5b5061024c6106753660046144bd565b6121c8565b348015610685575f80fd5b5061024c61069436600461458c565b61229f565b3480156106a4575f80fd5b506105246106b336600461458c565b6001600160a01b03165f9081527f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22e602052604090206001015490565b3480156106fa575f80fd5b5061024c6107093660046144bd565b6123de565b348015610719575f80fd5b5061024c6107283660046144bd565b612508565b348015610738575f80fd5b5061024c61074736600461458c565b6127d4565b348015610757575f80fd5b5061024c6107663660046144bd565b61282b565b348015610776575f80fd5b50610474610785366004614528565b612a5a565b3330146107a9576040516282b42960e81b815260040160405180910390fd5b5f6107b682840184614910565b805160208201516040808401519051631e66650960e11b815260048101939093526001600160a01b039091166024830152604482015290915073c441915f909b16b8559c326c6582f0bfa8d7976c90633cccca12906064015b5f6040518083038186803b158015610825575f80fd5b505af4158015610837573d5f803e3d5ffd5b50505050505050565b5f8061084b83612ace565b5460ff169392505050565b6040516213049560e71b81526001600160a01b03821660048201526108da9073c441915f909b16b8559c326c6582f0bfa8d7976c906309824a80906024015f60405180830381865af41580156108ae573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526108d591908101906149dc565b612b29565b50565b3330146108fc576040516282b42960e81b815260040160405180910390fd5b7f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f65f61092a84840185614a6c565b8051835560208101516001840180546fffffffffffffffffffffffffffffffff19166001600160801b039092169190911790556040808201516002850155519091507f5e3c25378b5946068b94aa2ea10c4c1e215cc975f994322b159ddc9237a973d4905f90a150505050565b3330146109b6576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f6109e384840185614ac0565b90505f6109f38260200151612cc9565b82515f9081526001808601602052604090912090810154919250906001600160a01b031615610a3557604051631f6206e560e01b815260040160405180910390fd5b60408301518154829060ff191660018381811115610a5557610a5561453f565b02179055506001810180546001600160a01b0319166001600160a01b038416179055805470ffffffffffffffffffffffffffffffff001916815582516040517fe7e6b36c9bc4c7817d3879c45d6ce1edd3c61b1966c488f1817697bb0b704525905f90a2505050505050565b333014610ae0576040516282b42960e81b815260040160405180910390fd5b5f610aed82840184614b5a565b9050610b05815f015182602001518360400151612d1c565b505050565b6040516326aa101f60e01b81526001600160a01b03821660048201525f9073c441915f909b16b8559c326c6582f0bfa8d7976c906326aa101f90602401602060405180830381865af4158015610b62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b869190614be2565b92915050565b5f805f610b9884612ace565b546001600160401b036101008204811696600160481b90920416945092505050565b5f5a90505f610bc98635612ace565b8054909150610be79061010090046001600160401b03166001614c0f565b6001600160401b0316610c006040880160208901614c4c565b6001600160401b031614610c2757604051633ab3447f60e11b815260040160405180910390fd5b805461010090046001600160401b0316816001610c4383614c65565b91906101000a8154816001600160401b0302191690836001600160401b03160217905550505f86604051602001610c7a9190614d15565b6040516020818303038152906040528051906020012090505f610cd08787808060200260200160405190810160405280939291908181526020018383602002808284375f92019190915250869250612e8b915050565b9050610cdc8186612ecd565b610cf9576040516309bde33960e01b815260040160405180910390fd5b5f610d0a60a08a0160808b01614c4c565b6001600160401b031690505f5481610d229190614dbe565b5a1015610d4257604051636eb14fc360e11b815260040160405180910390fd5b60015f610d5560608c0160408d01614dd1565b6022811115610d6657610d6661453f565b03610dd557306335ede96983610d7f60608e018e614dea565b6040518463ffffffff1660e01b8152600401610d9c929190614e2c565b5f604051808303815f88803b158015610db3575f80fd5b5087f193505050508015610dc5575060015b610dd057505f61133b565b61133b565b6002610de760608c0160408d01614dd1565b6022811115610df857610df861453f565b03610e11573063c3b8ec8e83610d7f60608e018e614dea565b6003610e2360608c0160408d01614dd1565b6022811115610e3457610e3461453f565b03610e4d57306317abcf6083610d7f60608e018e614dea565b6004610e5f60608c0160408d01614dd1565b6022811115610e7057610e7061453f565b03610e89573063afce33c483610d7f60608e018e614dea565b6005610e9b60608c0160408d01614dd1565b6022811115610eac57610eac61453f565b03610ec55730638257f3d583610d7f60608e018e614dea565b6006610ed760608c0160408d01614dd1565b6022811115610ee857610ee861453f565b03610f015730639a870c8b83610d7f60608e018e614dea565b6001610f1360608c0160408d01614dd1565b6022811115610f2457610f2461453f565b03610f3d5730632539464583610d7f60608e018e614dea565b6007610f4f60608c0160408d01614dd1565b6022811115610f6057610f6061453f565b03610f795730635b2e9c4c83610d7f60608e018e614dea565b6008610f8b60608c0160408d01614dd1565b6022811115610f9c57610f9c61453f565b03610fb55730630c86ea4683610d7f60608e018e614dea565b6009610fc760608c0160408d01614dd1565b6022811115610fd857610fd861453f565b03610ff157306393dbdf1d83610d7f60608e018e614dea565b600a61100360608c0160408d01614dd1565b60228111156110145761101461453f565b0361102d573063ae8a4d9883610d7f60608e018e614dea565b600b61103f60608c0160408d01614dd1565b60228111156110505761105061453f565b03611069573063017b731183610d7f60608e018e614dea565b602261107b60608c0160408d01614dd1565b602281111561108c5761108c61453f565b036111b6573063fbebbc2c836110a560608e018e614dea565b6040518463ffffffff1660e01b81526004016110c2929190614e2c565b5f604051808303815f88803b1580156110d9575f80fd5b5087f1935050505080156110eb575060015b610dd0576110f7614e3f565b806308c379a003611156575061110b614e57565b806111165750611158565b7fa5c3d8fb760908f41c76be7895cad9604026af9199941b8acb89df38129ced96816040516111459190614f0d565b60405180910390a15f91505061133b565b505b3d808015611181576040519150601f19603f3d011682016040523d82523d5f602084013e611186565b606091505b507f6ad5b0077c5d29c0997620effc37071ab1076e5c07e562bf474d2e8af8e67b65816040516111459190614f0d565b60216111c860608c0160408d01614dd1565b60228111156111d9576111d961453f565b036112f2573063c45578b5836111f260608e018e614dea565b6040518463ffffffff1660e01b815260040161120f929190614e2c565b5f604051808303815f88803b158015611226575f80fd5b5087f193505050508015611238575060015b610dd057611244614e3f565b806308c379a0036112925750611258614e57565b806112635750611294565b7f7288d75ae482e895a82170fea3e4b676deaafccd3a4ed2b0458b52eb3e3f9871816040516111459190614f0d565b505b3d8080156112bd576040519150601f19603f3d011682016040523d82523d5f602084013e6112c2565b606091505b507f83299bf4eb6c92af218e82e3d6a849c455fc3d6806a93d99070c999d360f3a2b816040516111459190614f0d565b505f7fbaa1607288f2f457b14d1c481bb0470ad2af897b6f1e438930a75184acf542a861132560608c0160408d01614dd1565b6040516113329190614f1f565b60405180910390a15b5f5a6113479088614f2d565b61134f612f8b565b6113599190614dbe565b90505f61136a3a8d60a00135612fa3565b6113749083614f40565b90505f61139c61138860c08f013584614dbe565b60018a01546001600160a01b031631612fa3565b90506113a6612fb8565b8111156113c65760018801546113c6906001600160a01b03163383612fc5565b8c60e001358d5f01357f617fdb0cb78f01551a192a3673208ec5eb09f20a90acf673c63a0dcb11745a7a8f60200160208101906114039190614c4c565b604080516001600160401b03909216825288151560208301520160405180910390a350505050505050505050505050565b333014611453576040516282b42960e81b815260040160405180910390fd5b5f61146082840184614f57565b90505f61146f825f0151612cc9565b90508160200151515f03611496576040516309e256f760e21b815260040160405180910390fd5b5f8083602001518060200190518101906114b09190614fcc565b90925090505f8280156114c5576114c561453f565b0361159b575f805f838060200190518101906114e1919061501c565b60405163163ace6960e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152808b1660248301528085166044830152831660648201526001600160801b0382166084820152929550909350915073c441915f909b16b8559c326c6582f0bfa8d7976c9063163ace699060a4015f6040518083038186803b158015611581575f80fd5b505af4158015611593573d5f803e3d5ffd5b505050505050505b505050505050565b5f6115cc7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6001600160a01b0316036115f2576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f61161f8484018561505b565b905061162a3361302e565b80518254839060ff1916600183818111156116475761164761453f565b02179055505f7f000000000000000000000000000000000000000000000000000000000000000060405161167a90614471565b908152602001604051809103905ff080158015611699573d5f803e3d5ffd5b507f00000000000000000000000000000000000000000000000000000000000000005f818152600286016020908152604080832080546001600160a01b0319166001600160a01b03871690811790915580845260038901835281842094909455805160808101825283815280830184905280820184905260608101949094526001808452808901909252909120825181549495509293909291839160ff191690838181111561174a5761174a61453f565b0217905550602082810151825460408086015170ffffffffffffffffffffffffffffffff00199092166101006001600160401b039485160267ffffffffffffffff60481b191617600160481b9390921692909202178355606093840151600193840180546001600160a01b0319166001600160a01b0392831617905581516080810183525f808252818501819052818401819052918716958101959095526002815287840190925290208251815491929091839160ff199091169083818111156118165761181661453f565b02179055506020820151815460408085015170ffffffffffffffffffffffffffffffff00199092166101006001600160401b039485160267ffffffffffffffff60481b191617600160481b9390921692909202178255606090920151600190910180546001600160a01b0319166001600160a01b03909216919091179055608083015190515f91906118a790614471565b908152602001604051809103905ff0801580156118c6573d5f803e3d5ffd5b50608084810180515f908152600288016020908152604080832080546001600160a01b0388166001600160a01b03199091168117909155935184845260038b0183528184205580519485018152828552848201839052848101839052606080860194909452928801518351637061726160e01b8184015260e09190911b6001600160e01b0319166024820152835160088183030181526028909101845280519082012082526001808a01909152919020825181549495509293909291839160ff191690838181111561199a5761199a61453f565b02179055506020820151815460408401516001600160401b03908116600160481b0267ffffffffffffffff60481b1991909316610100021670ffffffffffffffffffffffffffffffff001990911617178155606090910151600190910180546001600160a01b039092166001600160a01b03199092169190911790555f611a3e7f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f690565b6040850151815560208501516001820180546fffffffffffffffffffffffffffffffff19166001600160801b03928316179055610100860151600283015560608601517f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22f80546001600160a01b0387166001600160a01b031963ffffffff9094167401000000000000000000000000000000000000000002939093166001600160c01b03199091161791909117905560e08601517f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c2315560a086015160c08701518216600160801b029116177f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c2305590507f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22e5f7f06e511110254c925caa9863541ca318b1a9a0615f0ac1669e771c5d47be3a4bb610120969096015186546001600160a01b0319166001600160a01b03909116179095555050505050505050565b60405163711d829160e01b81525f9073c441915f909b16b8559c326c6582f0bfa8d7976c9063711d829190611c2290899033908a908a908a907f0000000000000000000000000000000000000000000000000000000000000000908b90600401615106565b5f60405180830381865af4158015611c3c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611c6391908101906149dc565b905061159b81612b29565b333014611c8d576040516282b42960e81b815260040160405180910390fd5b7f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22e5f611cbb84840185615193565b805160208201516001600160801b03908116600160801b0291161760028401556040808201516003850155519091507f4793c0cb5bef4b1fdbbfbcf17e06991844eb881088b012442af17a12ff38d5cd905f90a150505050565b5f611d3e7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905090565b5f610b8682612cc9565b5f611d3e73c441915f909b16b8559c326c6582f0bfa8d7976c63b02b33206040518163ffffffff1660e01b81526004016040805180830381865af4158015611d97573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dbb91906151ca565b61309e565b333014611ddf576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f611e0c848401856151e4565b8051835491925090839060ff191660018381811115611e2d57611e2d61453f565b021790555080516040517f4016a1377b8961c4aa6f3a2d3de830a685ddbfe0f228ffc0208eb96304c4cf1a91611e6291614553565b60405180910390a150505050565b60405163beb9a0bb60e01b81526001600160a01b038416600482015263ffffffff831660248201526001600160801b0380831660448301527f00000000000000000000000000000000000000000000000000000000000000001660648201525f90611f0e9073c441915f909b16b8559c326c6582f0bfa8d7976c9063beb9a0bb906084016040805180830381865af4158015611d97573d5f803e3d5ffd5b90505b9392505050565b333014611f37576040516282b42960e81b815260040160405180910390fd5b5f611f4482840184615212565b90505f611f53825f0151612cc9565b60208301516040808501516060860151915163163ace6960e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015280861660248301529384166044820152921660648301526001600160801b0316608482015290915073c441915f909b16b8559c326c6582f0bfa8d7976c9063163ace699060a4015f6040518083038186803b158015611ffc575f80fd5b505af415801561200e573d5f803e3d5ffd5b5050505050505050565b333014612037576040516282b42960e81b815260040160405180910390fd5b5f61204482840184614910565b90505f612053825f0151612cc9565b90506120688183602001518460400151612fc5565b81602001516001600160a01b0316825f01517ff953871855f78d5ccdd6268f2d9d69fc67f26542a35d2bba1c615521aed5705484604001516040516120af91815260200190565b60405180910390a350505050565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b03163314612128576040516282b42960e81b815260040160405180910390fd5b5f61213485858561312f565b905061214760015f1b82604001516131ed565b5050505050565b33301461216d576040516282b42960e81b815260040160405180910390fd5b5f61217a82840184615282565b8051602082015160408084015160608501519151631eb2d29d60e21b815294955073c441915f909b16b8559c326c6582f0bfa8d7976c94637acb4a749461080f94909390929160040161532b565b3330146121e7576040516282b42960e81b815260040160405180910390fd5b5f6121f48284018461536a565b90505f612203825f0151612ace565b8251909150600114801561222c57505f826020015160018111156122295761222961453f565b14155b1561224a5760405163b24a3b7760e01b815260040160405180910390fd5b60208201518154829060ff19166001838181111561226a5761226a61453f565b021790555081516040517f66e174b5e03ba247add8660a34e70bdd484239fe794c2567772e8e93a5c1696b905f90a250505050565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad6780546001600160a01b031633146122e9576040516282b42960e81b815260040160405180910390fd5b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b039081169084166123585760405163c713399f60e01b815260040160405180910390fd5b806001600160a01b0316846001600160a01b03160361238a576040516305814fc960e21b815260040160405180910390fd5b6001820180546001600160a01b0319166001600160a01b0386811691821790925560405190918316907f2029edfac4c6b19a6616d552bd60af6d0ec3f6a974d3a8750de675321f382c5c905f90a350505050565b3330146123fd576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f61242a848401856153a2565b80515f9081526002840160205260409020549091506001600160a01b0316156124665760405163135d15b960e21b815260040160405180910390fd5b5f815f015160405161247790614471565b908152602001604051809103905ff080158015612496573d5f803e3d5ffd5b5082515f90815260028501602090815260409182902080546001600160a01b0319166001600160a01b03851690811790915585518351908152918201529192507f7c96960a1ebd8cc753b10836ea25bd7c9c4f8cd43590db1e8b3648cb0ec4cc89910160405180910390a15050505050565b333014612527576040516282b42960e81b815260040160405180910390fd5b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b0316806125925760405163120bf7bb60e21b815260040160405180910390fd5b5f80808080806125a4898b018b6153c8565b604051631e66650960e11b8152600481018290526001600160a01b038e16602482015260448101849052959b5093995091975095509350915073c441915f909b16b8559c326c6582f0bfa8d7976c90633cccca12906064015f6040518083038186803b158015612612575f80fd5b505af4158015612624573d5f803e3d5ffd5b505060405163fe61cc4960e01b8152600481018490525f925073c441915f909b16b8559c326c6582f0bfa8d7976c915063fe61cc4990602401602060405180830381865af4158015612678573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061269c9190615407565b60405163117e3b0960e21b815260048101899052602481018890526044810187905260648101869052608481018590526001600160a01b0380831660a4830152919250908916906345f8ec249060c4015f604051808303815f87803b158015612703575f80fd5b505af1925050508015612714575060015b6127c757612720614e3f565b806308c379a00361276f5750612734614e57565b8061273f5750612771565b878783888888866040516355682f7560e11b81526004016127669796959493929190615422565b60405180910390fd5b505b3d80801561279a576040519150601f19603f3d011682016040523d82523d5f602084013e61279f565b606091505b5087878388888886604051631e6a269160e11b81526004016127669796959493929190615422565b5050505050505050505050565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad6780546001600160a01b0316331461281e576040516282b42960e81b815260040160405180910390fd5b6128278261302e565b5050565b33301461284a576040516282b42960e81b815260040160405180910390fd5b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b0316806128b55760405163120bf7bb60e21b815260040160405180910390fd5b5f6128c28486018661546e565b9050815f5b826020015151811015610837575f836020015182815181106128eb576128eb61557c565b6020908102919091018101516040808201518251938301519151633136c5d760e01b815265ffffffffffff90911660048201526024810193909352604483015291506001600160a01b03841690633136c5d7906064015f604051808303815f87803b158015612958575f80fd5b505af1925050508015612969575060015b612a5057612975614e3f565b806308c379a0036129e15750612989614e57565b8061299457506129e3565b8160400151825f01517fcaf5a17fa52c8de175d4bfdbce1de004c92f2e8e7d81c3c56138d5ede109316c8460200151846040516129d2929190615590565b60405180910390a35050612a52565b505b3d808015612a0c576040519150601f19603f3d011682016040523d82523d5f602084013e612a11565b606091505b508160400151825f01517f8361b2b142dbdd4ee5ee6fe96616f18b6e653617e216353ee9b509ea4cdb0d288460200151846040516129d2929190615590565b505b6001016128c7565b60405163fe61cc4960e01b8152600481018290525f9073c441915f909b16b8559c326c6582f0bfa8d7976c9063fe61cc4990602401602060405180830381865af4158015612aaa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b869190615407565b5f8181527e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ac6020526040902060018101546001600160a01b0316612b2457604051636ddd9da960e01b815260040160405180910390fd5b919050565b805160408051637061726160e01b60208083019190915260e09390931b6001600160e01b031916602482015281516008818303018152602890910190915280519101205f612b7682612ace565b9050612b81816132d8565b5f612b8f846020015161309e565b905080341015612bb2576040516303e66ae760e31b815260040160405180910390fd5b8154612bcf90600160481b90046001600160401b03166001614c0f565b82546001600160401b0391909116600160481b0267ffffffffffffffff60481b199091161782556001820154612c0e906001600160a01b031682613350565b80341115612c2a57612c2a612c238234614f2d565b3390613350565b81546040805160208101869052600160481b90920460c01b6001600160c01b031916908201525f9060480160405160208183030381529060405280519060200120905080847f7153f9357c8ea496bba60bf82e67143e27b64462b49041f8e689e1b05728f84f855f0160099054906101000a90046001600160401b03168860400151604051612cba9291906155a8565b60405180910390a35050505050565b5f8181527e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ad60205260409020546001600160a01b031680612b245760405163d3227c9b60e01b815260040160405180910390fd5b612d2e836001600160a01b0316613379565b612d4b576040516303777f6960e51b815260040160405180910390fd5b81836001600160a01b03163f14612d75576040516323e13ec960e21b815260040160405180910390fd5b612d9d837f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc55565b5f80846001600160a01b031683604051602401612dba9190614f0d565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1663439fab9160e01b17905251612e0491906155e0565b5f60405180830381855af49150503d805f8114612e3c576040519150601f19603f3d011682016040523d82523d5f602084013e612e41565b606091505b5091509150612e5082826133bf565b506040516001600160a01b038616907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a25050505050565b5f81815b8451811015612ec557612ebb82868381518110612eae57612eae61557c565b60200260200101516133de565b9150600101612e8f565b509392505050565b604051632f254d7560e21b81525f9073759701b01b2fa18f8d6031f98480ffb64ba3f43f9063bc9535d490612f4c907f0000000000000000000000000000000000000000000000000000000000000000907f00000000000000000000000000000000000000000000000000000000000000009088908890600401615678565b602060405180830381865af4158015612f67573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f119190614be2565b5f612f97366010614f40565b611d3e90618b72614dbe565b5f818310612fb15781611f11565b5090919050565b5f611d3e3a615208614f40565b6040516001600160a01b0383166024820152604481018290525f9060640160408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff16633e97486160e11b1790529050612147848261340a565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad6780546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b80517f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f7545f917f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f6918391613104916130ff91906001600160801b0316614dbe565b6134b5565b9050613118825f01548360020154836134fa565b84602001516131279190614dbe565b949350505050565b61313761447e565b5f83900361315857604051634e5981a560e11b815260040160405180910390fd5b826103e881111561317c576040516352e7350f60e11b815260040160405180910390fd5b5f80835260408051808201909152818152602080820192909252908301526131a685858386613588565b60408084018290525182917fcf50ba21a594d6724d0039b955599adf260c9882300a8701c31a8b334315eddb916131dd9190614f0d565b60405180910390a2509392505050565b5f6131f783612ace565b9050613202816132d8565b805461321f90600160481b90046001600160401b03166001614c0f565b81546001600160401b03918216600160481b90810267ffffffffffffffff60481b19909216919091178084556040515f9361327793889304169060200191825260c01b6001600160c01b031916602082015260280190565b60405160208183030381529060405280519060200120905080847f7153f9357c8ea496bba60bf82e67143e27b64462b49041f8e689e1b05728f84f845f0160099054906101000a90046001600160401b0316866040516120af9291906155a8565b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab80545f9060ff1660018111156133105761331061453f565b14158061333257505f825460ff16600181111561332f5761332f61453f565b14155b1561282757604051633ac4266d60e11b815260040160405180910390fd5b5f805f805f85875af1905080610b0557604051633d2cec6f60e21b815260040160405180910390fd5b5f6001600160a01b0382163f15801590610b865750506001600160a01b03163f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470141590565b606082156133ce575080610b86565b8151156102295781518083602001fd5b5f8183106133f8575f828152602084905260409020611f11565b5f838152602083905260409020611f11565b60605f80846001600160a01b0316639bb66b287f0000000000000000000000000000000000000000000000000000000000000000866040518363ffffffff1660e01b815260040161345c929190615766565b5f604051808303815f875af1158015613477573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261349e9190810190615787565b915091506134ac82826133bf565b95945050505050565b5f6134c9670de0b6b3a76400005f196157cf565b8211156134ec57604051631cd951a760e01b815260048101839052602401612766565b50670de0b6b3a76400000290565b5f8061350d670de0b6b3a76400006134b5565b90505f61354f61353f7f000000000000000000000000000000000000000000000000000000000000000060ff166134b5565b613549600a6134b5565b9061374b565b90505f613572836135668461356c8b838c8c61385b565b9061385b565b90613869565b905061357d81613880565b979650505050505050565b60605f6135968460206157ee565b63ffffffff166001600160401b038111156135b3576135b36147de565b6040519080825280601f01601f1916602001820160405280156135dd576020820181803683370190505b5090505f5b8463ffffffff168163ffffffff1610156136ad575f5b60208163ffffffff1610156136a45787878363ffffffff1681811061361f5761361f61557c565b905060200201358163ffffffff166020811061363d5761363d61557c565b1a60f81b838261364e8560206157ee565b613658919061580e565b63ffffffff168151811061366e5761366e61557c565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191690815f1a9053506001016135f8565b506001016135e2565b50630e02a00760e31b5f806136c187613893565b8465ff000000ff00600889811b91821664ff000000ff918b901c91821617601090811b63ff0000009390931662ff00009290921691909117901c17602081811b6bffffffffffffffff000000001691901c63ffffffff161760c01b6040516020016137319695949392919061582b565b604051602081830303815290604052915050949350505050565b5f8282818303613774578015613761575f61376b565b670de0b6b3a76400005b92505050610b86565b670de0b6b3a7640000820361379557670de0b6b3a764000092505050610b86565b805f036137ae57670de0b6b3a764000092505050610b86565b670de0b6b3a764000081036137c7578492505050610b86565b670de0b6b3a76400008211156137f8576137f16137ec6137e687613a01565b8661385b565b613b28565b9250613853565b5f613818613815846ec097ce7bc90715b34b9f10000000006157cf565b90565b90505f6138306137ec61382a84613a01565b8861385b565b905061384e613815826ec097ce7bc90715b34b9f10000000006157cf565b945050505b505092915050565b5f611f116138158484613b7c565b5f611f1161381584670de0b6b3a764000085613c2e565b5f610b86670de0b6b3a7640000836157cf565b6060603f8263ffffffff16116138d057604051603f60fa1b60fa84901b1660208201526021015b6040516020818303038152906040529050919050565b613fff8263ffffffff16116139475761390c6138f86403fffffffc600285901b16600161580e565b600881811b62ffff001691901c60ff161790565b6040516020016138ba919060f09190911b7fffff00000000000000000000000000000000000000000000000000000000000016815260020190565b633fffffff8263ffffffff16116139b95761399660028363ffffffff16901b6002613972919061580e565b600881811c62ff00ff1663ff00ff009290911b9190911617601081811c91901b1790565b6040516020016138ba919060e09190911b6001600160e01b031916815260040190565b604051600360f81b60208201526001600160e01b0319600884811c62ff00ff1663ff00ff009186901b9190911617601081811c91901b1760e01b1660218201526025016138ba565b5f81670de0b6b3a7640000811015613a2f5760405163036d32ef60e41b815260048101849052602401612766565b5f613ab0670de0b6b3a7640000830460016001600160801b03821160071b91821c6001600160401b03811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810282821c670de0b6b3a763ffff198101613ad95750949350505050565b671bc16d674ec800006706f05b59d3b200005b8015613b1c57670de0b6b3a7640000838002049250818310613b14579283019260019290921c915b60011c613aec565b50919695505050505050565b5f81680a688906bd8affffff811115613b575760405163b3b6ba1f60e01b815260048101849052602401612766565b5f613b6e670de0b6b3a7640000604084901b6157cf565b905061312761381582613cfd565b5f80805f19848609848602925082811083820303915050805f03613bad5750670de0b6b3a764000090049050610b86565b670de0b6b3a76400008110613bdf57604051635173648d60e01b81526004810186905260248101859052604401612766565b5f670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b5f80805f19858709858702925082811083820303915050805f03613c6557838281613c5b57613c5b6157bb565b0492505050611f11565b838110613c9657604051630c740aef60e31b8152600481018790526024810186905260448101859052606401612766565b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b7780000000000000000000000000000000000000000000000067ff00000000000000821615613e1e57678000000000000000821615613d455768016a09e667f3bcc9090260401c5b674000000000000000821615613d64576801306fe0a31b7152df0260401c5b672000000000000000821615613d83576801172b83c7d517adce0260401c5b671000000000000000821615613da25768010b5586cf9890f62a0260401c5b670800000000000000821615613dc1576801059b0d31585743ae0260401c5b670400000000000000821615613de057680102c9a3e778060ee70260401c5b670200000000000000821615613dff5768010163da9fb33356d80260401c5b670100000000000000821615613e1e57680100b1afa5abcbed610260401c5b66ff000000000000821615613f1d576680000000000000821615613e4b5768010058c86da1c09ea20260401c5b6640000000000000821615613e69576801002c605e2e8cec500260401c5b6620000000000000821615613e8757680100162f3904051fa10260401c5b6610000000000000821615613ea5576801000b175effdc76ba0260401c5b6608000000000000821615613ec357680100058ba01fb9f96d0260401c5b6604000000000000821615613ee15768010002c5cc37da94920260401c5b6602000000000000821615613eff576801000162e525ee05470260401c5b6601000000000000821615613f1d5768010000b17255775c040260401c5b65ff00000000008216156140135765800000000000821615613f48576801000058b91b5bc9ae0260401c5b65400000000000821615613f6557680100002c5c89d5ec6d0260401c5b65200000000000821615613f825768010000162e43f4f8310260401c5b65100000000000821615613f9f57680100000b1721bcfc9a0260401c5b65080000000000821615613fbc5768010000058b90cf1e6e0260401c5b65040000000000821615613fd9576801000002c5c863b73f0260401c5b65020000000000821615613ff657680100000162e430e5a20260401c5b65010000000000821615614013576801000000b1721835510260401c5b64ff000000008216156141005764800000000082161561403c57680100000058b90c0b490260401c5b6440000000008216156140585768010000002c5c8601cc0260401c5b642000000000821615614074576801000000162e42fff00260401c5b6410000000008216156140905768010000000b17217fbb0260401c5b6408000000008216156140ac576801000000058b90bfce0260401c5b6404000000008216156140c857680100000002c5c85fe30260401c5b6402000000008216156140e45768010000000162e42ff10260401c5b64010000000082161561410057680100000000b17217f80260401c5b63ff0000008216156141e45763800000008216156141275768010000000058b90bfc0260401c5b6340000000821615614142576801000000002c5c85fe0260401c5b632000000082161561415d57680100000000162e42ff0260401c5b6310000000821615614178576801000000000b17217f0260401c5b630800000082161561419357680100000000058b90c00260401c5b63040000008216156141ae5768010000000002c5c8600260401c5b63020000008216156141c9576801000000000162e4300260401c5b63010000008216156141e45768010000000000b172180260401c5b62ff00008216156142bf5762800000821615614209576801000000000058b90c0260401c5b6240000082161561422357680100000000002c5c860260401c5b6220000082161561423d5768010000000000162e430260401c5b6210000082161561425757680100000000000b17210260401c5b620800008216156142715768010000000000058b910260401c5b6204000082161561428b576801000000000002c5c80260401c5b620200008216156142a557680100000000000162e40260401c5b620100008216156142bf576801000000000000b1720260401c5b61ff00821615614391576180008216156142e257680100000000000058b90260401c5b6140008216156142fb5768010000000000002c5d0260401c5b612000821615614314576801000000000000162e0260401c5b61100082161561432d5768010000000000000b170260401c5b610800821615614346576801000000000000058c0260401c5b61040082161561435f57680100000000000002c60260401c5b61020082161561437857680100000000000001630260401c5b61010082161561439157680100000000000000b10260401c5b60ff82161561445a5760808216156143b257680100000000000000590260401c5b60408216156143ca576801000000000000002c0260401c5b60208216156143e257680100000000000000160260401c5b60108216156143fa576801000000000000000b0260401c5b600882161561441257680100000000000000060260401c5b600482161561442a57680100000000000000030260401c5b600282161561444257680100000000000000010260401c5b600182161561445a57680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b61032c8061589d83390190565b60405180606001604052805f63ffffffff1681526020016144b060405180604001604052805f81526020015f81525090565b8152602001606081525090565b5f80602083850312156144ce575f80fd5b82356001600160401b03808211156144e4575f80fd5b818501915085601f8301126144f7575f80fd5b813581811115614505575f80fd5b866020828501011115614516575f80fd5b60209290920196919550909350505050565b5f60208284031215614538575f80fd5b5035919050565b634e487b7160e01b5f52602160045260245ffd5b60208101600283106145675761456761453f565b91905290565b6001600160a01b03811681146108da575f80fd5b8035612b248161456d565b5f6020828403121561459c575f80fd5b8135611f118161456d565b5f8083601f8401126145b7575f80fd5b5081356001600160401b038111156145cd575f80fd5b6020830191508360208260051b85010111156145e7575f80fd5b9250929050565b5f805f8060608587031215614601575f80fd5b84356001600160401b0380821115614617575f80fd5b90860190610100828903121561462b575f80fd5b90945060208601359080821115614640575f80fd5b61464c888389016145a7565b90955093506040870135915080821115614664575f80fd5b5085016101208188031215614677575f80fd5b939692955090935050565b63ffffffff811681146108da575f80fd5b8035612b2481614682565b6001600160801b03811681146108da575f80fd5b8035612b248161469e565b5f805f805f60a086880312156146d1575f80fd5b85356146dc8161456d565b945060208601356146ec81614682565b935060408601356001600160401b03811115614706575f80fd5b860160408189031215614717575f80fd5b925060608601356147278161469e565b915060808601356147378161469e565b809150509295509295909350565b5f805f60608486031215614757575f80fd5b83356147628161456d565b9250602084013561477281614682565b915060408401356147828161469e565b809150509250925092565b5f805f6040848603121561479f575f80fd5b83356001600160401b038111156147b4575f80fd5b6147c0868287016145a7565b909450925050602084013565ffffffffffff81168114614782575f80fd5b634e487b7160e01b5f52604160045260245ffd5b606081018181106001600160401b0382111715614811576148116147de565b60405250565b604081018181106001600160401b0382111715614811576148116147de565b602081018181106001600160401b0382111715614811576148116147de565b608081018181106001600160401b0382111715614811576148116147de565b601f8201601f191681016001600160401b0381118282101715614899576148996147de565b6040525050565b60405161014081016001600160401b03811182821017156148c3576148c36147de565b60405290565b5f606082840312156148d9575f80fd5b6040516148e5816147f2565b8091508235815260208301356148fa8161456d565b6020820152604092830135920191909152919050565b5f60608284031215614920575f80fd5b611f1183836148c9565b5f6040828403121561493a575f80fd5b60405161494681614817565b80915082518152602083015160208201525092915050565b5f6001600160401b03821115614976576149766147de565b50601f01601f191660200190565b5f82601f830112614993575f80fd5b815161499e8161495e565b6040516149ab8282614874565b8281528560208487010111156149bf575f80fd5b8260208601602083015e5f92810160200192909252509392505050565b5f602082840312156149ec575f80fd5b81516001600160401b0380821115614a02575f80fd5b9083019060808286031215614a15575f80fd5b604051614a21816147f2565b8251614a2c81614682565b8152614a3b866020850161492a565b6020820152606083015182811115614a51575f80fd5b614a5d87828601614984565b60408301525095945050505050565b5f60608284031215614a7c575f80fd5b604051614a88816147f2565b823581526020830135614a9a8161469e565b60208201526040928301359281019290925250919050565b803560028110612b24575f80fd5b5f60608284031215614ad0575f80fd5b604051614adc816147f2565b8235815260208301356020820152614af660408401614ab2565b60408201529392505050565b5f82601f830112614b11575f80fd5b8135614b1c8161495e565b604051614b298282614874565b828152856020848701011115614b3d575f80fd5b826020860160208301375f92810160200192909252509392505050565b5f60208284031215614b6a575f80fd5b81356001600160401b0380821115614b80575f80fd5b9083019060608286031215614b93575f80fd5b604051614b9f816147f2565b8235614baa8161456d565b815260208381013590820152604083013582811115614bc7575f80fd5b614a5d87828601614b02565b80518015158114612b24575f80fd5b5f60208284031215614bf2575f80fd5b611f1182614bd3565b634e487b7160e01b5f52601160045260245ffd5b6001600160401b03818116838216019080821115614c2f57614c2f614bfb565b5092915050565b80356001600160401b0381168114612b24575f80fd5b5f60208284031215614c5c575f80fd5b611f1182614c36565b5f6001600160401b03808316818103614c8057614c80614bfb565b6001019392505050565b803560238110612b24575f80fd5b60238110614ca857614ca861453f565b9052565b5f808335601e19843603018112614cc1575f80fd5b83016020810192503590506001600160401b03811115614cdf575f80fd5b8036038213156145e7575f80fd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b60208152813560208201525f614d2d60208401614c36565b6001600160401b038082166040850152614d4960408601614c8a565b9150614d586060850183614c98565b614d656060860186614cac565b9250610100806080870152614d7f61012087018584614ced565b935082614d8e60808901614c36565b1660a087015260a087013560c087015260c087013560e087015260e0870135818701525050508091505092915050565b80820180821115610b8657610b86614bfb565b5f60208284031215614de1575f80fd5b611f1182614c8a565b5f808335601e19843603018112614dff575f80fd5b8301803591506001600160401b03821115614e18575f80fd5b6020019150368190038213156145e7575f80fd5b602081525f611f0e602083018486614ced565b5f60033d11156138155760045f803e505f5160e01c90565b5f60443d1015614e645790565b6040516003193d81016004833e81513d6001600160401b038160248401118184111715614e9357505050505090565b8285019150815181811115614eab5750505050505090565b843d8701016020828501011115614ec55750505050505090565b614ed460208286010187614874565b509095945050505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611f116020830184614edf565b60208101610b868284614c98565b81810381811115610b8657610b86614bfb565b8082028115828204841417610b8657610b86614bfb565b5f60208284031215614f67575f80fd5b81356001600160401b0380821115614f7d575f80fd5b9083019060408286031215614f90575f80fd5b604051614f9c81614817565b82358152602083013582811115614fb1575f80fd5b614fbd87828601614b02565b60208301525095945050505050565b5f8060408385031215614fdd575f80fd5b825160018110614feb575f80fd5b60208401519092506001600160401b03811115615006575f80fd5b61501285828601614984565b9150509250929050565b5f805f6060848603121561502e575f80fd5b83516150398161456d565b602085015190935061504a8161456d565b60408501519092506147828161469e565b5f610140828403121561506c575f80fd5b6150746148a0565b61507d83614ab2565b815261508b602084016146b2565b6020820152604083013560408201526150a660608401614693565b6060820152608083013560808201526150c160a084016146b2565b60a08201526150d260c084016146b2565b60c082015260e083013560e08201526101008084013581830152506101206150fb818501614581565b908201529392505050565b6001600160a01b0388811682528716602082015263ffffffff8616604082015260e060608201525f85356003811061513c575f80fd5b60e083015261514e6020870187614cac565b604061010085015261516561012085018284614ced565b6001600160801b03978816608086015295871660a0850152505050921660c090920191909152949350505050565b5f606082840312156151a3575f80fd5b6040516151af816147f2565b82356151ba8161469e565b81526020830135614a9a8161469e565b5f604082840312156151da575f80fd5b611f11838361492a565b5f602082840312156151f4575f80fd5b60405161520081614836565b61520983614ab2565b81529392505050565b5f60808284031215615222575f80fd5b60405161522e81614855565b8235815260208301356152408161456d565b602082015260408301356152538161456d565b604082015260608301356152668161469e565b60608201529392505050565b803560ff81168114612b24575f80fd5b5f60208284031215615292575f80fd5b81356001600160401b03808211156152a8575f80fd5b90830190608082860312156152bb575f80fd5b6040516152c781614855565b823581526020830135828111156152dc575f80fd5b6152e887828601614b02565b6020830152506040830135828111156152ff575f80fd5b61530b87828601614b02565b60408301525061531d60608401615272565b606082015295945050505050565b848152608060208201525f6153436080830186614edf565b82810360408401526153558186614edf565b91505060ff8316606083015295945050505050565b5f6040828403121561537a575f80fd5b60405161538681614817565b8235815261539660208401614ab2565b60208201529392505050565b5f602082840312156153b2575f80fd5b6040516153be81614836565b9135825250919050565b5f805f805f8060c087890312156153dd575f80fd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b5f60208284031215615417575f80fd5b8151611f118161456d565b8781528660208201526001600160a01b03861660408201528460608201528360808201528260a082015260e060c08201525f61546160e0830184614edf565b9998505050505050505050565b5f602080838503121561547f575f80fd5b82356001600160401b0380821115615495575f80fd5b818501915060408083880312156154aa575f80fd5b80516154b581614817565b8335815284840135838111156154c9575f80fd5b80850194505087601f8501126154dd575f80fd5b8335838111156154ef576154ef6147de565b82519350615502868260051b0185614874565b80845260609081028501860190868501908a83111561551f575f80fd5b958701955b828710156155685780878c03121561553a575f80fd5b8451615545816147f2565b873581528888013589820152858801358682015282529586019590870190615524565b505050938401919091525090949350505050565b634e487b7160e01b5f52603260045260245ffd5b828152604060208201525f611f0e6040830184614edf565b6001600160401b0383168152604060208201525f611f0e6040830184614edf565b5f81518060208401855e5f93019283525090919050565b5f611f1182846155c9565b5f808335601e19843603018112615600575f80fd5b83016020810192503590506001600160401b0381111561561e575f80fd5b8060051b36038213156145e7575f80fd5b8183525f7f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561565f575f80fd5b8260051b80836020870137939093016020019392505050565b6001600160a01b03851681526001600160e01b031984166020820152604081018390526080606082015260ff6156ad83615272565b1660808201525f60208301356156c281614682565b63ffffffff80821660a0850152604085013560c08501526001600160401b036156ed60608701614c36565b1660e08501526080850135915061570382614682565b61010081831681860152610120925060a08601358386015261572860c08701876155eb565b9250836101408701526157406101a08701848361562f565b60e088013561016088015291909601356101809095019490945250919695505050505050565b6001600160a01b0383168152604060208201525f611f0e6040830184614edf565b5f8060408385031215615798575f80fd5b6157a183614bd3565b915060208301516001600160401b03811115615006575f80fd5b634e487b7160e01b5f52601260045260245ffd5b5f826157e957634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff81811683821602808216919082811461385357613853614bfb565b63ffffffff818116838216019080821115614c2f57614c2f614bfb565b6001600160e01b0319871681527fff000000000000000000000000000000000000000000000000000000000000008681166004830152851660058201525f61587f61587960068401876155c9565b856155c9565b6001600160c01b031993909316835250506008019594505050505056fe60c0604052348015600e575f80fd5b5060405161032c38038061032c833981016040819052602b916036565b6080523360a052604c565b5f602082840312156045575f80fd5b5051919050565b60805160a0516102ba6100725f395f81816052015261010d01525f60cf01526102ba5ff3fe608060405260043610610036575f3560e01c8063338c5371146100415780639bb66b2814610091578063e905182a146100be575f80fd5b3661003d57005b5f80fd5b34801561004c575f80fd5b506100747f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561009c575f80fd5b506100b06100ab3660046101ae565b6100ff565b604051610088929190610237565b3480156100c9575f80fd5b506100f17f000000000000000000000000000000000000000000000000000000000000000081565b604051908152602001610088565b5f6060336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461014a576040516282b42960e81b815260040160405180910390fd5b846001600160a01b03168484604051610164929190610275565b5f60405180830381855af49150503d805f811461019c576040519150601f19603f3d011682016040523d82523d5f602084013e6101a1565b606091505b5091509150935093915050565b5f805f604084860312156101c0575f80fd5b83356001600160a01b03811681146101d6575f80fd5b9250602084013567ffffffffffffffff808211156101f2575f80fd5b818601915086601f830112610205575f80fd5b813581811115610213575f80fd5b876020828501011115610224575f80fd5b6020830194508093505050509250925092565b8215158152604060208201525f82518060408401528060208501606085015e5f606082850101526060601f19601f8301168401019150509392505050565b818382375f910190815291905056fea26469706673582212207f8ca0f108479aa0bdad395f48bcd618386aaeddd23d9abd5fbee2190be446a364736f6c63430008190033a264697066735822122033e86ee408abcef1e18afebec9577f10d63564b3a2e69e1abd062b148ce3d82c64736f6c6343000819003300000000000000000000000068cfb0df884e488e362690408231c316ed7348af000000000000000000000000ad4a6d5dae036fe490b34c08c7085c6b2ae69969000000000000000000000000000000000000000000000000000000000000000103170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000de0b6b3a7640000
Deployed Bytecode
0x608060405260043610610229575f3560e01c80635e6dae2611610131578063ae8a4d98116100ac578063c3b8ec8e1161007c578063f2fde38b11610062578063f2fde38b1461072d578063fbebbc2c1461074c578063fe61cc491461076b575f80fd5b8063c3b8ec8e146106ef578063c45578b51461070e575f80fd5b8063ae8a4d981461063c578063afce33c41461065b578063b7d8e1a91461067a578063be8d42c014610699575f80fd5b8063928bc49d116101015780639a870c8b116100e75780639a870c8b146105c25780639acd53ef146105e1578063a8bd41cd14610600575f80fd5b8063928bc49d1461058457806393dbdf1d146105a3575f80fd5b80635e6dae26146104f1578063805ce31d146105105780638257f3d51461053257806390ffc4f914610551575f80fd5b80632a6c3229116101c1578063423e69b611610191578063520548341161017757806352054834146104ab5780635b2e9c4c146104be5780635c60da1b146104dd575f80fd5b8063423e69b614610441578063439fab911461048c575f80fd5b80632a6c32291461038f5780632ab9b512146103ce57806335ede969146103ed57806338004f691461040c575f80fd5b80630c86ea46116101fc5780630c86ea461461030357806317abcf6014610322578063253946451461034157806326aa101f14610360575f80fd5b8063017b73111461022d5780630705f4651461024e57806309824a80146102835780630b61764614610296575b5f80fd5b348015610238575f80fd5b5061024c6102473660046144bd565b61078a565b005b348015610259575f80fd5b5061026d610268366004614528565b610840565b60405161027a9190614553565b60405180910390f35b61024c61029136600461458c565b610856565b3480156102a1575f80fd5b507f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f6547f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f754604080519283526001600160801b0390911660208301520161027a565b34801561030e575f80fd5b5061024c61031d3660046144bd565b6108dd565b34801561032d575f80fd5b5061024c61033c3660046144bd565b610997565b34801561034c575f80fd5b5061024c61035b3660046144bd565b610ac1565b34801561036b575f80fd5b5061037f61037a36600461458c565b610b0a565b604051901515815260200161027a565b34801561039a575f80fd5b506103ae6103a9366004614528565b610b8c565b604080516001600160401b0393841681529290911660208301520161027a565b3480156103d9575f80fd5b5061024c6103e83660046145ee565b610bba565b3480156103f8575f80fd5b5061024c6104073660046144bd565b611434565b348015610417575f80fd5b507e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5460ff1661026d565b34801561044c575f80fd5b506104747f000000000000000000000000ad4a6d5dae036fe490b34c08c7085c6b2ae6996981565b6040516001600160a01b03909116815260200161027a565b348015610497575f80fd5b5061024c6104a63660046144bd565b6115a3565b61024c6104b93660046146bd565b611bbd565b3480156104c9575f80fd5b5061024c6104d83660046144bd565b611c6e565b3480156104e8575f80fd5b50610474611d15565b3480156104fc575f80fd5b5061047461050b366004614528565b611d43565b34801561051b575f80fd5b50610524611d4d565b60405190815260200161027a565b34801561053d575f80fd5b5061024c61054c3660046144bd565b611dc0565b34801561055c575f80fd5b506104747f00000000000000000000000068cfb0df884e488e362690408231c316ed7348af81565b34801561058f575f80fd5b5061052461059e366004614745565b611e70565b3480156105ae575f80fd5b5061024c6105bd3660046144bd565b611f18565b3480156105cd575f80fd5b5061024c6105dc3660046144bd565b612018565b3480156105ec575f80fd5b5061024c6105fb36600461478d565b6120bd565b34801561060b575f80fd5b507fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68546001600160a01b0316610474565b348015610647575f80fd5b5061024c6106563660046144bd565b61214e565b348015610666575f80fd5b5061024c6106753660046144bd565b6121c8565b348015610685575f80fd5b5061024c61069436600461458c565b61229f565b3480156106a4575f80fd5b506105246106b336600461458c565b6001600160a01b03165f9081527f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22e602052604090206001015490565b3480156106fa575f80fd5b5061024c6107093660046144bd565b6123de565b348015610719575f80fd5b5061024c6107283660046144bd565b612508565b348015610738575f80fd5b5061024c61074736600461458c565b6127d4565b348015610757575f80fd5b5061024c6107663660046144bd565b61282b565b348015610776575f80fd5b50610474610785366004614528565b612a5a565b3330146107a9576040516282b42960e81b815260040160405180910390fd5b5f6107b682840184614910565b805160208201516040808401519051631e66650960e11b815260048101939093526001600160a01b039091166024830152604482015290915073c441915f909b16b8559c326c6582f0bfa8d7976c90633cccca12906064015b5f6040518083038186803b158015610825575f80fd5b505af4158015610837573d5f803e3d5ffd5b50505050505050565b5f8061084b83612ace565b5460ff169392505050565b6040516213049560e71b81526001600160a01b03821660048201526108da9073c441915f909b16b8559c326c6582f0bfa8d7976c906309824a80906024015f60405180830381865af41580156108ae573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526108d591908101906149dc565b612b29565b50565b3330146108fc576040516282b42960e81b815260040160405180910390fd5b7f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f65f61092a84840185614a6c565b8051835560208101516001840180546fffffffffffffffffffffffffffffffff19166001600160801b039092169190911790556040808201516002850155519091507f5e3c25378b5946068b94aa2ea10c4c1e215cc975f994322b159ddc9237a973d4905f90a150505050565b3330146109b6576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f6109e384840185614ac0565b90505f6109f38260200151612cc9565b82515f9081526001808601602052604090912090810154919250906001600160a01b031615610a3557604051631f6206e560e01b815260040160405180910390fd5b60408301518154829060ff191660018381811115610a5557610a5561453f565b02179055506001810180546001600160a01b0319166001600160a01b038416179055805470ffffffffffffffffffffffffffffffff001916815582516040517fe7e6b36c9bc4c7817d3879c45d6ce1edd3c61b1966c488f1817697bb0b704525905f90a2505050505050565b333014610ae0576040516282b42960e81b815260040160405180910390fd5b5f610aed82840184614b5a565b9050610b05815f015182602001518360400151612d1c565b505050565b6040516326aa101f60e01b81526001600160a01b03821660048201525f9073c441915f909b16b8559c326c6582f0bfa8d7976c906326aa101f90602401602060405180830381865af4158015610b62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b869190614be2565b92915050565b5f805f610b9884612ace565b546001600160401b036101008204811696600160481b90920416945092505050565b5f5a90505f610bc98635612ace565b8054909150610be79061010090046001600160401b03166001614c0f565b6001600160401b0316610c006040880160208901614c4c565b6001600160401b031614610c2757604051633ab3447f60e11b815260040160405180910390fd5b805461010090046001600160401b0316816001610c4383614c65565b91906101000a8154816001600160401b0302191690836001600160401b03160217905550505f86604051602001610c7a9190614d15565b6040516020818303038152906040528051906020012090505f610cd08787808060200260200160405190810160405280939291908181526020018383602002808284375f92019190915250869250612e8b915050565b9050610cdc8186612ecd565b610cf9576040516309bde33960e01b815260040160405180910390fd5b5f610d0a60a08a0160808b01614c4c565b6001600160401b031690505f5481610d229190614dbe565b5a1015610d4257604051636eb14fc360e11b815260040160405180910390fd5b60015f610d5560608c0160408d01614dd1565b6022811115610d6657610d6661453f565b03610dd557306335ede96983610d7f60608e018e614dea565b6040518463ffffffff1660e01b8152600401610d9c929190614e2c565b5f604051808303815f88803b158015610db3575f80fd5b5087f193505050508015610dc5575060015b610dd057505f61133b565b61133b565b6002610de760608c0160408d01614dd1565b6022811115610df857610df861453f565b03610e11573063c3b8ec8e83610d7f60608e018e614dea565b6003610e2360608c0160408d01614dd1565b6022811115610e3457610e3461453f565b03610e4d57306317abcf6083610d7f60608e018e614dea565b6004610e5f60608c0160408d01614dd1565b6022811115610e7057610e7061453f565b03610e89573063afce33c483610d7f60608e018e614dea565b6005610e9b60608c0160408d01614dd1565b6022811115610eac57610eac61453f565b03610ec55730638257f3d583610d7f60608e018e614dea565b6006610ed760608c0160408d01614dd1565b6022811115610ee857610ee861453f565b03610f015730639a870c8b83610d7f60608e018e614dea565b6001610f1360608c0160408d01614dd1565b6022811115610f2457610f2461453f565b03610f3d5730632539464583610d7f60608e018e614dea565b6007610f4f60608c0160408d01614dd1565b6022811115610f6057610f6061453f565b03610f795730635b2e9c4c83610d7f60608e018e614dea565b6008610f8b60608c0160408d01614dd1565b6022811115610f9c57610f9c61453f565b03610fb55730630c86ea4683610d7f60608e018e614dea565b6009610fc760608c0160408d01614dd1565b6022811115610fd857610fd861453f565b03610ff157306393dbdf1d83610d7f60608e018e614dea565b600a61100360608c0160408d01614dd1565b60228111156110145761101461453f565b0361102d573063ae8a4d9883610d7f60608e018e614dea565b600b61103f60608c0160408d01614dd1565b60228111156110505761105061453f565b03611069573063017b731183610d7f60608e018e614dea565b602261107b60608c0160408d01614dd1565b602281111561108c5761108c61453f565b036111b6573063fbebbc2c836110a560608e018e614dea565b6040518463ffffffff1660e01b81526004016110c2929190614e2c565b5f604051808303815f88803b1580156110d9575f80fd5b5087f1935050505080156110eb575060015b610dd0576110f7614e3f565b806308c379a003611156575061110b614e57565b806111165750611158565b7fa5c3d8fb760908f41c76be7895cad9604026af9199941b8acb89df38129ced96816040516111459190614f0d565b60405180910390a15f91505061133b565b505b3d808015611181576040519150601f19603f3d011682016040523d82523d5f602084013e611186565b606091505b507f6ad5b0077c5d29c0997620effc37071ab1076e5c07e562bf474d2e8af8e67b65816040516111459190614f0d565b60216111c860608c0160408d01614dd1565b60228111156111d9576111d961453f565b036112f2573063c45578b5836111f260608e018e614dea565b6040518463ffffffff1660e01b815260040161120f929190614e2c565b5f604051808303815f88803b158015611226575f80fd5b5087f193505050508015611238575060015b610dd057611244614e3f565b806308c379a0036112925750611258614e57565b806112635750611294565b7f7288d75ae482e895a82170fea3e4b676deaafccd3a4ed2b0458b52eb3e3f9871816040516111459190614f0d565b505b3d8080156112bd576040519150601f19603f3d011682016040523d82523d5f602084013e6112c2565b606091505b507f83299bf4eb6c92af218e82e3d6a849c455fc3d6806a93d99070c999d360f3a2b816040516111459190614f0d565b505f7fbaa1607288f2f457b14d1c481bb0470ad2af897b6f1e438930a75184acf542a861132560608c0160408d01614dd1565b6040516113329190614f1f565b60405180910390a15b5f5a6113479088614f2d565b61134f612f8b565b6113599190614dbe565b90505f61136a3a8d60a00135612fa3565b6113749083614f40565b90505f61139c61138860c08f013584614dbe565b60018a01546001600160a01b031631612fa3565b90506113a6612fb8565b8111156113c65760018801546113c6906001600160a01b03163383612fc5565b8c60e001358d5f01357f617fdb0cb78f01551a192a3673208ec5eb09f20a90acf673c63a0dcb11745a7a8f60200160208101906114039190614c4c565b604080516001600160401b03909216825288151560208301520160405180910390a350505050505050505050505050565b333014611453576040516282b42960e81b815260040160405180910390fd5b5f61146082840184614f57565b90505f61146f825f0151612cc9565b90508160200151515f03611496576040516309e256f760e21b815260040160405180910390fd5b5f8083602001518060200190518101906114b09190614fcc565b90925090505f8280156114c5576114c561453f565b0361159b575f805f838060200190518101906114e1919061501c565b60405163163ace6960e01b81526001600160a01b037f000000000000000000000000ad4a6d5dae036fe490b34c08c7085c6b2ae6996981166004830152808b1660248301528085166044830152831660648201526001600160801b0382166084820152929550909350915073c441915f909b16b8559c326c6582f0bfa8d7976c9063163ace699060a4015f6040518083038186803b158015611581575f80fd5b505af4158015611593573d5f803e3d5ffd5b505050505050505b505050505050565b5f6115cc7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b6001600160a01b0316036115f2576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f61161f8484018561505b565b905061162a3361302e565b80518254839060ff1916600183818111156116475761164761453f565b02179055505f7f03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131460405161167a90614471565b908152602001604051809103905ff080158015611699573d5f803e3d5ffd5b507f03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c1113145f818152600286016020908152604080832080546001600160a01b0319166001600160a01b03871690811790915580845260038901835281842094909455805160808101825283815280830184905280820184905260608101949094526001808452808901909252909120825181549495509293909291839160ff191690838181111561174a5761174a61453f565b0217905550602082810151825460408086015170ffffffffffffffffffffffffffffffff00199092166101006001600160401b039485160267ffffffffffffffff60481b191617600160481b9390921692909202178355606093840151600193840180546001600160a01b0319166001600160a01b0392831617905581516080810183525f808252818501819052818401819052918716958101959095526002815287840190925290208251815491929091839160ff199091169083818111156118165761181661453f565b02179055506020820151815460408085015170ffffffffffffffffffffffffffffffff00199092166101006001600160401b039485160267ffffffffffffffff60481b191617600160481b9390921692909202178255606090920151600190910180546001600160a01b0319166001600160a01b03909216919091179055608083015190515f91906118a790614471565b908152602001604051809103905ff0801580156118c6573d5f803e3d5ffd5b50608084810180515f908152600288016020908152604080832080546001600160a01b0388166001600160a01b03199091168117909155935184845260038b0183528184205580519485018152828552848201839052848101839052606080860194909452928801518351637061726160e01b8184015260e09190911b6001600160e01b0319166024820152835160088183030181526028909101845280519082012082526001808a01909152919020825181549495509293909291839160ff191690838181111561199a5761199a61453f565b02179055506020820151815460408401516001600160401b03908116600160481b0267ffffffffffffffff60481b1991909316610100021670ffffffffffffffffffffffffffffffff001990911617178155606090910151600190910180546001600160a01b039092166001600160a01b03199092169190911790555f611a3e7f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f690565b6040850151815560208501516001820180546fffffffffffffffffffffffffffffffff19166001600160801b03928316179055610100860151600283015560608601517f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22f80546001600160a01b0387166001600160a01b031963ffffffff9094167401000000000000000000000000000000000000000002939093166001600160c01b03199091161791909117905560e08601517f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c2315560a086015160c08701518216600160801b029116177f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c2305590507f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22e5f7f06e511110254c925caa9863541ca318b1a9a0615f0ac1669e771c5d47be3a4bb610120969096015186546001600160a01b0319166001600160a01b03909116179095555050505050505050565b60405163711d829160e01b81525f9073c441915f909b16b8559c326c6582f0bfa8d7976c9063711d829190611c2290899033908a908a908a907f0000000000000000000000000000000000000000000000000de0b6b3a7640000908b90600401615106565b5f60405180830381865af4158015611c3c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611c6391908101906149dc565b905061159b81612b29565b333014611c8d576040516282b42960e81b815260040160405180910390fd5b7f8d3b47662f045c362f825b520d7ddf7a0e5f6703a828606de6840b3652b8c22e5f611cbb84840185615193565b805160208201516001600160801b03908116600160801b0291161760028401556040808201516003850155519091507f4793c0cb5bef4b1fdbbfbcf17e06991844eb881088b012442af17a12ff38d5cd905f90a150505050565b5f611d3e7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5490565b905090565b5f610b8682612cc9565b5f611d3e73c441915f909b16b8559c326c6582f0bfa8d7976c63b02b33206040518163ffffffff1660e01b81526004016040805180830381865af4158015611d97573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dbb91906151ca565b61309e565b333014611ddf576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f611e0c848401856151e4565b8051835491925090839060ff191660018381811115611e2d57611e2d61453f565b021790555080516040517f4016a1377b8961c4aa6f3a2d3de830a685ddbfe0f228ffc0208eb96304c4cf1a91611e6291614553565b60405180910390a150505050565b60405163beb9a0bb60e01b81526001600160a01b038416600482015263ffffffff831660248201526001600160801b0380831660448301527f0000000000000000000000000000000000000000000000000de0b6b3a76400001660648201525f90611f0e9073c441915f909b16b8559c326c6582f0bfa8d7976c9063beb9a0bb906084016040805180830381865af4158015611d97573d5f803e3d5ffd5b90505b9392505050565b333014611f37576040516282b42960e81b815260040160405180910390fd5b5f611f4482840184615212565b90505f611f53825f0151612cc9565b60208301516040808501516060860151915163163ace6960e01b81526001600160a01b037f000000000000000000000000ad4a6d5dae036fe490b34c08c7085c6b2ae699698116600483015280861660248301529384166044820152921660648301526001600160801b0316608482015290915073c441915f909b16b8559c326c6582f0bfa8d7976c9063163ace699060a4015f6040518083038186803b158015611ffc575f80fd5b505af415801561200e573d5f803e3d5ffd5b5050505050505050565b333014612037576040516282b42960e81b815260040160405180910390fd5b5f61204482840184614910565b90505f612053825f0151612cc9565b90506120688183602001518460400151612fc5565b81602001516001600160a01b0316825f01517ff953871855f78d5ccdd6268f2d9d69fc67f26542a35d2bba1c615521aed5705484604001516040516120af91815260200190565b60405180910390a350505050565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b03163314612128576040516282b42960e81b815260040160405180910390fd5b5f61213485858561312f565b905061214760015f1b82604001516131ed565b5050505050565b33301461216d576040516282b42960e81b815260040160405180910390fd5b5f61217a82840184615282565b8051602082015160408084015160608501519151631eb2d29d60e21b815294955073c441915f909b16b8559c326c6582f0bfa8d7976c94637acb4a749461080f94909390929160040161532b565b3330146121e7576040516282b42960e81b815260040160405180910390fd5b5f6121f48284018461536a565b90505f612203825f0151612ace565b8251909150600114801561222c57505f826020015160018111156122295761222961453f565b14155b1561224a5760405163b24a3b7760e01b815260040160405180910390fd5b60208201518154829060ff19166001838181111561226a5761226a61453f565b021790555081516040517f66e174b5e03ba247add8660a34e70bdd484239fe794c2567772e8e93a5c1696b905f90a250505050565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad6780546001600160a01b031633146122e9576040516282b42960e81b815260040160405180910390fd5b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b039081169084166123585760405163c713399f60e01b815260040160405180910390fd5b806001600160a01b0316846001600160a01b03160361238a576040516305814fc960e21b815260040160405180910390fd5b6001820180546001600160a01b0319166001600160a01b0386811691821790925560405190918316907f2029edfac4c6b19a6616d552bd60af6d0ec3f6a974d3a8750de675321f382c5c905f90a350505050565b3330146123fd576040516282b42960e81b815260040160405180910390fd5b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab5f61242a848401856153a2565b80515f9081526002840160205260409020549091506001600160a01b0316156124665760405163135d15b960e21b815260040160405180910390fd5b5f815f015160405161247790614471565b908152602001604051809103905ff080158015612496573d5f803e3d5ffd5b5082515f90815260028501602090815260409182902080546001600160a01b0319166001600160a01b03851690811790915585518351908152918201529192507f7c96960a1ebd8cc753b10836ea25bd7c9c4f8cd43590db1e8b3648cb0ec4cc89910160405180910390a15050505050565b333014612527576040516282b42960e81b815260040160405180910390fd5b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b0316806125925760405163120bf7bb60e21b815260040160405180910390fd5b5f80808080806125a4898b018b6153c8565b604051631e66650960e11b8152600481018290526001600160a01b038e16602482015260448101849052959b5093995091975095509350915073c441915f909b16b8559c326c6582f0bfa8d7976c90633cccca12906064015f6040518083038186803b158015612612575f80fd5b505af4158015612624573d5f803e3d5ffd5b505060405163fe61cc4960e01b8152600481018490525f925073c441915f909b16b8559c326c6582f0bfa8d7976c915063fe61cc4990602401602060405180830381865af4158015612678573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061269c9190615407565b60405163117e3b0960e21b815260048101899052602481018890526044810187905260648101869052608481018590526001600160a01b0380831660a4830152919250908916906345f8ec249060c4015f604051808303815f87803b158015612703575f80fd5b505af1925050508015612714575060015b6127c757612720614e3f565b806308c379a00361276f5750612734614e57565b8061273f5750612771565b878783888888866040516355682f7560e11b81526004016127669796959493929190615422565b60405180910390fd5b505b3d80801561279a576040519150601f19603f3d011682016040523d82523d5f602084013e61279f565b606091505b5087878388888886604051631e6a269160e11b81526004016127669796959493929190615422565b5050505050505050505050565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad6780546001600160a01b0316331461281e576040516282b42960e81b815260040160405180910390fd5b6128278261302e565b5050565b33301461284a576040516282b42960e81b815260040160405180910390fd5b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad68547fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad67906001600160a01b0316806128b55760405163120bf7bb60e21b815260040160405180910390fd5b5f6128c28486018661546e565b9050815f5b826020015151811015610837575f836020015182815181106128eb576128eb61557c565b6020908102919091018101516040808201518251938301519151633136c5d760e01b815265ffffffffffff90911660048201526024810193909352604483015291506001600160a01b03841690633136c5d7906064015f604051808303815f87803b158015612958575f80fd5b505af1925050508015612969575060015b612a5057612975614e3f565b806308c379a0036129e15750612989614e57565b8061299457506129e3565b8160400151825f01517fcaf5a17fa52c8de175d4bfdbce1de004c92f2e8e7d81c3c56138d5ede109316c8460200151846040516129d2929190615590565b60405180910390a35050612a52565b505b3d808015612a0c576040519150601f19603f3d011682016040523d82523d5f602084013e612a11565b606091505b508160400151825f01517f8361b2b142dbdd4ee5ee6fe96616f18b6e653617e216353ee9b509ea4cdb0d288460200151846040516129d2929190615590565b505b6001016128c7565b60405163fe61cc4960e01b8152600481018290525f9073c441915f909b16b8559c326c6582f0bfa8d7976c9063fe61cc4990602401602060405180830381865af4158015612aaa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b869190615407565b5f8181527e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ac6020526040902060018101546001600160a01b0316612b2457604051636ddd9da960e01b815260040160405180910390fd5b919050565b805160408051637061726160e01b60208083019190915260e09390931b6001600160e01b031916602482015281516008818303018152602890910190915280519101205f612b7682612ace565b9050612b81816132d8565b5f612b8f846020015161309e565b905080341015612bb2576040516303e66ae760e31b815260040160405180910390fd5b8154612bcf90600160481b90046001600160401b03166001614c0f565b82546001600160401b0391909116600160481b0267ffffffffffffffff60481b199091161782556001820154612c0e906001600160a01b031682613350565b80341115612c2a57612c2a612c238234614f2d565b3390613350565b81546040805160208101869052600160481b90920460c01b6001600160c01b031916908201525f9060480160405160208183030381529060405280519060200120905080847f7153f9357c8ea496bba60bf82e67143e27b64462b49041f8e689e1b05728f84f855f0160099054906101000a90046001600160401b03168860400151604051612cba9291906155a8565b60405180910390a35050505050565b5f8181527e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ad60205260409020546001600160a01b031680612b245760405163d3227c9b60e01b815260040160405180910390fd5b612d2e836001600160a01b0316613379565b612d4b576040516303777f6960e51b815260040160405180910390fd5b81836001600160a01b03163f14612d75576040516323e13ec960e21b815260040160405180910390fd5b612d9d837f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc55565b5f80846001600160a01b031683604051602401612dba9190614f0d565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1663439fab9160e01b17905251612e0491906155e0565b5f60405180830381855af49150503d805f8114612e3c576040519150601f19603f3d011682016040523d82523d5f602084013e612e41565b606091505b5091509150612e5082826133bf565b506040516001600160a01b038616907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a25050505050565b5f81815b8451811015612ec557612ebb82868381518110612eae57612eae61557c565b60200260200101516133de565b9150600101612e8f565b509392505050565b604051632f254d7560e21b81525f9073759701b01b2fa18f8d6031f98480ffb64ba3f43f9063bc9535d490612f4c907f00000000000000000000000068cfb0df884e488e362690408231c316ed7348af907f01000000000000000000000000000000000000000000000000000000000000009088908890600401615678565b602060405180830381865af4158015612f67573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f119190614be2565b5f612f97366010614f40565b611d3e90618b72614dbe565b5f818310612fb15781611f11565b5090919050565b5f611d3e3a615208614f40565b6040516001600160a01b0383166024820152604481018290525f9060640160408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff16633e97486160e11b1790529050612147848261340a565b7fe07f9585be08def4dcde4d58f9f84d3982cbebefa85d2f6b9bdfcf41bc09ad6780546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b80517f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f7545f917f59ef95eb9983b1a4650e1bc666384b8507689fc8aca3edd429d7e07c0ca9d2f6918391613104916130ff91906001600160801b0316614dbe565b6134b5565b9050613118825f01548360020154836134fa565b84602001516131279190614dbe565b949350505050565b61313761447e565b5f83900361315857604051634e5981a560e11b815260040160405180910390fd5b826103e881111561317c576040516352e7350f60e11b815260040160405180910390fd5b5f80835260408051808201909152818152602080820192909252908301526131a685858386613588565b60408084018290525182917fcf50ba21a594d6724d0039b955599adf260c9882300a8701c31a8b334315eddb916131dd9190614f0d565b60405180910390a2509392505050565b5f6131f783612ace565b9050613202816132d8565b805461321f90600160481b90046001600160401b03166001614c0f565b81546001600160401b03918216600160481b90810267ffffffffffffffff60481b19909216919091178084556040515f9361327793889304169060200191825260c01b6001600160c01b031916602082015260280190565b60405160208183030381529060405280519060200120905080847f7153f9357c8ea496bba60bf82e67143e27b64462b49041f8e689e1b05728f84f845f0160099054906101000a90046001600160401b0316866040516120af9291906155a8565b7e96e2f02350077f4ff1746770dbe5db3c04b7db2c8763c8fc21bf66b35e96ab80545f9060ff1660018111156133105761331061453f565b14158061333257505f825460ff16600181111561332f5761332f61453f565b14155b1561282757604051633ac4266d60e11b815260040160405180910390fd5b5f805f805f85875af1905080610b0557604051633d2cec6f60e21b815260040160405180910390fd5b5f6001600160a01b0382163f15801590610b865750506001600160a01b03163f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470141590565b606082156133ce575080610b86565b8151156102295781518083602001fd5b5f8183106133f8575f828152602084905260409020611f11565b5f838152602083905260409020611f11565b60605f80846001600160a01b0316639bb66b287f000000000000000000000000ad4a6d5dae036fe490b34c08c7085c6b2ae69969866040518363ffffffff1660e01b815260040161345c929190615766565b5f604051808303815f875af1158015613477573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261349e9190810190615787565b915091506134ac82826133bf565b95945050505050565b5f6134c9670de0b6b3a76400005f196157cf565b8211156134ec57604051631cd951a760e01b815260048101839052602401612766565b50670de0b6b3a76400000290565b5f8061350d670de0b6b3a76400006134b5565b90505f61354f61353f7f000000000000000000000000000000000000000000000000000000000000000c60ff166134b5565b613549600a6134b5565b9061374b565b90505f613572836135668461356c8b838c8c61385b565b9061385b565b90613869565b905061357d81613880565b979650505050505050565b60605f6135968460206157ee565b63ffffffff166001600160401b038111156135b3576135b36147de565b6040519080825280601f01601f1916602001820160405280156135dd576020820181803683370190505b5090505f5b8463ffffffff168163ffffffff1610156136ad575f5b60208163ffffffff1610156136a45787878363ffffffff1681811061361f5761361f61557c565b905060200201358163ffffffff166020811061363d5761363d61557c565b1a60f81b838261364e8560206157ee565b613658919061580e565b63ffffffff168151811061366e5761366e61557c565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191690815f1a9053506001016135f8565b506001016135e2565b50630e02a00760e31b5f806136c187613893565b8465ff000000ff00600889811b91821664ff000000ff918b901c91821617601090811b63ff0000009390931662ff00009290921691909117901c17602081811b6bffffffffffffffff000000001691901c63ffffffff161760c01b6040516020016137319695949392919061582b565b604051602081830303815290604052915050949350505050565b5f8282818303613774578015613761575f61376b565b670de0b6b3a76400005b92505050610b86565b670de0b6b3a7640000820361379557670de0b6b3a764000092505050610b86565b805f036137ae57670de0b6b3a764000092505050610b86565b670de0b6b3a764000081036137c7578492505050610b86565b670de0b6b3a76400008211156137f8576137f16137ec6137e687613a01565b8661385b565b613b28565b9250613853565b5f613818613815846ec097ce7bc90715b34b9f10000000006157cf565b90565b90505f6138306137ec61382a84613a01565b8861385b565b905061384e613815826ec097ce7bc90715b34b9f10000000006157cf565b945050505b505092915050565b5f611f116138158484613b7c565b5f611f1161381584670de0b6b3a764000085613c2e565b5f610b86670de0b6b3a7640000836157cf565b6060603f8263ffffffff16116138d057604051603f60fa1b60fa84901b1660208201526021015b6040516020818303038152906040529050919050565b613fff8263ffffffff16116139475761390c6138f86403fffffffc600285901b16600161580e565b600881811b62ffff001691901c60ff161790565b6040516020016138ba919060f09190911b7fffff00000000000000000000000000000000000000000000000000000000000016815260020190565b633fffffff8263ffffffff16116139b95761399660028363ffffffff16901b6002613972919061580e565b600881811c62ff00ff1663ff00ff009290911b9190911617601081811c91901b1790565b6040516020016138ba919060e09190911b6001600160e01b031916815260040190565b604051600360f81b60208201526001600160e01b0319600884811c62ff00ff1663ff00ff009186901b9190911617601081811c91901b1760e01b1660218201526025016138ba565b5f81670de0b6b3a7640000811015613a2f5760405163036d32ef60e41b815260048101849052602401612766565b5f613ab0670de0b6b3a7640000830460016001600160801b03821160071b91821c6001600160401b03811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810282821c670de0b6b3a763ffff198101613ad95750949350505050565b671bc16d674ec800006706f05b59d3b200005b8015613b1c57670de0b6b3a7640000838002049250818310613b14579283019260019290921c915b60011c613aec565b50919695505050505050565b5f81680a688906bd8affffff811115613b575760405163b3b6ba1f60e01b815260048101849052602401612766565b5f613b6e670de0b6b3a7640000604084901b6157cf565b905061312761381582613cfd565b5f80805f19848609848602925082811083820303915050805f03613bad5750670de0b6b3a764000090049050610b86565b670de0b6b3a76400008110613bdf57604051635173648d60e01b81526004810186905260248101859052604401612766565b5f670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b5f80805f19858709858702925082811083820303915050805f03613c6557838281613c5b57613c5b6157bb565b0492505050611f11565b838110613c9657604051630c740aef60e31b8152600481018790526024810186905260448101859052606401612766565b5f8486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091025f889003889004909101858311909403939093029303949094049190911702949350505050565b7780000000000000000000000000000000000000000000000067ff00000000000000821615613e1e57678000000000000000821615613d455768016a09e667f3bcc9090260401c5b674000000000000000821615613d64576801306fe0a31b7152df0260401c5b672000000000000000821615613d83576801172b83c7d517adce0260401c5b671000000000000000821615613da25768010b5586cf9890f62a0260401c5b670800000000000000821615613dc1576801059b0d31585743ae0260401c5b670400000000000000821615613de057680102c9a3e778060ee70260401c5b670200000000000000821615613dff5768010163da9fb33356d80260401c5b670100000000000000821615613e1e57680100b1afa5abcbed610260401c5b66ff000000000000821615613f1d576680000000000000821615613e4b5768010058c86da1c09ea20260401c5b6640000000000000821615613e69576801002c605e2e8cec500260401c5b6620000000000000821615613e8757680100162f3904051fa10260401c5b6610000000000000821615613ea5576801000b175effdc76ba0260401c5b6608000000000000821615613ec357680100058ba01fb9f96d0260401c5b6604000000000000821615613ee15768010002c5cc37da94920260401c5b6602000000000000821615613eff576801000162e525ee05470260401c5b6601000000000000821615613f1d5768010000b17255775c040260401c5b65ff00000000008216156140135765800000000000821615613f48576801000058b91b5bc9ae0260401c5b65400000000000821615613f6557680100002c5c89d5ec6d0260401c5b65200000000000821615613f825768010000162e43f4f8310260401c5b65100000000000821615613f9f57680100000b1721bcfc9a0260401c5b65080000000000821615613fbc5768010000058b90cf1e6e0260401c5b65040000000000821615613fd9576801000002c5c863b73f0260401c5b65020000000000821615613ff657680100000162e430e5a20260401c5b65010000000000821615614013576801000000b1721835510260401c5b64ff000000008216156141005764800000000082161561403c57680100000058b90c0b490260401c5b6440000000008216156140585768010000002c5c8601cc0260401c5b642000000000821615614074576801000000162e42fff00260401c5b6410000000008216156140905768010000000b17217fbb0260401c5b6408000000008216156140ac576801000000058b90bfce0260401c5b6404000000008216156140c857680100000002c5c85fe30260401c5b6402000000008216156140e45768010000000162e42ff10260401c5b64010000000082161561410057680100000000b17217f80260401c5b63ff0000008216156141e45763800000008216156141275768010000000058b90bfc0260401c5b6340000000821615614142576801000000002c5c85fe0260401c5b632000000082161561415d57680100000000162e42ff0260401c5b6310000000821615614178576801000000000b17217f0260401c5b630800000082161561419357680100000000058b90c00260401c5b63040000008216156141ae5768010000000002c5c8600260401c5b63020000008216156141c9576801000000000162e4300260401c5b63010000008216156141e45768010000000000b172180260401c5b62ff00008216156142bf5762800000821615614209576801000000000058b90c0260401c5b6240000082161561422357680100000000002c5c860260401c5b6220000082161561423d5768010000000000162e430260401c5b6210000082161561425757680100000000000b17210260401c5b620800008216156142715768010000000000058b910260401c5b6204000082161561428b576801000000000002c5c80260401c5b620200008216156142a557680100000000000162e40260401c5b620100008216156142bf576801000000000000b1720260401c5b61ff00821615614391576180008216156142e257680100000000000058b90260401c5b6140008216156142fb5768010000000000002c5d0260401c5b612000821615614314576801000000000000162e0260401c5b61100082161561432d5768010000000000000b170260401c5b610800821615614346576801000000000000058c0260401c5b61040082161561435f57680100000000000002c60260401c5b61020082161561437857680100000000000001630260401c5b61010082161561439157680100000000000000b10260401c5b60ff82161561445a5760808216156143b257680100000000000000590260401c5b60408216156143ca576801000000000000002c0260401c5b60208216156143e257680100000000000000160260401c5b60108216156143fa576801000000000000000b0260401c5b600882161561441257680100000000000000060260401c5b600482161561442a57680100000000000000030260401c5b600282161561444257680100000000000000010260401c5b600182161561445a57680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b61032c8061589d83390190565b60405180606001604052805f63ffffffff1681526020016144b060405180604001604052805f81526020015f81525090565b8152602001606081525090565b5f80602083850312156144ce575f80fd5b82356001600160401b03808211156144e4575f80fd5b818501915085601f8301126144f7575f80fd5b813581811115614505575f80fd5b866020828501011115614516575f80fd5b60209290920196919550909350505050565b5f60208284031215614538575f80fd5b5035919050565b634e487b7160e01b5f52602160045260245ffd5b60208101600283106145675761456761453f565b91905290565b6001600160a01b03811681146108da575f80fd5b8035612b248161456d565b5f6020828403121561459c575f80fd5b8135611f118161456d565b5f8083601f8401126145b7575f80fd5b5081356001600160401b038111156145cd575f80fd5b6020830191508360208260051b85010111156145e7575f80fd5b9250929050565b5f805f8060608587031215614601575f80fd5b84356001600160401b0380821115614617575f80fd5b90860190610100828903121561462b575f80fd5b90945060208601359080821115614640575f80fd5b61464c888389016145a7565b90955093506040870135915080821115614664575f80fd5b5085016101208188031215614677575f80fd5b939692955090935050565b63ffffffff811681146108da575f80fd5b8035612b2481614682565b6001600160801b03811681146108da575f80fd5b8035612b248161469e565b5f805f805f60a086880312156146d1575f80fd5b85356146dc8161456d565b945060208601356146ec81614682565b935060408601356001600160401b03811115614706575f80fd5b860160408189031215614717575f80fd5b925060608601356147278161469e565b915060808601356147378161469e565b809150509295509295909350565b5f805f60608486031215614757575f80fd5b83356147628161456d565b9250602084013561477281614682565b915060408401356147828161469e565b809150509250925092565b5f805f6040848603121561479f575f80fd5b83356001600160401b038111156147b4575f80fd5b6147c0868287016145a7565b909450925050602084013565ffffffffffff81168114614782575f80fd5b634e487b7160e01b5f52604160045260245ffd5b606081018181106001600160401b0382111715614811576148116147de565b60405250565b604081018181106001600160401b0382111715614811576148116147de565b602081018181106001600160401b0382111715614811576148116147de565b608081018181106001600160401b0382111715614811576148116147de565b601f8201601f191681016001600160401b0381118282101715614899576148996147de565b6040525050565b60405161014081016001600160401b03811182821017156148c3576148c36147de565b60405290565b5f606082840312156148d9575f80fd5b6040516148e5816147f2565b8091508235815260208301356148fa8161456d565b6020820152604092830135920191909152919050565b5f60608284031215614920575f80fd5b611f1183836148c9565b5f6040828403121561493a575f80fd5b60405161494681614817565b80915082518152602083015160208201525092915050565b5f6001600160401b03821115614976576149766147de565b50601f01601f191660200190565b5f82601f830112614993575f80fd5b815161499e8161495e565b6040516149ab8282614874565b8281528560208487010111156149bf575f80fd5b8260208601602083015e5f92810160200192909252509392505050565b5f602082840312156149ec575f80fd5b81516001600160401b0380821115614a02575f80fd5b9083019060808286031215614a15575f80fd5b604051614a21816147f2565b8251614a2c81614682565b8152614a3b866020850161492a565b6020820152606083015182811115614a51575f80fd5b614a5d87828601614984565b60408301525095945050505050565b5f60608284031215614a7c575f80fd5b604051614a88816147f2565b823581526020830135614a9a8161469e565b60208201526040928301359281019290925250919050565b803560028110612b24575f80fd5b5f60608284031215614ad0575f80fd5b604051614adc816147f2565b8235815260208301356020820152614af660408401614ab2565b60408201529392505050565b5f82601f830112614b11575f80fd5b8135614b1c8161495e565b604051614b298282614874565b828152856020848701011115614b3d575f80fd5b826020860160208301375f92810160200192909252509392505050565b5f60208284031215614b6a575f80fd5b81356001600160401b0380821115614b80575f80fd5b9083019060608286031215614b93575f80fd5b604051614b9f816147f2565b8235614baa8161456d565b815260208381013590820152604083013582811115614bc7575f80fd5b614a5d87828601614b02565b80518015158114612b24575f80fd5b5f60208284031215614bf2575f80fd5b611f1182614bd3565b634e487b7160e01b5f52601160045260245ffd5b6001600160401b03818116838216019080821115614c2f57614c2f614bfb565b5092915050565b80356001600160401b0381168114612b24575f80fd5b5f60208284031215614c5c575f80fd5b611f1182614c36565b5f6001600160401b03808316818103614c8057614c80614bfb565b6001019392505050565b803560238110612b24575f80fd5b60238110614ca857614ca861453f565b9052565b5f808335601e19843603018112614cc1575f80fd5b83016020810192503590506001600160401b03811115614cdf575f80fd5b8036038213156145e7575f80fd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b60208152813560208201525f614d2d60208401614c36565b6001600160401b038082166040850152614d4960408601614c8a565b9150614d586060850183614c98565b614d656060860186614cac565b9250610100806080870152614d7f61012087018584614ced565b935082614d8e60808901614c36565b1660a087015260a087013560c087015260c087013560e087015260e0870135818701525050508091505092915050565b80820180821115610b8657610b86614bfb565b5f60208284031215614de1575f80fd5b611f1182614c8a565b5f808335601e19843603018112614dff575f80fd5b8301803591506001600160401b03821115614e18575f80fd5b6020019150368190038213156145e7575f80fd5b602081525f611f0e602083018486614ced565b5f60033d11156138155760045f803e505f5160e01c90565b5f60443d1015614e645790565b6040516003193d81016004833e81513d6001600160401b038160248401118184111715614e9357505050505090565b8285019150815181811115614eab5750505050505090565b843d8701016020828501011115614ec55750505050505090565b614ed460208286010187614874565b509095945050505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611f116020830184614edf565b60208101610b868284614c98565b81810381811115610b8657610b86614bfb565b8082028115828204841417610b8657610b86614bfb565b5f60208284031215614f67575f80fd5b81356001600160401b0380821115614f7d575f80fd5b9083019060408286031215614f90575f80fd5b604051614f9c81614817565b82358152602083013582811115614fb1575f80fd5b614fbd87828601614b02565b60208301525095945050505050565b5f8060408385031215614fdd575f80fd5b825160018110614feb575f80fd5b60208401519092506001600160401b03811115615006575f80fd5b61501285828601614984565b9150509250929050565b5f805f6060848603121561502e575f80fd5b83516150398161456d565b602085015190935061504a8161456d565b60408501519092506147828161469e565b5f610140828403121561506c575f80fd5b6150746148a0565b61507d83614ab2565b815261508b602084016146b2565b6020820152604083013560408201526150a660608401614693565b6060820152608083013560808201526150c160a084016146b2565b60a08201526150d260c084016146b2565b60c082015260e083013560e08201526101008084013581830152506101206150fb818501614581565b908201529392505050565b6001600160a01b0388811682528716602082015263ffffffff8616604082015260e060608201525f85356003811061513c575f80fd5b60e083015261514e6020870187614cac565b604061010085015261516561012085018284614ced565b6001600160801b03978816608086015295871660a0850152505050921660c090920191909152949350505050565b5f606082840312156151a3575f80fd5b6040516151af816147f2565b82356151ba8161469e565b81526020830135614a9a8161469e565b5f604082840312156151da575f80fd5b611f11838361492a565b5f602082840312156151f4575f80fd5b60405161520081614836565b61520983614ab2565b81529392505050565b5f60808284031215615222575f80fd5b60405161522e81614855565b8235815260208301356152408161456d565b602082015260408301356152538161456d565b604082015260608301356152668161469e565b60608201529392505050565b803560ff81168114612b24575f80fd5b5f60208284031215615292575f80fd5b81356001600160401b03808211156152a8575f80fd5b90830190608082860312156152bb575f80fd5b6040516152c781614855565b823581526020830135828111156152dc575f80fd5b6152e887828601614b02565b6020830152506040830135828111156152ff575f80fd5b61530b87828601614b02565b60408301525061531d60608401615272565b606082015295945050505050565b848152608060208201525f6153436080830186614edf565b82810360408401526153558186614edf565b91505060ff8316606083015295945050505050565b5f6040828403121561537a575f80fd5b60405161538681614817565b8235815261539660208401614ab2565b60208201529392505050565b5f602082840312156153b2575f80fd5b6040516153be81614836565b9135825250919050565b5f805f805f8060c087890312156153dd575f80fd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b5f60208284031215615417575f80fd5b8151611f118161456d565b8781528660208201526001600160a01b03861660408201528460608201528360808201528260a082015260e060c08201525f61546160e0830184614edf565b9998505050505050505050565b5f602080838503121561547f575f80fd5b82356001600160401b0380821115615495575f80fd5b818501915060408083880312156154aa575f80fd5b80516154b581614817565b8335815284840135838111156154c9575f80fd5b80850194505087601f8501126154dd575f80fd5b8335838111156154ef576154ef6147de565b82519350615502868260051b0185614874565b80845260609081028501860190868501908a83111561551f575f80fd5b958701955b828710156155685780878c03121561553a575f80fd5b8451615545816147f2565b873581528888013589820152858801358682015282529586019590870190615524565b505050938401919091525090949350505050565b634e487b7160e01b5f52603260045260245ffd5b828152604060208201525f611f0e6040830184614edf565b6001600160401b0383168152604060208201525f611f0e6040830184614edf565b5f81518060208401855e5f93019283525090919050565b5f611f1182846155c9565b5f808335601e19843603018112615600575f80fd5b83016020810192503590506001600160401b0381111561561e575f80fd5b8060051b36038213156145e7575f80fd5b8183525f7f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83111561565f575f80fd5b8260051b80836020870137939093016020019392505050565b6001600160a01b03851681526001600160e01b031984166020820152604081018390526080606082015260ff6156ad83615272565b1660808201525f60208301356156c281614682565b63ffffffff80821660a0850152604085013560c08501526001600160401b036156ed60608701614c36565b1660e08501526080850135915061570382614682565b61010081831681860152610120925060a08601358386015261572860c08701876155eb565b9250836101408701526157406101a08701848361562f565b60e088013561016088015291909601356101809095019490945250919695505050505050565b6001600160a01b0383168152604060208201525f611f0e6040830184614edf565b5f8060408385031215615798575f80fd5b6157a183614bd3565b915060208301516001600160401b03811115615006575f80fd5b634e487b7160e01b5f52601260045260245ffd5b5f826157e957634e487b7160e01b5f52601260045260245ffd5b500490565b63ffffffff81811683821602808216919082811461385357613853614bfb565b63ffffffff818116838216019080821115614c2f57614c2f614bfb565b6001600160e01b0319871681527fff000000000000000000000000000000000000000000000000000000000000008681166004830152851660058201525f61587f61587960068401876155c9565b856155c9565b6001600160c01b031993909316835250506008019594505050505056fe60c0604052348015600e575f80fd5b5060405161032c38038061032c833981016040819052602b916036565b6080523360a052604c565b5f602082840312156045575f80fd5b5051919050565b60805160a0516102ba6100725f395f81816052015261010d01525f60cf01526102ba5ff3fe608060405260043610610036575f3560e01c8063338c5371146100415780639bb66b2814610091578063e905182a146100be575f80fd5b3661003d57005b5f80fd5b34801561004c575f80fd5b506100747f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561009c575f80fd5b506100b06100ab3660046101ae565b6100ff565b604051610088929190610237565b3480156100c9575f80fd5b506100f17f000000000000000000000000000000000000000000000000000000000000000081565b604051908152602001610088565b5f6060336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461014a576040516282b42960e81b815260040160405180910390fd5b846001600160a01b03168484604051610164929190610275565b5f60405180830381855af49150503d805f811461019c576040519150601f19603f3d011682016040523d82523d5f602084013e6101a1565b606091505b5091509150935093915050565b5f805f604084860312156101c0575f80fd5b83356001600160a01b03811681146101d6575f80fd5b9250602084013567ffffffffffffffff808211156101f2575f80fd5b818601915086601f830112610205575f80fd5b813581811115610213575f80fd5b876020828501011115610224575f80fd5b6020830194508093505050509250925092565b8215158152604060208201525f82518060408401528060208501606085015e5f606082850101526060601f19601f8301168401019150509392505050565b818382375f910190815291905056fea26469706673582212207f8ca0f108479aa0bdad395f48bcd618386aaeddd23d9abd5fbee2190be446a364736f6c63430008190033a264697066735822122033e86ee408abcef1e18afebec9577f10d63564b3a2e69e1abd062b148ce3d82c64736f6c63430008190033
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.