Verified contractPartialMIT
IntentChainer
Address0x96f7dba7e587f359a8f585c335fe510e4dc9bcc0
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.27
- Same code
Only this contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,940,283
- Creation transaction
- 0xa983e849f8…697d8a5030
11 files
- contracts/chain/IntentChainer.solmain18.89 KB
- contracts/chain/IntentTemplate.sol11.57 KB
- contracts/chain/SolanaVault.sol5.05 KB
- contracts/interfaces/IIntentSource.sol17.03 KB
- contracts/types/Intent.sol2.69 KB
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- node_modules/@openzeppelin/contracts/utils/Address.sol6.26 KB
- node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol3.24 KB
- node_modules/@openzeppelin/contracts/utils/math/Math.sol15.12 KB
contracts/chain/IntentChainer.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IIntentSource} from "../interfaces/IIntentSource.sol";
import {Reward} from "../types/Intent.sol";
import {IntentTemplate} from "./IntentTemplate.sol";
/**
* @title IntentChainer
* @notice Publishes a second intent whose amount is not known until the first intent executes.
* @dev Called as the last {Call} of an executing intent (intent1), at which point this contract holds the
* output of whatever intent1's earlier calls produced -- typically a DEX swap that named this contract
* as its recipient. It measures that balance -- the ONE runtime measurement in the whole flow -- and
* derives from it the two amounts of a second intent (intent2) whose every other field was fixed when
* intent1 was signed: `amountIn` is escrowed as intent2's reward, and
* `amountOut = ceil(amountIn * scale / WAD)` is available alongside amountIn to the route's typed
* items. A conventional amount-only route uses amountOut as its solver delivery obligation; scale
* carries the proportional margin and unit conversion. Nested vault items render downstream
* intents from that same measurement and splice their recipients into the route as data.
*
* WHY THIS IS SAFE WITHOUT ACCESS CONTROL. Route calls reach every contract through the Portal's single
* shared {Executor}, which any fulfiller of any intent drives permissionlessly, so `msg.sender` proves
* only that "some route call is running" -- never whose. The authorization anchor is instead intent1's
* own hash: the entire {Order}, including intent2's route bytes and `reward.creator`, rides inside
* `intent1.route.calls[k].data`, which is covered by `keccak256(abi.encode(route))`, which is covered by
* the `intentHash` that {Inbox} re-derives and checks before executing anything. A solver cannot alter
* the order it is executing. The residual exposure is a balance donated to this contract out-of-band,
* which the next caller sweeps into their own intent; the intended flow never leaves a balance at rest.
*
* WHY THIS CONTRACT IS NOT PAYABLE AND HAS NO `receive()`. Every {IIntentSource} funding entry point
* (`fund`, `fundFor`, `publishAndFund`, `publishAndFundFor`, `open`, `openFor`) ends in
* `Refund.excessNative()`, which forwards the Portal's ENTIRE native balance to `msg.sender`. Reached
* re-entrantly from inside a route call that is what this contract would be, so it would silently
* capture the solver's in-flight ETH. This contract therefore touches `publish` and nothing else.
*
* PUBLISH IS OPTIONAL; SETTLEMENT CHECKS ARE NOT. The local Portal predicts the local reward vault.
* Its status is checked even when publish is false. Publishing emits the completed route and
* reward for discovery; it does not control where value moves. Funding is deliberately NOT called:
* withdraw accepts Status.Initial and pays from the live vault balance. Rendered remote vaults are
* only bytes inside the route and cannot redirect the local push.
*/
contract IntentChainer is ReentrancyGuard {
using SafeERC20 for IERC20;
// ============ Types ============
/**
* @notice A locally funded child intent with a fully committed, dynamically rendered route.
* @dev The entire template program, including downstream rewards, derivation tags/configs and node
* references, rides inside intent1's hashed calldata. Nested vaults are addresses inserted in
* the route, NOT recipients of this contract's local transfer. No new custody or approvals.
* @param publish Whether to publish intent2 for discoverability. Settlement checks are unconditional.
* @param portal The LOCAL Portal whose reward vault receives the measured token.
* @param token The single local ERC20 measured and escrowed.
* @param destination Intent2's route execution chain.
* @param template Dependency-first downstream intents and the root route's segments/items.
* @param reward Local reward: exactly one leg in token, no native amount. Its amount is overwritten.
* @param scale WAD-denominated transform: amountOut = ceil(amountIn * scale / WAD). Carries both
* unit conversion and proportional spread (1e18 identity, 1e30 for 6->18, 1e6 for 18->6).
* Amount items explicitly select amountIn or amountOut and any further transform.
* @param minAmountIn Reject a measured balance below this floor, reverting the outer fulfillment.
*/
struct Order {
bool publish;
address portal;
address token;
uint64 destination;
IntentTemplate.Program template;
Reward reward;
uint256 scale;
uint256 minAmountIn;
}
// ============ Constants ============
/// @notice Fixed-point denominator for {Order.scale}.
/// @dev Decimal, not binary, so every power-of-ten unit conversion is exact in both directions. Matches
/// the WAD convention v3 adopts for `RewardToken.rate`.
uint256 public constant WAD = 1e18;
/// @notice Per-template item bound; nodes and aggregate rendered bytes are also bounded.
uint256 public constant MAX_ITEMS = IntentTemplate.MAX_ITEMS;
/// @notice Minimum time intent2's reward deadline must clear `block.timestamp` by.
/// @dev Intent2's deadlines are fixed when intent1 is signed, but intent1 may be fulfilled at any point
/// up to its own route deadline. Publishing an intent2 that is already expired is recoverable (the
/// escrow refunds to `reward.creator` after the deadline) but burns intent1 for nothing, so it fails
/// loudly here instead.
uint64 public constant MIN_DEADLINE_BUFFER = 5 minutes;
// ============ Events ============
/**
* @notice A second intent was published and funded from a measured balance.
* @param intentHash Intent2's hash.
* @param vault Intent2's deterministic vault, which now holds `amountIn`.
* @param token The measured token.
* @param amountIn The measured amount, escrowed as intent2's reward.
* @param amountOut The scaled amount available to template items selecting AmountSource.Output.
* @param published Whether this call also emitted the Portal's canonical `IntentPublished`. An indexer
* that sees `false` must reconstruct intent2 from the committed order rather than wait for it.
*/
event IntentChained(
bytes32 indexed intentHash,
address indexed vault,
address indexed token,
uint256 amountIn,
uint256 amountOut,
bool published
);
// ============ Errors ============
/// @notice `order.portal` is the zero address.
error InvalidPortal();
/// @notice The reward does not carry exactly one leg.
error InvalidRewardLegCount(uint256 count);
/// @notice The reward leg names a token this contract did not measure.
error RewardTokenMismatch(address expected, address actual);
/// @notice The reward declares a native amount. Native rewards are out of scope; see the contract NatSpec.
error NativeRewardNotSupported();
/// @notice Nothing was measured -- intent1's earlier calls delivered no `token` to this contract.
error ZeroAmount();
/// @notice The measured amount is below the order's floor.
error AmountBelowFloor(uint256 amountIn, uint256 minAmountIn);
/// @notice {Order.scale} is zero, which would oblige the solver to deliver nothing.
error InvalidScale();
/// @notice Intent2's reward deadline is in the past or inside {MIN_DEADLINE_BUFFER}.
error DeadlineTooSoon(uint64 deadline, uint256 timestamp);
/// @notice The transfer moved less into the vault than was declared, e.g. a fee-on-transfer token.
error PushShortfall(address vault, uint256 expected, uint256 delivered);
/// @notice Intent2's hash has already settled, so a push into its vault could not be paid out.
/// @dev Checked explicitly rather than inherited from `publish` reverting, because publish is optional.
error IntentAlreadySettled(bytes32 intentHash, IIntentSource.Status status);
/// @notice Intent2's vault already holds at least the amount being pushed.
/// @dev A salt collision: the same order resolving to a hash that has already been chained. Nothing
/// legitimate pre-funds this address, since it depends on the measured amount. See
/// {_pushAndVerify} for why `publish` does not catch this on its own.
error VaultAlreadyFunded(address vault, uint256 balance);
// ============ External Functions ============
/**
* @notice Measure this contract's balance of one token and publish a second intent escrowing it.
* @dev Render nested templates and resolve/check the LOCAL vault before any value moves. Optional
* publication also precedes the transfer. Every validation failure reverts the outer intent
* whole. Remote recipients are populated route data for a later fulfillment; chain itself
* performs no remote transfer or CCTP burn.
*
* `publish` does NOT reject every colliding hash, and the gap is the operating window rather than
* an edge: `IntentSource._validatePublish` rejects only `Withdrawn` and `Refunded`, and publishing
* an `Initial` or `Funded` intent is deliberately idempotent. Because this contract never calls
* `fund`, intent2 sits at `Initial` for its whole useful life -- so a second `chain` on a colliding
* order would re-publish and push a second `amountIn` into the same vault, merging two chains into
* one intent with no signal. {_pushAndVerify} is what actually closes that.
* @param order The committed intent2 template. See {Order}.
* @return intentHash Intent2's hash.
* @return vault Intent2's vault, now holding the measured amount.
* @return amountIn The measured amount, escrowed as intent2's reward.
* @return amountOut The scaled destination obligation available to template amount items.
*/
function chain(
Order calldata order
)
external
nonReentrant
returns (
bytes32 intentHash,
address vault,
uint256 amountIn,
uint256 amountOut
)
{
_validate(order);
(amountIn, amountOut) = _measure(order);
Reward memory reward = order.reward;
reward.tokens[0].amount = amountIn;
bytes memory route = IntentTemplate.render(
order.template,
amountIn,
amountOut
);
IIntentSource portal = IIntentSource(order.portal);
// Resolved WITHOUT publishing. `publish` returns the vault too, but making the flag optional means
// neither the address nor the settled check may depend on it.
(intentHash, , ) = portal.getIntentHash(
order.destination,
route,
reward
);
vault = portal.intentVaultAddress(order.destination, route, reward);
_requireNotSettled(portal, intentHash);
if (order.publish) {
portal.publish(order.destination, route, reward);
}
_pushAndVerify(order.token, vault, amountIn);
emit IntentChained(
intentHash,
vault,
order.token,
amountIn,
amountOut,
order.publish
);
}
// ============ Internal Functions ============
/**
* @notice Reject a hash that has already paid out or refunded.
* @dev `IntentSource._validatePublish` refuses `Withdrawn` and `Refunded`, and inheriting that side
* effect would leave the terminal case unguarded whenever `order.publish` is false. Asserted
* directly instead, so the protection holds either way. The `Initial`-state collision -- the one
* that actually occurs, since this contract never funds intent2 -- is caught in {_pushAndVerify}.
* @param portal The Portal to ask.
* @param intentHash Intent2's hash.
*/
function _requireNotSettled(
IIntentSource portal,
bytes32 intentHash
) internal view {
IIntentSource.Status status = portal.getRewardStatus(intentHash);
if (
status != IIntentSource.Status.Initial &&
status != IIntentSource.Status.Funded
) {
revert IntentAlreadySettled(intentHash, status);
}
}
/**
* @notice Move the measured balance into intent2's vault, bracketing the transfer with the two checks
* that make it safe.
* @dev Reading the vault BEFORE the transfer does the work `publish` cannot. `_validatePublish` lets an
* `Initial` intent be re-published, and intent2 is `Initial` for its whole useful life because this
* contract never funds it -- so a colliding order would otherwise top the same vault up a second
* time, consuming a second intent1 and producing no second delivery. Nothing legitimate can
* pre-fund this address: it depends on the measured amount, so it is unknowable until this call
* runs. A balance already covering the push therefore means the hash is not fresh.
*
* Comparing a DELTA afterwards, rather than the absolute balance, is what keeps the shortfall check
* honest. The vault address is computable by anyone reading intent1's calldata, so an absolute
* comparison could be satisfied by a donation instead of by this transfer -- masking exactly the
* fee-on-transfer case the check exists to catch.
* @param token The measured token.
* @param vault Intent2's vault.
* @param amountIn The amount to push.
*/
function _pushAndVerify(
address token,
address vault,
uint256 amountIn
) internal {
uint256 balanceBefore = IERC20(token).balanceOf(vault);
if (balanceBefore >= amountIn) {
revert VaultAlreadyFunded(vault, balanceBefore);
}
IERC20(token).safeTransfer(vault, amountIn);
uint256 delivered = IERC20(token).balanceOf(vault) - balanceBefore;
if (delivered < amountIn) {
revert PushShortfall(vault, amountIn, delivered);
}
}
/**
* @notice Measure the held balance and derive the two amounts intent2 is built from.
* @dev Ceil rounding serves two purposes. It rounds toward the USER, since `amountOut` is the solver's
* delivery floor. And it guarantees a non-zero obligation: with `amountIn >= 1` and `scale >= 1`
* the quotient is strictly positive, so no order can oblige a solver to deliver nothing while
* collecting the whole escrow. That is why there is no zero-obligation check.
*
* {Math-mulDiv} is used for that ROUNDING MODE, not for its wide intermediate, and the distinction
* is worth stating because it is easy to get backwards. Precision here is fixed by {WAD} alone --
* `ceil(amountIn * scale / WAD)` is one exact integer, and no intermediate width changes it by a
* unit. The 512-bit path buys only RANGE, and the range is not close to binding: overflow of a
* plain `amountIn * scale` needs the product to reach `2^256`, which on a 6-to-18 lane
* (`scale = 1e30`) means an `amountIn` above `1.16e47` -- some seventeen orders of magnitude past
* an 18-decimal token with a trillion-unit supply. Under checked arithmetic that case would revert
* rather than wrap in any event.
*
* What it does earn is a ceiling with no overflow edge of its own. The hand-rolled form,
* `(amountIn * scale + WAD - 1) / WAD`, introduces exactly the boundary overflow the plain
* expression does not have; `mulDiv` adds its increment after the division instead.
* @param order The validated order.
* @return amountIn The measured balance, escrowed as intent2's reward.
* @return amountOut The scaled destination obligation.
*/
function _measure(
Order calldata order
) internal view returns (uint256 amountIn, uint256 amountOut) {
amountIn = IERC20(order.token).balanceOf(address(this));
if (amountIn == 0) {
revert ZeroAmount();
}
if (amountIn < order.minAmountIn) {
revert AmountBelowFloor(amountIn, order.minAmountIn);
}
amountOut = Math.mulDiv(amountIn, order.scale, WAD, Math.Rounding.Ceil);
}
/**
* @notice Rejects a malformed order before anything is measured or moved.
* @param order The order to validate.
*/
function _validate(Order calldata order) internal view {
if (order.portal == address(0)) revert InvalidPortal();
IntentTemplate.validateShape(order.template.route);
// A zero scale would publish an intent obliging the solver to deliver nothing while still
// collecting the whole escrow.
if (order.scale == 0) {
revert InvalidScale();
}
// Exactly one leg, in the measured token. A leg in any other token could never be funded from here --
// the vault address is unknowable in advance, so nothing else can pre-fund it -- and once such an
// intent is proven its vault is bricked: `_validateRefund` reverts `IntentNotClaimed` for as long as
// the proof stands, while `recoverToken` refuses reward tokens.
if (order.reward.tokens.length != 1) {
revert InvalidRewardLegCount(order.reward.tokens.length);
}
if (order.reward.tokens[0].token != order.token) {
revert RewardTokenMismatch(
order.token,
order.reward.tokens[0].token
);
}
// A native reward would make this contract's own funding path payable and drag in the NATIVE_ERC20
// alias guard, `Vault.withdraw`'s `NativeTransferFailed` revert against a contract claimant, and
// `Vault.refund`'s discarded native call. None of it is needed for a token-in/token-out chain.
if (order.reward.nativeAmount != 0) {
revert NativeRewardNotSupported();
}
if (order.reward.deadline < block.timestamp + MIN_DEADLINE_BUFFER) {
revert DeadlineTooSoon(order.reward.deadline, block.timestamp);
}
}
}
contracts/chain/IntentTemplate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SolanaVault} from "./SolanaVault.sol";
/**
* @notice Deterministic, bounded rendering of amount and downstream-vault template items.
* @dev A program is a flattened tree: vaults are listed dependency-first, and a vault may reference
* only earlier vaults. The root route may reference any vault. Every route, reward, configuration,
* and reference is part of the calling order's calldata commitment. Rendering never reads a
* balance, calls a Portal, publishes an intent, or moves value. The only external calls are to
* fixed cryptographic precompiles for Solana derivation. All amounts derive from the same
* initial measurement. Remote recipients are DATA in the local child's route, not local payees.
*
* Route and reward templates contain the remote VM's exact serialization (ABI or Borsh). Rendering
* validates geometry and derivation parameters, not opaque route/reward semantics or deployed remote
* bytecode. Authors must verify token identifiers, deadlines, prover, fee treatment and deployment
* parameters. In particular, the remote reward must describe the amount that will actually arrive.
*/
library IntentTemplate {
uint256 internal constant WAD = 1e18;
uint256 internal constant MAX_VAULTS = 8;
uint256 internal constant MAX_ITEMS = 8;
uint256 internal constant MAX_RENDERED_BYTES = 32768;
enum ItemKind {
Invalid,
Amount,
Vault
}
enum AmountSource {
Invalid,
Input,
Output
}
enum VaultKind {
Invalid,
EvmCreate2,
SolanaAta
}
/// @dev Config is canonical abi.encode(AmountConfig) or abi.encode(uint256 vaultIndex).
struct Item {
ItemKind kind;
bytes config;
}
struct Template {
bytes[] segments;
Item[] items;
}
/// @dev The selected initial amount is multiplied by scale / WAD, rounding up, then encoded.
/// scale = WAD means no additional transform. Zero scale and truncating encodings revert.
struct AmountConfig {
AmountSource source;
uint256 scale;
uint8 width;
bool littleEndian;
}
struct VaultDerivation {
VaultKind kind;
bytes config;
}
/// @dev destination is the downstream intent's execution chain, NOT its reward-vault chain.
/// reward renders the entire encoded Reward, including any ABI tuple offset.
struct Vault {
uint64 destination;
Template route;
Template reward;
VaultDerivation derivation;
}
struct Program {
Vault[] vaults;
Template route;
}
/// @dev initCodeHash is keccak256(remote Proxy.creationCode || abi.encode(implementation)).
/// Both implementation and bytecode are remote parameters; local Proxy bytecode is never used.
/// Presence is checked, but the hash/implementation/deployment relationship cannot be attested
/// from this chain. Authors must obtain and commit the correct pair for the remote deployment.
struct EvmConfig {
address portal;
bytes1 prefix;
address implementation;
bytes32 initCodeHash;
}
/// @dev Both bumps are searched canonically on-chain, never accepted from order input.
struct SolanaConfig {
bytes32 portalProgramId;
bytes32 tokenProgramId;
bytes32 mint;
}
error TooManyVaults(uint256 count);
error TooManyItems(uint256 count);
error SegmentCountMismatch(uint256 segments, uint256 items);
error TemplateTooLarge();
error InvalidItemKind();
error InvalidVaultKind();
error InvalidAmountSource();
error InvalidConfigEncoding();
error InvalidAmountScale();
error InvalidAmountWidth(uint8 width);
error AmountDoesNotFit(uint256 amount, uint8 width);
error InvalidVaultReference(uint256 index, uint256 available);
error MissingPortal();
error MissingPrefix();
error MissingImplementation();
error MissingInitCodeHash();
/// @notice Render downstream intents first, then splice their recipients into the root route.
/// @dev The aggregate output budget covers ALL nested route/reward bytes plus the root route.
function render(
Program calldata program,
uint256 amountIn,
uint256 amountOut
) internal view returns (bytes memory route) {
uint256 count = program.vaults.length;
if (count > MAX_VAULTS) revert TooManyVaults(count);
bytes32[] memory recipients = new bytes32[](count);
uint256 remaining = MAX_RENDERED_BYTES;
for (uint256 i; i < count; ++i) {
Vault calldata vault = program.vaults[i];
bytes memory remoteRoute = _render(
vault.route,
recipients,
i,
amountIn,
amountOut,
remaining
);
remaining -= remoteRoute.length;
bytes memory remoteReward = _render(
vault.reward,
recipients,
i,
amountIn,
amountOut,
remaining
);
remaining -= remoteReward.length;
bytes32 intentHash = keccak256(
abi.encodePacked(
vault.destination,
keccak256(remoteRoute),
keccak256(remoteReward)
)
);
recipients[i] = _derive(intentHash, vault.derivation);
}
return
_render(
program.route,
recipients,
count,
amountIn,
amountOut,
remaining
);
}
/// @notice Derive an EVM/TRON remote vault from explicit, committed deployment parameters.
/// @dev Returns the 20-byte result LEFT-zero-padded to bytes32, suitable for CCTP mintRecipient.
/// No address(this), chain-id branch, assumed 0xff prefix, or local creation code is used.
function deriveEvm(
bytes32 intentHash,
EvmConfig memory config
) internal pure returns (bytes32) {
if (config.portal == address(0)) revert MissingPortal();
if (config.prefix == bytes1(0)) revert MissingPrefix();
if (config.implementation == address(0)) revert MissingImplementation();
if (config.initCodeHash == bytes32(0)) revert MissingInitCodeHash();
bytes32 digest = keccak256(
abi.encodePacked(
config.prefix,
config.portal,
intentHash,
config.initCodeHash
)
);
return bytes32(uint256(digest) & type(uint160).max);
}
function _derive(
bytes32 intentHash,
VaultDerivation calldata derivation
) private view returns (bytes32) {
if (derivation.kind == VaultKind.EvmCreate2) {
// Static schemas have a single canonical ABI encoding; exact length also rejects trailing data.
if (derivation.config.length != 128) revert InvalidConfigEncoding();
EvmConfig memory config = abi.decode(
derivation.config,
(EvmConfig)
);
if (keccak256(derivation.config) != keccak256(abi.encode(config)))
revert InvalidConfigEncoding();
return deriveEvm(intentHash, config);
}
if (derivation.kind == VaultKind.SolanaAta) {
if (derivation.config.length != 96) revert InvalidConfigEncoding();
SolanaConfig memory config = abi.decode(
derivation.config,
(SolanaConfig)
);
(, bytes32 ata, , ) = SolanaVault.derive(
intentHash,
config.portalProgramId,
config.tokenProgramId,
config.mint
);
return ata;
}
revert InvalidVaultKind();
}
/// @notice Validate one template's geometry without a measurement or allocation.
function validateShape(Template calldata template) internal pure {
uint256 count = template.items.length;
if (count > MAX_ITEMS) revert TooManyItems(count);
if (template.segments.length != count + 1) {
revert SegmentCountMismatch(template.segments.length, count);
}
}
function _render(
Template calldata template,
bytes32[] memory recipients,
uint256 available,
uint256 amountIn,
uint256 amountOut,
uint256 remaining
) private pure returns (bytes memory result) {
uint256 count = template.items.length;
validateShape(template);
// Bound copies before allocating any rendered output. Item widths are charged as they render.
uint256 literalSize;
for (uint256 i; i <= count; ++i) {
literalSize += template.segments[i].length;
if (literalSize > remaining) revert TemplateTooLarge();
}
remaining -= literalSize;
result = template.segments[0];
for (uint256 i; i < count; ++i) {
Item calldata item = template.items[i];
bytes memory value;
if (item.kind == ItemKind.Amount) {
value = _amount(item.config, amountIn, amountOut);
} else if (item.kind == ItemKind.Vault) {
if (item.config.length != 32) revert InvalidConfigEncoding();
uint256 index = abi.decode(item.config, (uint256));
// For a nested vault, this rejects self references, forward edges and cycles.
if (index >= available)
revert InvalidVaultReference(index, available);
value = abi.encode(recipients[index]);
} else {
revert InvalidItemKind();
}
if (value.length > remaining) revert TemplateTooLarge();
remaining -= value.length;
result = bytes.concat(result, value, template.segments[i + 1]);
}
}
function _amount(
bytes calldata encoded,
uint256 amountIn,
uint256 amountOut
) private pure returns (bytes memory result) {
if (encoded.length != 128) revert InvalidConfigEncoding();
AmountConfig memory config = abi.decode(encoded, (AmountConfig));
if (keccak256(encoded) != keccak256(abi.encode(config)))
revert InvalidConfigEncoding();
if (config.scale == 0) revert InvalidAmountScale();
if (config.width == 0 || config.width > 32)
revert InvalidAmountWidth(config.width);
uint256 amount;
if (config.source == AmountSource.Input) amount = amountIn;
else if (config.source == AmountSource.Output) amount = amountOut;
else revert InvalidAmountSource();
amount = Math.mulDiv(amount, config.scale, WAD, Math.Rounding.Ceil);
if (config.width < 32 && amount >> (uint256(config.width) * 8) != 0) {
revert AmountDoesNotFit(amount, config.width);
}
result = new bytes(config.width);
for (uint256 i; i < config.width; ++i) {
// forge-lint: disable-next-line(unsafe-typecast)
result[config.littleEndian ? i : config.width - 1 - i] = bytes1(
uint8(amount >> (8 * i))
);
}
}
}
contracts/chain/SolanaVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/**
* @notice Canonical Eco Solana vault and associated-token-account derivation on EVM.
* @dev Uses SHA-256 (0x02), field arithmetic and MODEXP (0x05); no Ed25519 precompile is required.
* The decompression check follows the Edwards25519 square-root test used by Solana's dalek,
* as also implemented in sauce, ref 16243de08, v12-evm/engine/handlers/Pda.huff (PR #416).
* This is a PDA membership test, NOT a signature/public-key validation routine: dalek's PDA
* test reduces y modulo p and does not reject the sign bit when x is zero.
*
* Both bumps are DERIVED, never caller-supplied. A non-canonical bump can produce a different,
* valid-looking, off-curve address which the Portal/ATA program will not use. A CCTP mint to that
* address can be unrecoverable. Order commitment alone would prevent bump substitution, not prove
* canonicality for an unknown runtime amount. Search from 255 down ensures the first off-curve
* digest is canonical. Each search is bounded to 32 attempts (255..224); exhaustion reverts,
* never returns a lower/non-canonical address. Chains must provide both standard precompiles.
*/
library SolanaVault {
uint256 internal constant P =
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed;
uint256 internal constant D =
0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3;
uint256 internal constant EXP =
0x0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
uint256 internal constant MAX_ATTEMPTS = 32;
// ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL
bytes32 internal constant ATA_PROGRAM =
0x8c97258f4e2489f1bb3d1029148e0d830b5a1399daff1084048e7bd8dbe9f859;
error MissingProgramId();
error MissingTokenProgramId();
error MissingMint();
error PdaSearchExhausted();
error PrecompileFailed(address precompile);
/// @notice Derive the vault, then its ATA (the actual CCTP mint recipient).
function derive(
bytes32 intentHash,
bytes32 portalProgram,
bytes32 tokenProgram,
bytes32 mint
)
internal
view
returns (bytes32 vault, bytes32 ata, uint8 vaultBump, uint8 ataBump)
{
if (portalProgram == bytes32(0)) revert MissingProgramId();
if (tokenProgram == bytes32(0)) revert MissingTokenProgramId();
if (mint == bytes32(0)) revert MissingMint();
(vault, vaultBump) = _find(
abi.encodePacked("vault", intentHash),
portalProgram
);
(ata, ataBump) = _find(
abi.encodePacked(vault, tokenProgram, mint),
ATA_PROGRAM
);
}
/// @dev Only fixed internal seed shapes reach this helper: [5,32] or [32,32,32] bytes. Both satisfy
/// Solana's seed count/length limits including the extra bump seed; no arbitrary seed API.
function _find(
bytes memory seeds,
bytes32 program
) private view returns (bytes32 result, uint8 bump) {
bytes memory preimage = abi.encodePacked(
seeds,
bytes1(0xff),
program,
"ProgramDerivedAddress"
);
for (uint256 i; i < MAX_ATTEMPTS; ++i) {
// forge-lint: disable-next-line(unsafe-typecast)
bump = uint8(255 - i);
preimage[seeds.length] = bytes1(bump);
(bool success, bytes memory output) = address(0x02).staticcall(
preimage
);
if (!success || output.length != 32)
revert PrecompileFailed(address(0x02));
result = abi.decode(output, (bytes32));
if (!isOnCurve(result)) return (result, bump);
}
revert PdaSearchExhausted();
}
/// @notice Whether a compressed Edwards Y decompresses under Solana's PDA membership rules.
function isOnCurve(bytes32 compressed) internal view returns (bool) {
// Solana's compressed Y is little-endian, with the sign of X in the top bit.
uint256 y;
for (uint256 i; i < 32; ++i)
y |= uint256(uint8(compressed[i])) << (8 * i);
y &= type(uint256).max >> 1;
uint256 yy = mulmod(y, y, P);
uint256 u = addmod(yy, P - 1, P);
uint256 v = addmod(mulmod(D, yy, P), 1, P);
uint256 v3 = mulmod(mulmod(v, v, P), v, P);
uint256 v7 = mulmod(mulmod(v3, v3, P), v, P);
bytes memory input = abi.encode(
uint256(32),
uint256(32),
uint256(32),
mulmod(u, v7, P),
EXP,
P
);
(bool success, bytes memory output) = address(0x05).staticcall(input);
if (!success || output.length != 32)
revert PrecompileFailed(address(0x05));
uint256 r = mulmod(mulmod(u, v3, P), abi.decode(output, (uint256)), P);
uint256 check = mulmod(v, mulmod(r, r, P), P);
return check == u || check == P - u;
}
}
contracts/interfaces/IIntentSource.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Intent, Reward, TokenAmount} from "../types/Intent.sol";
/**
* @title IIntentSource
* @notice Interface for managing cross-chain intents and their associated rewards on the source chain
* @dev This contract works in conjunction with a portal contract on the destination chain
* and a prover contract for verification. It handles intent creation, funding,
* and reward distribution.
*/
interface IIntentSource {
/// @notice Intent lifecycle status
enum Status {
Initial, /// @dev Intent created, may be partially funded but not fully funded
Funded, /// @dev Intent has been fully funded with all required rewards
Withdrawn, /// @dev Rewards have been withdrawn by claimant
Refunded /// @dev Rewards have been refunded to creator
}
/**
* @notice Indicates an attempt to publish a duplicate intent
* @param intentHash The hash of the pre-existing intent
*/
error IntentAlreadyExists(bytes32 intentHash);
/**
* @notice Indicates a premature refund attempt before intent completion
* @param intentHash The hash of the unclaimed intent
*/
error IntentNotClaimed(bytes32 intentHash);
/**
* @notice Indicates mismatched array lengths in batch operations
*/
error ArrayLengthMismatch();
/**
* @notice Indicates insufficient funds to complete the intent funding
* @param intentHash The hash of the intent that couldn't be funded
*/
error InsufficientFunds(bytes32 intentHash);
/// @notice Thrown when intent status is invalid for funding operation
error InvalidStatusForFunding(Status status);
/// @notice Thrown when intent status is invalid for withdrawal operation
error InvalidStatusForWithdrawal(Status status);
/// @notice Thrown when attempting to recover an invalid token (zero address or reward token)
error InvalidRecoverToken(address token);
/// @notice Thrown when intent status is invalid for refund operation or deadline not reached
error InvalidStatusForRefund(
Status status,
uint256 currentTime,
uint256 deadline
);
/// @notice Thrown when claimant address is address zero
error InvalidClaimant();
/// @notice Thrown when caller is not the reward creator
error NotCreatorCaller(address caller);
/// @notice Thrown when a reward token duplicates value already committed elsewhere in the reward
/// (e.g. it is this deployment's configured native/ERC20 alias while the reward also carries
/// a non-zero native amount)
error RewardTokensNotUnique(address token);
/**
* @notice Signals the creation of a new cross-chain intent
* @dev AT-LEAST-ONCE. `intentHash` identifies an intent uniquely, but a
* single intent can emit `IntentPublished` more than once. Consumers
* MUST be idempotent on `intentHash`.
*
* `publish` is permissionless, takes no deadline, and only rejects
* intents that are already `Withdrawn` or `Refunded`. Re-publishing an
* `Initial` or `Funded` intent therefore succeeds and re-emits this
* event; when the intent is already `Funded` the escrow is left
* untouched, so the repeat is free to trigger and moves no funds. This
* is deliberate -- it lets an intent escrowed via `fund`/`fundFor` be
* announced after the fact, and lets a missed announcement be replayed
* for indexers.
*
* `publishAndFund`, `publishAndFundFor`, `open`, and `openFor` each
* call `publish` internally, so all five entry points re-emit this
* event -- not just `publish`. By contrast `fund`/`fundFor` escrow an
* existing intent WITHOUT publishing, so they never emit
* `IntentPublished`. (`Open` is separate and is emitted only by `open`
* and `openFor`; see {IOriginSettler}.)
*
* A re-emission on an already-`Funded` intent is NOT accompanied by a
* matching {IntentFunded}: `_fundIntent`/`_fundIntentFor` short-circuit
* via {onlyFundable} before their `IntentFunded` emit. An indexer that
* correlates the `IntentPublished`/`IntentFunded` pair therefore sees an
* orphan `IntentPublished` on every replay and must tolerate it.
* @param intentHash Unique identifier of the intent
* @param destination Destination chain ID
* @param route Encoded route data for the destination chain
* @param creator Intent originator address
* @param prover Prover contract address
* @param rewardDeadline Timestamp for reward claim eligibility
* @param rewardNativeAmount Native token reward amount
* @param rewardTokens ERC20 token rewards with amounts
*/
event IntentPublished(
bytes32 indexed intentHash,
uint64 destination,
bytes route,
address indexed creator,
address indexed prover,
uint64 rewardDeadline,
uint256 rewardNativeAmount,
TokenAmount[] rewardTokens
);
/**
* @notice Signals funding of an intent
* @param intentHash The hash of the funded intent
* @param funder The address providing the funding
* @param complete Whether the intent was completely funded (true) or partially funded (false)
*/
event IntentFunded(bytes32 intentHash, address funder, bool complete);
/**
* @notice Signals successful reward withdrawal
* @param intentHash The hash of the claimed intent
* @param claimant The address receiving the rewards
*/
event IntentWithdrawn(bytes32 intentHash, address indexed claimant);
/**
* @notice Signals successful reward refund
* @param intentHash The hash of the refunded intent
* @param refundee The address receiving the refund
*/
event IntentRefunded(bytes32 intentHash, address indexed refundee);
/**
* @notice Signals successful token recovery from an intent vault
* @dev Emitted when tokens that were accidentally sent to a vault are recovered
* Only tokens not part of the intent's reward structure can be recovered
* @param intentHash The hash of the intent whose vault had tokens recovered
* @param refundee The address receiving the recovered tokens (typically the intent creator)
* @param token The address of the token contract that was recovered
*/
event IntentTokenRecovered(
bytes32 intentHash,
address indexed refundee,
address indexed token
);
/**
* @notice Retrieves the current reward claim status for an intent
* @param intentHash The hash of the intent
* @return status Current reward status
*/
function getRewardStatus(
bytes32 intentHash
) external view returns (Status status);
/**
* @notice Computes the hash components of an intent
* @param intent The intent to hash
* @return intentHash Combined hash of route and reward components
* @return routeHash Hash of the route specifications
* @return rewardHash Hash of the reward specifications
*/
function getIntentHash(
Intent memory intent
)
external
pure
returns (bytes32 intentHash, bytes32 routeHash, bytes32 rewardHash);
/**
* @notice Computes the hash components of an intent
* @param destination Destination chain ID for the intent
* @param route Encoded route data for the intent as bytes
* @param reward The reward structure containing distribution details
* @return intentHash Combined hash of route and reward components
* @return routeHash Hash of the route specifications
* @return rewardHash Hash of the reward specifications
*/
function getIntentHash(
uint64 destination,
bytes memory route,
Reward memory reward
)
external
pure
returns (bytes32 intentHash, bytes32 routeHash, bytes32 rewardHash);
/**
* @notice Computes the deterministic vault address for an intent
* @param intent The intent to calculate the vault address for
* @return Predicted vault address
*/
function intentVaultAddress(
Intent calldata intent
) external view returns (address);
/**
* @notice Computes the deterministic vault address for an intent
* @param destination Destination chain ID for the intent
* @param route Encoded route data for the intent as bytes
* @param reward The reward structure containing distribution details
* @return Predicted vault address
*/
function intentVaultAddress(
uint64 destination,
bytes memory route,
Reward calldata reward
) external view returns (address);
/**
* @notice Checks if an intent's rewards are valid and fully funded
* @param intent The intent to validate
* @return True if the intent is properly funded
*/
function isIntentFunded(
Intent calldata intent
) external view returns (bool);
/**
* @notice Checks if an intent's rewards are valid and fully funded
* @param destination Destination chain ID for the intent
* @param route Encoded route data for the intent as bytes
* @param reward The reward structure containing distribution details
* @return True if the intent is properly funded
*/
function isIntentFunded(
uint64 destination,
bytes memory route,
Reward calldata reward
) external view returns (bool);
/**
* @notice Creates a new cross-chain intent with associated rewards
* @dev Intent must be proven on source chain before expiration for valid reward claims
* @param intent The complete intent specification
* @return intentHash Unique identifier of the created intent
* @return vault Address of the created vault
*/
function publish(
Intent calldata intent
) external returns (bytes32 intentHash, address vault);
/**
* @notice Creates a new cross-chain intent with associated rewards
* @dev Intent must be proven on source chain before expiration for valid reward claims
* @param destination Destination chain ID for the intent
* @param route Encoded route data for the intent as bytes
* @param reward The reward structure containing distribution details
* @return intentHash Unique identifier of the created intent
* @return vault Address of the created vault
*/
function publish(
uint64 destination,
bytes memory route,
Reward memory reward
) external returns (bytes32 intentHash, address vault);
/**
* @notice Creates and funds an intent in a single transaction
* @param intent The complete intent specification
* @param allowPartial Whether to allow partial funding
* @return intentHash Unique identifier of the created and funded intent
* @return vault Address of the created vault
*/
function publishAndFund(
Intent calldata intent,
bool allowPartial
) external payable returns (bytes32 intentHash, address vault);
/**
* @notice Creates and funds an intent in a single transaction
* @param destination Destination chain ID for the intent
* @param route Encoded route data for the intent as bytes
* @param reward The reward structure containing distribution details
* @param allowPartial Whether to allow partial funding
* @return intentHash Unique identifier of the created and funded intent
* @return vault Address of the created vault
*/
function publishAndFund(
uint64 destination,
bytes memory route,
Reward memory reward,
bool allowPartial
) external payable returns (bytes32 intentHash, address vault);
/**
* @notice Funds an existing intent
* @param destination Destination chain ID for the intent
* @param routeHash The hash of the intent's route component
* @param reward The reward specification
* @param allowPartial Whether to allow partial funding
* @return intentHash The hash of the funded intent
*/
function fund(
uint64 destination,
bytes32 routeHash,
Reward calldata reward,
bool allowPartial
) external payable returns (bytes32 intentHash);
/**
* @notice Funds an intent on behalf of another address using permit
* @param destination Destination chain ID for the intent
* @param routeHash The hash of the intent's route component
* @param reward The reward specification
* @param allowPartial Whether to accept partial funding
* @param fundingAddress The address providing the funding
* @param permitContract The permit contract address for external token approvals
* @return intentHash The hash of the funded intent
*/
function fundFor(
uint64 destination,
bytes32 routeHash,
Reward calldata reward,
bool allowPartial,
address fundingAddress,
address permitContract
) external payable returns (bytes32 intentHash);
/**
* @notice Creates and funds an intent on behalf of another address
* @param intent The complete intent specification
* @param allowPartial Whether to accept partial funding
* @param funder The address providing the funding
* @param permitContract The permit contract for token approvals
* @return intentHash The hash of the created and funded intent
* @return vault Address of the created vault
*/
function publishAndFundFor(
Intent calldata intent,
bool allowPartial,
address funder,
address permitContract
) external payable returns (bytes32 intentHash, address vault);
/**
* @notice Creates and funds an intent on behalf of another address
* @param destination Destination chain ID for the intent
* @param route Encoded route data for the intent as bytes
* @param reward The reward structure containing distribution details
* @param allowPartial Whether to accept partial funding
* @param funder The address providing the funding
* @param permitContract The permit contract for token approvals
* @return intentHash The hash of the created and funded intent
* @return vault Address of the created vault
*/
function publishAndFundFor(
uint64 destination,
bytes memory route,
Reward calldata reward,
bool allowPartial,
address funder,
address permitContract
) external payable returns (bytes32 intentHash, address vault);
/**
* @notice Claims rewards for a successfully fulfilled and proven intent
* @param destination Destination chain ID for the intent
* @param routeHash The hash of the intent's route component
* @param reward The reward specification
*/
function withdraw(
uint64 destination,
bytes32 routeHash,
Reward calldata reward
) external;
/**
* @notice Claims rewards for multiple fulfilled and proven intents
* @param destinations Array of destination chain IDs for the intents
* @param routeHashes Array of route component hashes
* @param rewards Array of corresponding reward specifications
*/
function batchWithdraw(
uint64[] calldata destinations,
bytes32[] calldata routeHashes,
Reward[] calldata rewards
) external;
/**
* @notice Returns rewards to the intent creator
* @param destination Destination chain ID for the intent
* @param routeHash The hash of the intent's route component
* @param reward The reward specification
*/
function refund(
uint64 destination,
bytes32 routeHash,
Reward calldata reward
) external;
/**
* @notice Returns rewards to a specified address (only callable by reward creator)
* @param destination Destination chain ID for the intent
* @param routeHash The hash of the intent's route component
* @param reward The reward specification
* @param refundee Address to receive the refunded rewards
*/
function refundTo(
uint64 destination,
bytes32 routeHash,
Reward calldata reward,
address refundee
) external;
/**
* @notice Recovers mistakenly transferred tokens from the intent vault
* @dev Token must not be part of the intent's reward structure
* @param destination Destination chain ID for the intent
* @param routeHash The hash of the intent's route component
* @param reward The reward specification
* @param token The address of the token to recover
*/
function recoverToken(
uint64 destination,
bytes32 routeHash,
Reward calldata reward,
address token
) external;
}
contracts/types/Intent.sol
/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/**
* @notice Represents a single contract call with encoded function data
* @dev Used to execute arbitrary function calls on the destination chain
* @param target The contract address to call
* @param data ABI-encoded function call data
* @param value Amount of native tokens to send with the call
*/
struct Call {
address target;
bytes data;
uint256 value;
}
/**
* @notice Represents a token amount pair
* @dev Used to specify token rewards and transfers
* @param token Address of the ERC20 token contract
* @param amount Amount of tokens in the token's smallest unit
*/
struct TokenAmount {
address token;
uint256 amount;
}
/**
* @notice Defines the routing and execution instructions for cross-chain messages
* @dev Contains all necessary information to route and execute a message on the destination chain
* @param salt Unique identifier provided by the intent creator, used to prevent duplicates
* @param deadline Timestamp by which the route must be executed
* @param portal Address of the portal contract on the destination chain that receives messages
* @param nativeAmount Amount of native tokens to send with the route execution
* @param tokens Array of tokens required for execution of calls on destination chain
* @param calls Array of contract calls to execute on the destination chain in sequence
*/
struct Route {
bytes32 salt;
uint64 deadline;
address portal;
uint256 nativeAmount;
TokenAmount[] tokens;
Call[] calls;
}
/**
* @notice Defines the reward and validation parameters for cross-chain execution
* @dev Specifies who can execute the intent and what rewards they receive
* @param deadline Timestamp after which the intent can no longer be executed
* @param creator Address that created the intent and has authority to modify/cancel
* @param prover Address of the prover contract that must approve execution
* @param nativeAmount Amount of native tokens offered as reward
* @param tokens Array of ERC20 tokens and amounts offered as additional rewards
*/
struct Reward {
uint64 deadline;
address creator;
address prover;
uint256 nativeAmount;
TokenAmount[] tokens;
}
/**
* @notice Complete cross-chain intent combining routing and reward information
* @dev Main structure used to process and execute cross-chain messages
* @param destination Target chain ID where the intent should be executed
* @param route Routing and execution instructions
* @param reward Reward and validation parameters
*/
struct Intent {
uint64 destination;
Route route;
Reward reward;
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
node_modules/@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// 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 FailedInnerCall();
}
}
}
node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
node_modules/@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
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.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 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.
uint256 twos = denominator & (0 - denominator);
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 (unsignedRoundsUp(rounding) && 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
* towards zero.
*
* 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @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 Return the log in base 10 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < 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;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
"@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
"@hyperlane-xyz/core/=node_modules/@hyperlane-xyz/core/",
"@eth-optimism/contracts-bedrock/=node_modules/@eth-optimism/contracts-bedrock/",
"@metalayer/contracts/=node_modules/@metalayer/contracts/",
"@chainlink/contracts-ccip/=node_modules/@chainlink/contracts-ccip/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.