Address Contract Verified
Address
0x3E9f065cdf0A0C597c5BB5719fEAb059C23f359D
Balance
0 ETH
Nonce
191
Code Size
4105 bytes
Creator
0x588ede44...033a at tx 0x3c7a874e...f896e0
Indexed Transactions
0
Contract Bytecode
4105 bytes
0x6080806040526004361015610012575f80fd5b5f905f3560e01c90816301ffc9a7146109ef575080630a1ca464146109c7578063168b258a1461094a57806334b5ee92146108dd5780634258b0b9146108b7578063739e39b314610891578063766248ed146107ae5780637714e03e146107775780638129fc1c146105ea57806384baa36c146105ad578063883edfb8146104e55780639572269e146104a2578063b1094ea8146103fb5763b3fb6579146100b8575f80fd5b3461027a5760a060031936011261027a576100d1610abc565b906044356bffffffffffffffffffffffff81169081810361027a5760643560843567ffffffffffffffff811161027a5761010f903690600401610ad2565b91804210156103d05761012f6001600160a01b0360025416918533610b52565b7f19457468657265756d205369676e6564204d6573736167653a0a3332000000005f52601c52603c5f2061016284610c4e565b936101706040519586610b1b565b8085526020850193368282011161027a57815f926020928737860101526101978482610f23565b60058195929510156103bc571593846103a9575b5083156102a6575b50505090501561027e576101ce6001600160a01b0391610cb9565b1690813b1561027a576001600160a01b03604051947f47e7ef2400000000000000000000000000000000000000000000000000000000865216600485015260243560248501525f8460448183865af193841561026f5760209461025a575b50604051927f037a3afe0751abef738eb74190bea476ded20cd037ed1fa291ef7157c6d69db7339180a38152f35b6102679193505f90610b1b565b5f915f61022c565b6040513d5f823e3d90fd5b5f80fd5b7fcea2b018000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f94859450608461031791601f19601f60405195869360208501987f1626ba7e000000000000000000000000000000000000000000000000000000008a526024860152604060448601525180918160648701528686015e89858286010152011681010301601f198101835282610b1b565b51915afa3d156103a2573d61032b81610c4e565b906103396040519283610b1b565b81523d5f602083013e5b81610394575b81610359575b50805f80806101b3565b905060208180518101031261027a57602001517f1626ba7e00000000000000000000000000000000000000000000000000000000145f61034f565b905060208151101590610349565b6060610343565b6001600160a01b0316831493505f6101ab565b634e487b7160e01b5f52602160045260245ffd5b7fc56cc5e4000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b3461027a57602060031936011261027a576001600160a01b0361041c610abc565b610424610c6a565b16801561047a5773ffffffffffffffffffffffffffffffffffffffff19600254826001600160a01b0382167faef869fcd0ce5a9fabc7014492cd725438b8f9cefa91b3d890e117d09f15e2145f80a31617600255005b7f1a24bb4c000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461027a575f60031936011261027a5760206040516001600160a01b037f000000000000000000000000a156ec23898de504b847ad247934231ef332ecd8168152f35b3461027a575f60031936011261027a576040518060206003549283815201809260035f527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b905f5b81811061058e5750505081610543910382610b1b565b604051918291602083019060208452518091526040830191905f5b81811061056c575050500390f35b82516001600160a01b031684528594506020938401939092019160010161055e565b82546001600160a01b031684526020909301926001928301920161052d565b3461027a57604060031936011261027a5760206105d96105cb610abc565b6105d3610b00565b90610ba0565b6001600160a01b0360405191168152f35b3461027a575f60031936011261027a575f5460ff8160081c16159081809261076a575b8015610753575b156106cf578160017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff008316175f556106a1575b5061064e57005b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff5f54165f557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a1005b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000016610101175f5581610647565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152fd5b50303b1580156106145750600160ff821614610614565b50600160ff82161061060d565b3461027a57606060031936011261027a5760206107a6610795610abc565b61079d610b00565b60443591610b52565b604051908152f35b3461027a575f60031936011261027a57336001600160a01b0360015416036108655773ffffffffffffffffffffffffffffffffffffffff19600154166001555f5475ffffffffffffffffffffffffffffffffffffffff00003360101b167fffffffffffffffffffff0000000000000000000000000000000000000000ffff8216175f556001600160a01b03339160101c167fd12c6d0023f33ea4623f09573867525c39e01ea657ccb920b8e858591689a8fe5f80a3005b7f2cd7e245000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b3461027a575f60031936011261027a5760206001600160a01b0360015416604051908152f35b3461027a575f60031936011261027a5760206001600160a01b0360025416604051908152f35b3461027a57606060031936011261027a576108f6610abc565b506108ff610a8d565b5060443567ffffffffffffffff811161027a57610920903690600401610ad2565b50507f6a2c668e000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461027a57602060031936011261027a576001600160a01b0361096b610abc565b610973610c6a565b168073ffffffffffffffffffffffffffffffffffffffff1960015416176001556001600160a01b035f5460101c167f89e07989a511e47b69130132740382fc032ac4832fa9748222fb51c4769fb7bd5f80a3005b3461027a575f60031936011261027a5760206001600160a01b035f5460101c16604051908152f35b3461027a57602060031936011261027a57600435907fffffffff00000000000000000000000000000000000000000000000000000000821680920361027a57817fa45485780000000000000000000000000000000000000000000000000000000060209314908115610a63575b5015158152f35b7f01ffc9a70000000000000000000000000000000000000000000000000000000091501483610a5c565b602435907fffffffff000000000000000000000000000000000000000000000000000000008216820361027a57565b600435906001600160a01b038216820361027a57565b9181601f8401121561027a5782359167ffffffffffffffff831161027a576020838186019501011161027a57565b602435906bffffffffffffffffffffffff8216820361027a57565b90601f601f19910116810190811067ffffffffffffffff821117610b3e57604052565b634e487b7160e01b5f52604160045260245ffd5b916bffffffffffffffffffffffff604051926001600160a01b03602085019516855216604083015260608201523060808201524660a082015260a08152610b9a60c082610b1b565b51902090565b610bae605592603792610c80565b604051907f3d602d80600a3d3981f3363d3d373d3d3d363d7300000000000000000000000082526bffffffffffffffffffffffff197f000000000000000000000000a156ec23898de504b847ad247934231ef332ecd860601b1660148301527f5af43d82803e903d91602b57fd5bf3ff0000000000000000000000000000000060288301523060601b6038830152604c820152818120606c820152012090565b67ffffffffffffffff8111610b3e57601f01601f191660200190565b6001600160a01b035f5460101c16330361086557565b604080516001600160a01b0392909216602083019081526bffffffffffffffffffffffff93909316828201528152610b9a606082610b1b565b905f91610cc68133610ba0565b803b610f1557506001600160a01b03610cdf8233610c80565b60376040517f3d602d80600a3d3981f3363d3d373d3d3d363d7300000000000000000000000081526bffffffffffffffffffffffff197f000000000000000000000000a156ec23898de504b847ad247934231ef332ecd860601b1660148201527f5af43d82803e903d91602b57fd5bf3000000000000000000000000000000000060288201525ff516908115610eb7578193823b1561027a576040517ff2a413740000000000000000000000000000000000000000000000000000000081523360048201526bffffffffffffffffffffffff831660248201525f8160448183885af1801561026f57610ea4575b506003549068010000000000000000821015610e90576001820180600355821015610e7c576060927f7ba7f5310bdc1f35de8fd56e0b1c97ff9f540b72f8c3b57d9402cf6cca700283949260036bffffffffffffffffffffffff93527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b018373ffffffffffffffffffffffffffffffffffffffff19825416179055604051928352336020840152166040820152a1565b80634e487b7160e01b602492526032600452fd5b80634e487b7160e01b602492526041600452fd5b610eb091505f90610b1b565b5f5f610dcc565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f455243313136373a2063726561746532206661696c65640000000000000000006044820152fd5b6001600160a01b0316925050565b9060418151145f14610f4f57610f4b91602082015190606060408401519301515f1a90610f58565b9091565b50505f90600290565b7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411610fc8576020935f9360ff60809460405194855216868401526040830152606082015282805260015afa1561026f575f516001600160a01b03811615610fc057905f90565b505f90600190565b505050505f9060039056fea2646970667358221220ec5325cdb86f19639ec4e045be5e5f4b29c6286afdc6df944c09ec4fd11537a464736f6c634300081e0033
Verified Source Code Full Match
Compiler: v0.8.30+commit.73712a01
EVM: prague
Optimization: Yes (2000 runs)
P2pResolvProxyFactory.sol 39 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../../../p2pYieldProxyFactory/P2pYieldProxyFactory.sol"; import "../p2pResolvProxy/P2pResolvProxy.sol"; /// @title Entry point for depositing into Resolv with P2P.org contract P2pResolvProxyFactory is P2pYieldProxyFactory { /// @notice Constructor for P2pResolvProxyFactory /// @param _p2pSigner The P2pSigner address /// @param _p2pTreasury The P2pTreasury address /// @param _stUSR stUSR address /// @param _USR USR address /// @param _stRESOLV stRESOLV /// @param _RESOLV RESOLV /// @param _allowedCalldataChecker AllowedCalldataChecker constructor( address _p2pSigner, address _p2pTreasury, address _stUSR, address _USR, address _stRESOLV, address _RESOLV, address _allowedCalldataChecker ) P2pYieldProxyFactory(_p2pSigner) { i_referenceP2pYieldProxy = new P2pResolvProxy( address(this), _p2pTreasury, _allowedCalldataChecker, _stUSR, _USR, _stRESOLV, _RESOLV ); } }
P2pYieldProxyFactory.sol 263 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../@openzeppelin/contracts/proxy/Clones.sol"; import "../@openzeppelin/contracts/utils/Address.sol"; import "../@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "../@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "../access/P2pOperator2Step.sol"; import "../common/AllowedCalldataChecker.sol"; import "../p2pYieldProxy/P2pYieldProxy.sol"; import "./IP2pYieldProxyFactory.sol"; /// @dev Error when the P2pSigner address is zero error P2pYieldProxyFactory__ZeroP2pSignerAddress(); /// @dev Error when the P2pSigner signature is invalid error P2pYieldProxyFactory__InvalidP2pSignerSignature(); /// @dev Error when the P2pSigner signature is expired error P2pYieldProxyFactory__P2pSignerSignatureExpired( uint256 _p2pSignerSigDeadline ); /// @dev Error when no rules are defined error P2pYieldProxyFactory__NoRulesDefined( address _target, bytes4 _selector ); /// @dev Error when no calldata is allowed error P2pYieldProxyFactory__NoCalldataAllowed( address _target, bytes4 _selector ); /// @dev Error when the calldata is too short for the start with rule error P2pYieldProxyFactory__CalldataTooShortForStartsWithRule( uint256 _calldataAfterSelectorLength, uint32 _ruleIndex, uint32 _bytesCount ); /// @dev Error when the calldata starts with rule is violated error P2pYieldProxyFactory__CalldataStartsWithRuleViolated( bytes _actual, bytes _expected ); /// @dev Error when the calldata is too short for the ends with rule error P2pYieldProxyFactory__CalldataTooShortForEndsWithRule( uint256 _calldataAfterSelectorLength, uint32 _bytesCount ); /// @dev Error when the calldata ends with rule is violated error P2pYieldProxyFactory__CalldataEndsWithRuleViolated( bytes _actual, bytes _expected ); /// @title P2pYieldProxyFactory /// @author P2P Validator <[email protected]> /// @notice P2pYieldProxyFactory is a factory contract for creating P2pYieldProxy contracts abstract contract P2pYieldProxyFactory is AllowedCalldataChecker, P2pOperator2Step, ERC165, IP2pYieldProxyFactory { using SignatureChecker for address; using ECDSA for bytes32; /// @notice Reference P2pYieldProxy contract P2pYieldProxy internal immutable i_referenceP2pYieldProxy; /// @notice P2pSigner address address internal s_p2pSigner; /// @notice All proxies address[] internal s_allProxies; /// @notice Modifier to check if the P2pSigner signature should not expire modifier p2pSignerSignatureShouldNotExpire(uint256 _p2pSignerSigDeadline) { require ( block.timestamp < _p2pSignerSigDeadline, P2pYieldProxyFactory__P2pSignerSignatureExpired(_p2pSignerSigDeadline) ); _; } /// @notice Modifier to check if the P2pSigner signature should be valid modifier p2pSignerSignatureShouldBeValid( uint96 _clientBasisPoints, uint256 _p2pSignerSigDeadline, bytes calldata _p2pSignerSignature ) { require ( s_p2pSigner.isValidSignatureNow( getHashForP2pSigner( msg.sender, _clientBasisPoints, _p2pSignerSigDeadline ).toEthSignedMessageHash(), _p2pSignerSignature ), P2pYieldProxyFactory__InvalidP2pSignerSignature() ); _; } /// @notice Constructor for P2pYieldProxyFactory /// @param _p2pSigner The P2pSigner address constructor( address _p2pSigner ) P2pOperator(msg.sender) { _transferP2pSigner(_p2pSigner); } /// @inheritdoc IP2pYieldProxyFactory function transferP2pSigner( address _newP2pSigner ) external onlyP2pOperator { _transferP2pSigner(_newP2pSigner); } /// @inheritdoc IP2pYieldProxyFactory function deposit( address _asset, uint256 _amount, uint96 _clientBasisPoints, uint256 _p2pSignerSigDeadline, bytes calldata _p2pSignerSignature ) external p2pSignerSignatureShouldNotExpire(_p2pSignerSigDeadline) p2pSignerSignatureShouldBeValid(_clientBasisPoints, _p2pSignerSigDeadline, _p2pSignerSignature) returns (address p2pYieldProxyAddress) { // create proxy if not created yet P2pYieldProxy p2pYieldProxy = _getOrCreateP2pYieldProxy(_clientBasisPoints); // deposit via proxy p2pYieldProxy.deposit(_asset, _amount); emit P2pYieldProxyFactory__Deposited(msg.sender, _clientBasisPoints); p2pYieldProxyAddress = address(p2pYieldProxy); } function _transferP2pSigner( address _newP2pSigner ) private { require (_newP2pSigner != address(0), P2pYieldProxyFactory__ZeroP2pSignerAddress()); emit P2pYieldProxyFactory__P2pSignerTransferred(s_p2pSigner, _newP2pSigner); s_p2pSigner = _newP2pSigner; } /// @notice Creates a new P2pYieldProxy contract instance if not created yet function _getOrCreateP2pYieldProxy(uint96 _clientBasisPoints) private returns (P2pYieldProxy p2pYieldProxy) { address p2pYieldProxyAddress = predictP2pYieldProxyAddress( msg.sender, _clientBasisPoints ); uint256 codeSize = p2pYieldProxyAddress.code.length; if (codeSize > 0) { return P2pYieldProxy(p2pYieldProxyAddress); } p2pYieldProxy = P2pYieldProxy( Clones.cloneDeterministic( address(i_referenceP2pYieldProxy), _getSalt( msg.sender, _clientBasisPoints ) ) ); p2pYieldProxy.initialize( msg.sender, _clientBasisPoints ); s_allProxies.push(address(p2pYieldProxy)); emit P2pYieldProxyFactory__ProxyCreated( address(p2pYieldProxy), msg.sender, _clientBasisPoints ); } /// @notice Calculates the salt required for deterministic clone creation /// depending on client address and client basis points /// @param _clientAddress address /// @param _clientBasisPoints basis points (10000 = 100%) /// @return bytes32 salt function _getSalt( address _clientAddress, uint96 _clientBasisPoints ) private pure returns (bytes32) { return keccak256(abi.encode(_clientAddress, _clientBasisPoints)); } /// @inheritdoc IP2pYieldProxyFactory function predictP2pYieldProxyAddress( address _client, uint96 _clientBasisPoints ) public view returns (address) { return Clones.predictDeterministicAddress( address(i_referenceP2pYieldProxy), _getSalt(_client, _clientBasisPoints) ); } /// @inheritdoc IP2pYieldProxyFactory function getReferenceP2pYieldProxy() external view returns (address) { return address(i_referenceP2pYieldProxy); } /// @inheritdoc IP2pYieldProxyFactory function getHashForP2pSigner( address _client, uint96 _clientBasisPoints, uint256 _p2pSignerSigDeadline ) public view returns (bytes32) { return keccak256(abi.encode( _client, _clientBasisPoints, _p2pSignerSigDeadline, address(this), block.chainid )); } /// @inheritdoc IP2pYieldProxyFactory function getP2pSigner() external view returns (address) { return s_p2pSigner; } /// @inheritdoc IP2pYieldProxyFactory function getP2pOperator() public override(IP2pYieldProxyFactory, P2pOperator) view returns (address) { return super.getP2pOperator(); } /// @inheritdoc IP2pYieldProxyFactory function getAllProxies() external view returns (address[] memory) { return s_allProxies; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IP2pYieldProxyFactory).interfaceId || super.supportsInterface(interfaceId); } }
P2pResolvProxy.sol 383 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../../../@resolv/IResolvStaking.sol"; import "../../../@resolv/IStUSR.sol"; import "../../../@resolv/IStakedTokenDistributor.sol"; import "../../../p2pYieldProxy/P2pYieldProxy.sol"; import "./IP2pResolvProxy.sol"; error P2pResolvProxy__ZeroAddress_USR(); error P2pResolvProxy__AssetNotSupported(address _asset); error P2pResolvProxy__UnauthorizedAccount(address _account); error P2pResolvProxy__NotP2pOperator(address _caller); error P2pResolvProxy__CallerNeitherClientNorP2pOperator(address _caller); error P2pResolvProxy__ZeroAccruedRewards(); error P2pResolvProxy__UnsupportedAsset(address _asset); error P2pResolvProxy__ZeroAddressStakedTokenDistributor(); error P2pResolvProxy__CannotSweepProtectedToken(address _token); error P2pResolvProxy__RewardTokenLookupFailed(uint256 index); contract P2pResolvProxy is P2pYieldProxy, IP2pResolvProxy { using SafeERC20 for IERC20; /// @dev USR address address internal immutable i_USR; /// @dev stUSR address address internal immutable i_stUSR; /// @dev RESOLV address address internal immutable i_RESOLV; /// @dev stRESOLV address address internal immutable i_stRESOLV; IStakedTokenDistributor private s_stakedTokenDistributor; // Tracks pending RESOLV rewards that arrived via StakedTokenDistributor claims. uint256 private s_pendingResolvRewardFromStakedTokenDistributor; /// @dev Throws if called by any account other than the P2pOperator. modifier onlyP2pOperator() { address p2pOperator = i_factory.getP2pOperator(); require (msg.sender == p2pOperator, P2pResolvProxy__NotP2pOperator(msg.sender)); _; } /// @dev Throws if called by any account other than client or P2pOperator. modifier onlyClientOrP2pOperator() { if (msg.sender != s_client) { address p2pOperator = i_factory.getP2pOperator(); require (msg.sender == p2pOperator, P2pResolvProxy__CallerNeitherClientNorP2pOperator(msg.sender)); } _; } /// @notice Constructor for P2pResolvProxy /// @param _factory Factory address /// @param _p2pTreasury P2pTreasury address /// @param _allowedCalldataChecker AllowedCalldataChecker /// @param _stUSR stUSR address /// @param _USR USR address /// @param _stRESOLV stRESOLV address /// @param _RESOLV RESOLV address constructor( address _factory, address _p2pTreasury, address _allowedCalldataChecker, address _stUSR, address _USR, address _stRESOLV, address _RESOLV ) P2pYieldProxy(_factory, _p2pTreasury, _allowedCalldataChecker) { require(_USR != address(0), P2pResolvProxy__ZeroAddress_USR()); i_USR = _USR; i_stUSR = _stUSR; i_RESOLV = _RESOLV; i_stRESOLV = _stRESOLV; } /// @inheritdoc IP2pYieldProxy function deposit(address _asset, uint256 _amount) external override onlyFactory { if (_asset == i_USR) { _deposit( i_stUSR, abi.encodeWithSelector(IStUSR.deposit.selector, _amount), i_USR, _amount ); } else if (_asset == i_RESOLV) { _depositResolv(_amount); } else { revert P2pResolvProxy__AssetNotSupported(_asset); } } /// @inheritdoc IP2pResolvProxy function withdrawUSR(uint256 _amount) external onlyClient { require (_amount > 0, P2pYieldProxy__ZeroAssetAmount()); uint256 currentBalance = IERC20(i_stUSR).balanceOf(address(this)); if (_amount >= currentBalance || currentBalance - _amount <= 1) { _withdraw( i_stUSR, i_USR, abi.encodeCall(IStUSR.withdrawAll, ()) ); return; } _withdraw( i_stUSR, i_USR, abi.encodeWithSelector(IStUSR.withdraw.selector, _amount) ); } function withdrawUSRAccruedRewards() external onlyP2pOperator { int256 amount = calculateAccruedRewardsUSR(); require (amount > 0, P2pResolvProxy__ZeroAccruedRewards()); _withdraw( i_stUSR, i_USR, abi.encodeWithSelector(IStUSR.withdraw.selector, amount), true ); } /// @inheritdoc IP2pResolvProxy function withdrawAllUSR() external onlyClient { _withdraw( i_stUSR, i_USR, abi.encodeCall(IStUSR.withdrawAll, ()) ); } /// @inheritdoc IP2pResolvProxy function initiateWithdrawalRESOLV(uint256 _amount) external onlyClient { return IResolvStaking(i_stRESOLV).initiateWithdrawal(_amount); } /// @inheritdoc IP2pResolvProxy function withdrawRESOLV() external onlyClientOrP2pOperator nonReentrant { IResolvStaking staking = IResolvStaking(i_stRESOLV); uint256 pendingReward = s_pendingResolvRewardFromStakedTokenDistributor; if (pendingReward == 0) { staking.withdraw(false, s_client); emit P2pResolvProxy__ResolvPrincipalWithdrawal(msg.sender); return; } IERC20 resolvToken = IERC20(i_RESOLV); uint256 balanceBefore = resolvToken.balanceOf(address(this)); staking.withdraw(false, address(this)); uint256 balanceAfter = resolvToken.balanceOf(address(this)); uint256 delta = balanceAfter - balanceBefore; s_pendingResolvRewardFromStakedTokenDistributor = 0; uint256 expectedReward = pendingReward; uint256 principalPortion = delta > expectedReward ? delta - expectedReward : 0; uint256 rewardPortion = delta - principalPortion; uint256 p2pAmount = calculateP2pFeeAmount(rewardPortion); uint256 clientRewardAmount = rewardPortion - p2pAmount; if (p2pAmount > 0) { resolvToken.safeTransfer(i_p2pTreasury, p2pAmount); } uint256 clientAmountToSend = clientRewardAmount + principalPortion; if (clientAmountToSend > 0) { resolvToken.safeTransfer(s_client, clientAmountToSend); } emit P2pResolvProxy__DistributorRewardsReleased( expectedReward, delta, p2pAmount, clientRewardAmount, principalPortion ); } /// @inheritdoc IP2pResolvProxy function claimStakedTokenDistributor( uint256 _index, uint256 _amount, bytes32[] calldata _merkleProof ) external nonReentrant onlyClientOrP2pOperator { // claim _reward token from StakedTokenDistributor address stakedTokenDistributor = address(s_stakedTokenDistributor); require( stakedTokenDistributor != address(0), P2pResolvProxy__ZeroAddressStakedTokenDistributor() ); IERC20 stResolv = IERC20(i_stRESOLV); uint256 sharesBefore = stResolv.balanceOf(address(this)); IStakedTokenDistributor(stakedTokenDistributor).claim(_index, _amount, _merkleProof); uint256 claimedShares = stResolv.balanceOf(address(this)) - sharesBefore; require(claimedShares > 0, P2pYieldProxy__ZeroAssetAmount()); s_pendingResolvRewardFromStakedTokenDistributor += claimedShares; emit P2pResolvProxy__Claimed(claimedShares); IResolvStaking(i_stRESOLV).initiateWithdrawal(claimedShares); } /// @inheritdoc IP2pResolvProxy function claimRewardTokens() external onlyClientOrP2pOperator nonReentrant { address[] memory rewardTokens = _getRewardTokens(); uint256 tokenCount = rewardTokens.length; uint256[] memory balancesBefore = new uint256[](tokenCount); for (uint256 i; i < tokenCount; ++i) { balancesBefore[i] = IERC20(rewardTokens[i]).balanceOf(address(this)); } IResolvStaking(i_stRESOLV).claim(address(this), address(this)); for (uint256 i; i < tokenCount; ++i) { address tokenAddress = rewardTokens[i]; IERC20 token = IERC20(tokenAddress); uint256 balanceAfter = token.balanceOf(address(this)); uint256 delta = balanceAfter - balancesBefore[i]; if (delta > 0) { uint256 p2pAmount = calculateP2pFeeAmount(delta); uint256 clientAmount = delta - p2pAmount; if (p2pAmount > 0) { token.safeTransfer(i_p2pTreasury, p2pAmount); } if (clientAmount > 0) { token.safeTransfer(s_client, clientAmount); } emit P2pResolvProxy__RewardTokensClaimed( tokenAddress, delta, p2pAmount, clientAmount ); } } } /// @inheritdoc IP2pResolvProxy function sweepRewardToken(address _token) external onlyClientOrP2pOperator { // Prevent sweeping of protected assets that are handled by existing accounting if (_token == i_USR || _token == i_RESOLV || _token == i_stUSR || _token == i_stRESOLV) { revert P2pResolvProxy__CannotSweepProtectedToken(_token); } uint256 balance = IERC20(_token).balanceOf(address(this)); if (balance > 0) { IERC20(_token).safeTransfer(s_client, balance); emit P2pResolvProxy__RewardTokenSwept(_token, balance); } } function setStakedTokenDistributor(address _stakedTokenDistributor) external override onlyP2pOperator { require(_stakedTokenDistributor != address(0), P2pResolvProxy__ZeroAddressStakedTokenDistributor()); address previousStakedTokenDistributor = address(s_stakedTokenDistributor); s_stakedTokenDistributor = IStakedTokenDistributor(_stakedTokenDistributor); emit P2pResolvProxy__StakedTokenDistributorUpdated( previousStakedTokenDistributor, _stakedTokenDistributor ); } function getStakedTokenDistributor() public view override returns(address) { return address(s_stakedTokenDistributor); } function getUserPrincipalUSR() public view returns(uint256) { return getUserPrincipal(i_USR); } function getUserPrincipalRESOLV() public view returns(uint256) { return IERC20(i_stRESOLV).balanceOf(address(this)); } function calculateAccruedRewardsUSR() public view returns(int256) { uint256 currentAmount = IERC20(i_stUSR).balanceOf(address(this)); uint256 userPrincipal = getUserPrincipal(i_USR); return int256(currentAmount) - int256(userPrincipal); } function calculateAccruedRewardsRESOLV(address _token) public view returns(int256) { return int256( IResolvStaking(i_stRESOLV).getUserClaimableAmounts(address(this), _token) ); } function getLastFeeCollectionTimeUSR() public view returns(uint48) { return getLastFeeCollectionTime(i_USR); } function getLastFeeCollectionTimeRESOLV() public view returns(uint48) { return getLastFeeCollectionTime(i_RESOLV); } function _depositResolv(uint256 _amount) internal { require(_amount > 0, P2pYieldProxy__ZeroAssetAmount()); IERC20 resolvToken = IERC20(i_RESOLV); uint256 balanceBefore = resolvToken.balanceOf(address(this)); resolvToken.safeTransferFrom(s_client, address(this), _amount); uint256 actualAmount = resolvToken.balanceOf(address(this)) - balanceBefore; require( actualAmount == _amount, P2pYieldProxy__DifferentActuallyDepositedAmount(_amount, actualAmount) ); resolvToken.safeIncreaseAllowance(i_stRESOLV, actualAmount); IResolvStaking(i_stRESOLV).deposit(actualAmount, address(this)); emit P2pResolvProxy__ResolvDeposited(actualAmount); } function _getCurrentAssetAmount(address _yieldProtocolAddress, address _asset) internal view override returns (uint256) { if (_asset == i_USR) { return IERC20(_yieldProtocolAddress).balanceOf(address(this)); } revert P2pResolvProxy__UnsupportedAsset(_asset); } function _getRewardTokens() internal view returns (address[] memory tokens) { IResolvStaking staking = IResolvStaking(i_stRESOLV); tokens = new address[](4); // start small; will expand as needed uint256 count; while (true) { try staking.rewardTokens(count) returns (address token) { if (count == tokens.length) { address[] memory expanded = new address[](tokens.length * 2); for (uint256 j; j < tokens.length; ++j) { expanded[j] = tokens[j]; } tokens = expanded; } tokens[count] = token; ++count; } catch { break; } } assembly { mstore(tokens, count) } } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(P2pYieldProxy) returns (bool) { return interfaceId == type(IP2pResolvProxy).interfaceId || super.supportsInterface(interfaceId); } }
Clones.sol 84 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/Clones.sol)
pragma solidity 0.8.30;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
Address.sol 221 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
pragma solidity 0.8.30;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) 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
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
SignatureChecker.sol 50 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity 0.8.30;
import "./ECDSA.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Gnosis Safe.
*
* _Available since v4.1._
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
return
(error == ECDSA.RecoverError.NoError && recovered == signer) ||
isValidERC1271SignatureNow(signer, hash, signature);
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
ERC165.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity 0.8.30;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
P2pOperator2Step.sol 69 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT // Copy and rename of OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol) pragma solidity 0.8.30; import {P2pOperator} from "./P2pOperator.sol"; /** * @dev Contract module which provides access control mechanism, where * there is an account (a P2pOperator) that can be granted exclusive access to * specific functions. * * This extension of the {P2pOperator.sol} contract includes a two-step mechanism to transfer * P2pOperator, where the new P2pOperator must call {acceptP2pOperator} in order to replace the * old one. This can help prevent common mistakes, such as transfers of P2pOperator to * incorrect accounts, or to contracts that are unable to interact with the * permission system. * * The initial P2pOperator is specified at deployment time in the constructor for `P2pOperator.sol`. This * can later be changed with {transferP2pOperator} and {acceptP2pOperator}. * * This module is used through inheritance. It will make available all functions * from parent (P2pOperator.sol). */ abstract contract P2pOperator2Step is P2pOperator { address private s_pendingP2pOperator; event P2pOperator2Step__P2pOperatorTransferStarted(address indexed _previousP2pOperator, address indexed _newP2pOperator); /** * @dev Returns the address of the pending P2pOperator. */ function getPendingP2pOperator() public view virtual returns (address) { return s_pendingP2pOperator; } /** * @dev Starts the P2pOperator transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current P2pOperator. * * Setting `_newP2pOperator` to the zero address is allowed; this can be used to cancel an initiated P2pOperator transfer. */ function transferP2pOperator(address _newP2pOperator) public virtual override onlyP2pOperator { s_pendingP2pOperator = _newP2pOperator; emit P2pOperator2Step__P2pOperatorTransferStarted(getP2pOperator(), _newP2pOperator); } /** * @dev Transfers P2pOperator of the contract to a new account (`_newP2pOperator`) and deletes any pending P2pOperator. * Internal function without access restriction. */ function _transferP2pOperator(address _newP2pOperator) internal virtual override { delete s_pendingP2pOperator; super._transferP2pOperator(_newP2pOperator); } /** * @dev The new P2pOperator accepts the P2pOperator transfer. */ function acceptP2pOperator() public virtual { address sender = msg.sender; if (s_pendingP2pOperator != sender) { revert P2pOperator__UnauthorizedAccount(sender); } _transferP2pOperator(sender); } }
AllowedCalldataChecker.sol 29 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../@openzeppelin/contracts-upgradable/proxy/utils/Initializable.sol"; import "./IAllowedCalldataChecker.sol"; /// @dev No extra calls are allowed for now. AllowedCalldataChecker can be upgraded in the future. error AllowedCalldataChecker__NoAllowedCalldata(); /// @title AllowedCalldataChecker /// @author P2P Validator <[email protected]> /// @notice Upgradable contract for checking if a calldata is allowed contract AllowedCalldataChecker is IAllowedCalldataChecker, Initializable { function initialize() public initializer { // do nothing in this implementation } /// @inheritdoc IAllowedCalldataChecker function checkCalldata( address, bytes4, bytes calldata ) public pure { revert AllowedCalldataChecker__NoAllowedCalldata(); } }
P2pYieldProxy.sol 404 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../@openzeppelin/contracts-upgradable/security/ReentrancyGuardUpgradeable.sol"; import "../@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../@openzeppelin/contracts/utils/Address.sol"; import "../@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "../@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "../common/AllowedCalldataChecker.sol"; import "../p2pYieldProxyFactory/IP2pYieldProxyFactory.sol"; import "../structs/P2pStructs.sol"; import "./IP2pYieldProxy.sol"; error P2pYieldProxy__ZeroAddressAsset(); error P2pYieldProxy__ZeroAssetAmount(); error P2pYieldProxy__ZeroSharesAmount(); error P2pYieldProxy__InvalidClientBasisPoints(uint96 _clientBasisPoints); error P2pYieldProxy__NotFactory(address _factory); error P2pYieldProxy__DifferentActuallyDepositedAmount( uint256 _requestedAmount, uint256 _actualAmount ); error P2pYieldProxy__NotFactoryCalled( address _msgSender, IP2pYieldProxyFactory _actualFactory ); error P2pYieldProxy__NotClientCalled( address _msgSender, address _actualClient ); error P2pYieldProxy__ZeroAddressFactory(); error P2pYieldProxy__ZeroAddressP2pTreasury(); error P2pYieldProxy__ZeroAllowedCalldataChecker(); error P2pYieldProxy__DataTooShort(); /// @title P2pYieldProxy /// @notice P2pYieldProxy is a contract that allows a client to deposit and withdraw assets from a yield protocol. abstract contract P2pYieldProxy is Initializable, ReentrancyGuardUpgradeable, ERC165, IP2pYieldProxy { using SafeERC20 for IERC20; using Address for address; /// @dev P2pYieldProxyFactory IP2pYieldProxyFactory internal immutable i_factory; /// @dev P2pTreasury address internal immutable i_p2pTreasury; IAllowedCalldataChecker internal immutable i_allowedCalldataChecker; /// @dev Client address internal s_client; /// @dev Client basis points uint96 internal s_clientBasisPoints; // asset => amount mapping(address => uint256) internal s_totalDeposited; // asset => amount mapping(address => Withdrawn) internal s_totalWithdrawn; /// @notice If caller is not factory, revert modifier onlyFactory() { if (msg.sender != address(i_factory)) { revert P2pYieldProxy__NotFactoryCalled(msg.sender, i_factory); } _; } /// @notice If caller is not client, revert modifier onlyClient() { if (msg.sender != s_client) { revert P2pYieldProxy__NotClientCalled(msg.sender, s_client); } _; } /// @dev Modifier for checking if a calldata is allowed /// @param _yieldProtocolAddress The address of the yield protocol /// @param _yieldProtocolCalldata The calldata (encoded signature + arguments) to be passed to the yield protocol modifier calldataShouldBeAllowed( address _yieldProtocolAddress, bytes calldata _yieldProtocolCalldata ) { // validate yieldProtocolCalldata for yieldProtocolAddress bytes4 selector = _getFunctionSelector(_yieldProtocolCalldata); i_allowedCalldataChecker.checkCalldata( _yieldProtocolAddress, selector, _yieldProtocolCalldata[4:] ); _; } /// @notice Constructor for P2pYieldProxy /// @param _factory The factory address /// @param _p2pTreasury The P2pTreasury address /// @param _allowedCalldataChecker AllowedCalldataChecker constructor( address _factory, address _p2pTreasury, address _allowedCalldataChecker ) { require(_factory != address(0), P2pYieldProxy__ZeroAddressFactory()); i_factory = IP2pYieldProxyFactory(_factory); require(_p2pTreasury != address(0), P2pYieldProxy__ZeroAddressP2pTreasury()); i_p2pTreasury = _p2pTreasury; require (_allowedCalldataChecker != address(0), P2pYieldProxy__ZeroAllowedCalldataChecker()); i_allowedCalldataChecker = IAllowedCalldataChecker(_allowedCalldataChecker); } /// @inheritdoc IP2pYieldProxy function initialize( address _client, uint96 _clientBasisPoints ) external initializer onlyFactory { __ReentrancyGuard_init(); require( _clientBasisPoints > 0 && _clientBasisPoints <= 10_000, P2pYieldProxy__InvalidClientBasisPoints(_clientBasisPoints) ); s_client = _client; s_clientBasisPoints = _clientBasisPoints; emit P2pYieldProxy__Initialized(); } /// @inheritdoc IP2pYieldProxy function deposit(address _asset, uint256 _amount) external virtual; /// @notice Deposit assets into yield protocol /// @param _yieldProtocolAddress yield protocol address /// @param _yieldProtocolDepositCalldata calldata for deposit function of yield protocol /// @param _asset asset to deposit /// @param _amount amount to deposit function _deposit( address _yieldProtocolAddress, bytes memory _yieldProtocolDepositCalldata, address _asset, uint256 _amount ) internal onlyFactory { require (_asset != address(0), P2pYieldProxy__ZeroAddressAsset()); require (_amount > 0, P2pYieldProxy__ZeroAssetAmount()); address client = s_client; uint256 assetAmountBefore = IERC20(_asset).balanceOf(address(this)); // transfer tokens into Proxy IERC20(_asset).safeTransferFrom( client, address(this), _amount ); uint256 assetAmountAfter = IERC20(_asset).balanceOf(address(this)); uint256 actualAmount = assetAmountAfter - assetAmountBefore; require ( actualAmount == _amount, P2pYieldProxy__DifferentActuallyDepositedAmount(_amount, actualAmount) ); // no support for fee-on-transfer or rebasing tokens uint256 totalDepositedAfter = s_totalDeposited[_asset] + actualAmount; s_totalDeposited[_asset] = totalDepositedAfter; emit P2pYieldProxy__Deposited( _yieldProtocolAddress, _asset, actualAmount, totalDepositedAfter ); IERC20(_asset).safeIncreaseAllowance( _yieldProtocolAddress, actualAmount ); _yieldProtocolAddress.functionCall(_yieldProtocolDepositCalldata); } /// @notice Withdraw assets from yield protocol /// @param _yieldProtocolAddress yield protocol address /// @param _asset ERC-20 asset address /// @param _yieldProtocolWithdrawalCalldata calldata for withdraw function of yield protocol function _withdraw( address _yieldProtocolAddress, address _asset, bytes memory _yieldProtocolWithdrawalCalldata ) internal { _withdraw(_yieldProtocolAddress, _asset, _yieldProtocolWithdrawalCalldata, false); } /// @notice Withdraw assets from yield protocol /// @param _yieldProtocolAddress yield protocol address /// @param _asset ERC-20 asset address /// @param _yieldProtocolWithdrawalCalldata calldata for withdraw function of yield protocol /// @param _rewardsOnly if true, prioritize treating the withdrawal as profit (used by operator reward flows) function _withdraw( address _yieldProtocolAddress, address _asset, bytes memory _yieldProtocolWithdrawalCalldata, bool _rewardsOnly ) internal nonReentrant { int256 accruedRewardsBefore = calculateAccruedRewards(_yieldProtocolAddress, _asset); uint256 assetAmountBefore = IERC20(_asset).balanceOf(address(this)); // withdraw assets from Protocol _yieldProtocolAddress.functionCall(_yieldProtocolWithdrawalCalldata); uint256 assetAmountAfter = IERC20(_asset).balanceOf(address(this)); uint256 newAssetAmount = assetAmountAfter - assetAmountBefore; Withdrawn memory withdrawn = s_totalWithdrawn[_asset]; bool isClient = msg.sender == s_client; uint256 remainingPrincipal = s_totalDeposited[_asset] > withdrawn.amount ? s_totalDeposited[_asset] - withdrawn.amount : 0; bool isClosingWithdrawal = isClient && withdrawn.amount + newAssetAmount >= s_totalDeposited[_asset]; uint256 positiveAccruedRewards = accruedRewardsBefore > 0 ? uint256(accruedRewardsBefore) : 0; uint256 profitFromAccrued = newAssetAmount > positiveAccruedRewards ? positiveAccruedRewards : newAssetAmount; uint256 remainingAfterAccrued = newAssetAmount - profitFromAccrued; uint256 principalPortion; uint256 profitPortion; if (_rewardsOnly) { profitPortion = profitFromAccrued; uint256 remainingAfterProfit = newAssetAmount - profitPortion; principalPortion = remainingAfterProfit > remainingPrincipal ? remainingPrincipal : remainingAfterProfit; } else { if (isClosingWithdrawal) { if (newAssetAmount > remainingPrincipal) { principalPortion = remainingPrincipal; profitPortion = newAssetAmount - remainingPrincipal; } else { principalPortion = newAssetAmount; profitPortion = 0; } } else { principalPortion = remainingAfterAccrued > remainingPrincipal ? remainingPrincipal : remainingAfterAccrued; uint256 extraProfit = remainingAfterAccrued - principalPortion; profitPortion = profitFromAccrued + extraProfit; } } uint256 totalWithdrawnBefore = uint256(withdrawn.amount); uint256 totalWithdrawnAfter = totalWithdrawnBefore + principalPortion; // update total withdrawn withdrawn.amount = uint208(totalWithdrawnAfter); withdrawn.lastFeeCollectionTime = uint48(block.timestamp); s_totalWithdrawn[_asset] = withdrawn; uint256 p2pAmount; if (profitPortion > 0) { // That extra 9999 ensures that any nonzero remainder will push the result up by 1 (ceiling division). p2pAmount = calculateP2pFeeAmount(profitPortion); } uint256 clientAmount = newAssetAmount - p2pAmount; if (p2pAmount > 0) { IERC20(_asset).safeTransfer(i_p2pTreasury, p2pAmount); } // clientAmount must be > 0 at this point IERC20(_asset).safeTransfer(s_client, clientAmount); emit P2pYieldProxy__Withdrawn( _yieldProtocolAddress, _yieldProtocolAddress, _asset, newAssetAmount, totalWithdrawnAfter, int256(profitPortion), p2pAmount, clientAmount ); } /// @inheritdoc IP2pYieldProxy function callAnyFunction( address _yieldProtocolAddress, bytes calldata _yieldProtocolCalldata ) external onlyClient nonReentrant calldataShouldBeAllowed(_yieldProtocolAddress, _yieldProtocolCalldata) { emit P2pYieldProxy__CalledAsAnyFunction(_yieldProtocolAddress); _yieldProtocolAddress.functionCall(_yieldProtocolCalldata); } /// @notice Returns function selector (first 4 bytes of data) /// @param _data calldata (encoded signature + arguments) /// @return functionSelector function selector function _getFunctionSelector( bytes calldata _data ) private pure returns (bytes4 functionSelector) { require (_data.length >= 4, P2pYieldProxy__DataTooShort()); return bytes4(_data[:4]); } /// @inheritdoc IP2pYieldProxy function getFactory() external view returns (address) { return address(i_factory); } /// @inheritdoc IP2pYieldProxy function getP2pTreasury() external view returns (address) { return i_p2pTreasury; } /// @inheritdoc IP2pYieldProxy function getClient() external view returns (address) { return s_client; } /// @inheritdoc IP2pYieldProxy function getClientBasisPoints() external view returns (uint96) { return s_clientBasisPoints; } /// @inheritdoc IP2pYieldProxy function getTotalDeposited(address _asset) external view returns (uint256) { return s_totalDeposited[_asset]; } /// @inheritdoc IP2pYieldProxy function getTotalWithdrawn(address _asset) external view returns (uint256) { return s_totalWithdrawn[_asset].amount; } function getUserPrincipal(address _asset) public view returns(uint256) { uint256 totalDeposited = s_totalDeposited[_asset]; uint256 totalWithdrawn = s_totalWithdrawn[_asset].amount; if (totalDeposited > totalWithdrawn) { return totalDeposited - totalWithdrawn; } return 0; } function calculateAccruedRewards(address _yieldProtocolAddress, address _asset) public view virtual returns(int256) { uint256 currentAmount = _getCurrentAssetAmount(_yieldProtocolAddress, _asset); uint256 userPrincipal = getUserPrincipal(_asset); return int256(currentAmount) - int256(userPrincipal); } function _getCurrentAssetAmount(address _yieldProtocolAddress, address _asset) internal view virtual returns (uint256); function getLastFeeCollectionTime(address _asset) public view returns(uint48) { return s_totalWithdrawn[_asset].lastFeeCollectionTime; } /// @notice Calculates P2P treasury fee amount using ceiling division /// @param _amount amount /// @return p2pFeeAmount p2p fee amount function calculateP2pFeeAmount(uint256 _amount) internal view returns (uint256 p2pFeeAmount) { if (_amount == 0) return 0; p2pFeeAmount = (_amount * (10_000 - s_clientBasisPoints) + 9999) / 10_000; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IP2pYieldProxy).interfaceId || super.supportsInterface(interfaceId); } }
IP2pYieldProxyFactory.sol 90 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../common/IAllowedCalldataChecker.sol"; /// @dev External interface of P2pYieldProxyFactory interface IP2pYieldProxyFactory is IAllowedCalldataChecker, IERC165 { /// @dev Emitted when the P2pSigner is transferred event P2pYieldProxyFactory__P2pSignerTransferred( address indexed _previousP2pSigner, address indexed _newP2pSigner ); /// @dev Emitted when the deposit is made event P2pYieldProxyFactory__Deposited( address indexed _client, uint96 indexed _clientBasisPoints ); /// @dev Emitted when the a new proxy is created event P2pYieldProxyFactory__ProxyCreated( address _proxy, address _client, uint96 _clientBasisPoints ); /// @notice Deposits a client supplied asset into the underlying yield protocol via a proxy. /// @param _asset Address of the ERC-20 asset to deposit on behalf of the client. /// @param _amount Amount of `_asset` to move from the client to the proxy and forward to the yield protocol. /// @param _clientBasisPoints Fee share expressed in basis points (out of 10_000) that the client keeps. /// @param _p2pSignerSigDeadline Expiration timestamp for the signer approval accompanying this deposit. /// @param _p2pSignerSignature Off-chain signature authorising the deposit parameters from the designated signer. /// @return p2pYieldProxyAddress Deterministic proxy address used for the client after the deposit is processed. function deposit( address _asset, uint256 _amount, uint96 _clientBasisPoints, uint256 _p2pSignerSigDeadline, bytes calldata _p2pSignerSignature ) external returns (address p2pYieldProxyAddress); /// @notice Predicts the deterministic proxy address that will serve a specific client and fee configuration. /// @param _client Address of the client that will control the proxy. /// @param _clientBasisPoints Fee share (in basis points) that the client keeps from accrued rewards. /// @return proxyAddress Deterministic address where the proxy will be deployed or already lives. function predictP2pYieldProxyAddress( address _client, uint96 _clientBasisPoints ) external view returns (address proxyAddress); /// @notice Updates the recognised P2P signer that authorises new deposits. /// @param _newP2pSigner Address of the replacement signer allowed to approve deposits. function transferP2pSigner( address _newP2pSigner ) external; /// @notice Returns the implementation contract used as the template for future proxies. /// @return referenceProxy Address of the proxy implementation clone target. function getReferenceP2pYieldProxy() external view returns (address referenceProxy); /// @notice Computes the EIP-191 hash that must be signed by the authorised P2P signer for a deposit. /// @param _client Address of the client that will control the proxy. /// @param _clientBasisPoints Fee share (in basis points) that the client keeps from accrued rewards. /// @param _p2pSignerSigDeadline Expiration timestamp of the off-chain approval. /// @return signerHash Message hash that should be signed by the configured P2P signer. function getHashForP2pSigner( address _client, uint96 _clientBasisPoints, uint256 _p2pSignerSigDeadline ) external view returns (bytes32 signerHash); /// @notice Returns the address authorised to co-sign new deposits. /// @return signer Address of the currently configured P2P signer. function getP2pSigner() external view returns (address signer); /// @notice Returns the operator allowed to manage privileged actions on the factory. /// @return operator Address of the current P2P operator. function getP2pOperator() external view returns (address operator); /// @notice Returns every proxy address created by this factory. /// @return proxies Array containing the addresses of all instantiated proxies. function getAllProxies() external view returns (address[] memory proxies); }
IResolvStaking.sol 45 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
interface IResolvStaking {
function deposit(
uint256 _amount,
address _receiver
) external;
function withdraw(
bool _claimRewards,
address _receiver
) external;
function initiateWithdrawal(uint256 _amount) external;
function claim(address _user, address _receiver) external;
function updateCheckpoint(address _user) external;
function depositReward(
address _token,
uint256 _amount,
uint256 _duration
) external;
function setRewardsReceiver(address _receiver) external;
function setCheckpointDelegatee(address _delegatee) external;
function setClaimEnabled(bool _enabled) external;
function setWithdrawalCooldown(uint256 _cooldown) external;
function getUserAccumulatedRewardPerToken(address _user, address _token) external view returns (uint256 amount);
function getUserClaimableAmounts(address _user, address _token) external view returns (uint256 amount);
function getUserEffectiveBalance(address _user) external view returns (uint256 balance);
function claimEnabled() external view returns (bool isEnabled);
function rewardTokens(uint256 _index) external view returns (address token);
}
IStUSR.sol 20 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
interface IStUSR {
event Deposit(address indexed _sender, address indexed _receiver, uint256 _usrAmount, uint256 _shares);
event Withdraw(address indexed _sender, address indexed _receiver, uint256 _usrAmount, uint256 _shares);
error InvalidDepositAmount(uint256 _usrAmount);
function deposit(uint256 _usrAmount) external;
function withdraw(uint256 _usrAmount) external;
function withdrawAll() external;
function previewDeposit(uint256 _usrAmount) external view returns (uint256 shares);
function previewWithdraw(uint256 _usrAmount) external view returns (uint256 shares);
}
IStakedTokenDistributor.sol 23 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
// Allows anyone to claim a token if they exist in a merkle root.
interface IStakedTokenDistributor {
event Claimed(uint256 index, address account, uint256 amount);
event AddedToBlacklist(address account);
event RemovedFromBlacklist(address account);
event Withdrawn(address reciever);
error AlreadyClaimed();
error InvalidProof();
error Blacklisted();
error EndTimeInPast();
error ClaimWindowFinished();
error NoWithdrawDuringClaim();
error ZeroAddress();
// Claim the given amount of the token to the contract caller. Reverts if the inputs are invalid.
function claim(uint256 index, uint256 amount, bytes32[] calldata merkleProof) external;
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
}
IP2pResolvProxy.sol 95 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; /// @title Interface for the P2P Resolv proxy adapter /// @notice Exposes Resolv specific helper flows to withdraw and claim on behalf of a client. interface IP2pResolvProxy { /// @notice Withdraws a specific amount of USR on behalf of the client. /// @param _amount Amount of USR (in wei) requested by the client. function withdrawUSR(uint256 _amount) external; /// @notice Withdraws the entire USR balance held by the proxy for the client. function withdrawAllUSR() external; /// @notice Initiates a delayed withdrawal request for RESOLV from the staking contract. /// @param _amount Amount of staked RESOLV shares to mark for withdrawal. function initiateWithdrawalRESOLV(uint256 _amount) external; /// @notice Completes a pending RESOLV withdrawal, distributing proceeds per the fee split. function withdrawRESOLV() external; /// @notice Claims rewards from the Resolv StakedTokenDistributor on behalf of the client/operator. /// @param _index Index of the Merkle proof entry. /// @param _amount Amount of rewards being claimed. /// @param _merkleProof Merkle proof validating the claim eligibility. function claimStakedTokenDistributor( uint256 _index, uint256 _amount, bytes32[] calldata _merkleProof ) external; /// @notice Claims accrued reward tokens directly from ResolvStaking and splits them per the fee schedule. function claimRewardTokens() external; function setStakedTokenDistributor(address _stakedTokenDistributor) external; function getStakedTokenDistributor() external view returns (address); /// @notice Emitted when rewards are claimed from the distributor. /// @param _amount Amount of rewards paid out for the claim. event P2pResolvProxy__Claimed(uint256 _amount); /// @notice Emitted when RESOLV is deposited into ResolvStaking via the proxy. /// @param amount Amount of RESOLV deposited on behalf of the client. event P2pResolvProxy__ResolvDeposited(uint256 amount); /// @notice Emitted when a RESOLV withdrawal without rewards is forwarded directly to the client. /// @param caller Address that triggered the withdrawal completion. event P2pResolvProxy__ResolvPrincipalWithdrawal(address indexed caller); /// @notice Emitted when staking reward tokens are claimed and split. /// @param token Reward token address. /// @param amount Total reward amount claimed for `token`. /// @param p2pAmount Portion forwarded to the P2P treasury. /// @param clientAmount Portion forwarded to the client. event P2pResolvProxy__RewardTokensClaimed( address indexed token, uint256 amount, uint256 p2pAmount, uint256 clientAmount ); /// @notice Emitted when a claimed airdrop withdrawal is processed and distributed. /// @param expectedRewardAmount The tracked pending reward amount from the distributor. /// @param actualRewardAmount Actual RESOLV amount received in the withdrawal. /// @param p2pAmount Portion of the reward sent to the treasury. /// @param clientAmount Portion of the reward sent to the client. /// @param principalForwarded The principal portion released to the client. event P2pResolvProxy__DistributorRewardsReleased( uint256 expectedRewardAmount, uint256 actualRewardAmount, uint256 p2pAmount, uint256 clientAmount, uint256 principalForwarded ); /// @notice Sweeps accumulated reward tokens from the proxy to the client. /// @param _token Address of the ERC-20 token to sweep. function sweepRewardToken(address _token) external; /// @notice Emitted when the staked token distributor address is updated. /// @param previousStakedTokenDistributor The previous distributor address. /// @param newStakedTokenDistributor The new distributor address. event P2pResolvProxy__StakedTokenDistributorUpdated( address indexed previousStakedTokenDistributor, address indexed newStakedTokenDistributor ); /// @notice Emitted when reward tokens are swept to the client. /// @param token The token address that was swept. /// @param amount The amount swept to the client. event P2pResolvProxy__RewardTokenSwept(address indexed token, uint256 amount); }
ECDSA.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity 0.8.30;
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));
}
}
IERC1271.sol 19 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity 0.8.30;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity 0.8.30;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
P2pOperator.sol 89 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT // Copy and rename of OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity 0.8.30; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an P2pOperator) that can be granted exclusive access to * specific functions. * * The initial P2pOperator is set to the address provided by the deployer. This can * later be changed with {transferP2pOperator}. * * This module is used through inheritance. It will make available the modifier * `onlyP2pOperator`, which can be applied to your functions to restrict their use to * the P2pOperator. */ abstract contract P2pOperator { address private s_p2pOperator; /** * @dev The caller account is not authorized to perform an operation. */ error P2pOperator__UnauthorizedAccount(address _account); /** * @dev The P2pOperator is not a valid P2pOperator account. (eg. `address(0)`) */ error P2pOperator__InvalidP2pOperator(address _p2pOperator); event P2pOperator__P2pOperatorTransferred(address indexed _previousP2pOperator, address indexed _newP2pOperator); /** * @dev Initializes the contract setting the address provided by the deployer as the initial P2pOperator. */ constructor(address _initialP2pOperator) { if (_initialP2pOperator == address(0)) { revert P2pOperator__InvalidP2pOperator(address(0)); } _transferP2pOperator(_initialP2pOperator); } /** * @dev Throws if called by any account other than the P2pOperator. */ modifier onlyP2pOperator() { _checkP2pOperator(); _; } /** * @dev Returns the address of the current P2pOperator. */ function getP2pOperator() public view virtual returns (address) { return s_p2pOperator; } /** * @dev Throws if the sender is not the P2pOperator. */ function _checkP2pOperator() internal view virtual { if (s_p2pOperator != msg.sender) { revert P2pOperator__UnauthorizedAccount(msg.sender); } } /** * @dev Transfers P2pOperator of the contract to a new account (`_newP2pOperator`). * Can only be called by the current P2pOperator. */ function transferP2pOperator(address _newP2pOperator) public virtual onlyP2pOperator { if (_newP2pOperator == address(0)) { revert P2pOperator__InvalidP2pOperator(address(0)); } _transferP2pOperator(_newP2pOperator); } /** * @dev Transfers P2pOperator of the contract to a new account (`_newP2pOperator`). * Internal function without access restriction. */ function _transferP2pOperator(address _newP2pOperator) internal virtual { address oldP2pOperator = s_p2pOperator; s_p2pOperator = _newP2pOperator; emit P2pOperator__P2pOperatorTransferred(oldP2pOperator, _newP2pOperator); } }
Initializable.sol 166 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity 0.8.30;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
IAllowedCalldataChecker.sol 20 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; /// @title IAllowedCalldataChecker /// @author P2P Validator <[email protected]> /// @notice Interface for checking if a calldata is allowed interface IAllowedCalldataChecker { /// @notice Checks if the calldata is allowed /// @param _target The address of the yield protocol /// @param _selector The selector of the function /// @param _calldataAfterSelector The calldata after the selector function checkCalldata( address _target, bytes4 _selector, bytes calldata _calldataAfterSelector ) external view; }
ReentrancyGuardUpgradeable.sol 89 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity 0.8.30;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
SafeERC20.sol 116 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity 0.8.30;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
ERC165Checker.sol 123 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.2) (utils/introspection/ERC165Checker.sol)
pragma solidity 0.8.30;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// prepare call
bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
// perform static call
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
returnSize := returndatasize()
returnValue := mload(0x00)
}
return success && returnSize >= 0x20 && returnValue > 0;
}
}
P2pStructs.sol 12 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; /// @dev 256 bit struct /// @member Amount /// @member lastFeeCollectionTime Last Fee Collection Time struct Withdrawn { uint208 amount; uint48 lastFeeCollectionTime; }
IP2pYieldProxy.sol 87 lines
// SPDX-FileCopyrightText: 2025 P2P Validator <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.30; import "../@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @dev External interface of P2pYieldProxy declared to support ERC165 detection. interface IP2pYieldProxy is IERC165 { /// @notice Emitted when the P2pYieldProxy is initialized event P2pYieldProxy__Initialized(); /// @notice Emitted when a deposit is made event P2pYieldProxy__Deposited( address indexed _yieldProtocolAddress, address indexed _asset, uint256 _amount, uint256 _totalDepositedAfter ); /// @notice Emitted when a withdrawal is made event P2pYieldProxy__Withdrawn( address indexed _yieldProtocolAddress, address indexed _vault, address indexed _asset, uint256 _assets, uint256 _totalWithdrawnAfter, int256 _accruedRewards, uint256 _p2pAmount, uint256 _clientAmount ); /// @notice Emitted when an arbitrary allowed function is called event P2pYieldProxy__CalledAsAnyFunction( address indexed _yieldProtocolAddress ); /// @notice Initializes the P2pYieldProxy /// @param _client The client address /// @param _clientBasisPoints The client basis points function initialize( address _client, uint96 _clientBasisPoints ) external; /// @notice Deposits the given asset amount into the underlying yield protocol. /// @param _asset Address of the ERC-20 asset the client wants to supply. /// @param _amount Amount of `_asset` in wei requested for deposit. function deposit(address _asset, uint256 _amount) external; /// @notice Calls an arbitrary allowed function /// @param _yieldProtocolAddress The address of the yield protocol /// @param _yieldProtocolCalldata The calldata to call the yield protocol function callAnyFunction( address _yieldProtocolAddress, bytes calldata _yieldProtocolCalldata ) external; /// @notice Gets the factory address /// @return The factory address function getFactory() external view returns (address); /// @notice Gets the P2pTreasury address /// @return The P2pTreasury address function getP2pTreasury() external view returns (address); /// @notice Gets the client address /// @return The client address function getClient() external view returns (address); /// @notice Gets the client basis points /// @return The client basis points function getClientBasisPoints() external view returns (uint96); /// @notice Gets the total deposited for an asset /// @param _asset The asset address /// @return The total deposited function getTotalDeposited(address _asset) external view returns (uint256); /// @notice Gets the total withdrawn for an asset /// @param _asset The asset address /// @return The total withdrawn function getTotalWithdrawn(address _asset) external view returns (uint256); }
Strings.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity 0.8.30;
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));
}
}
AddressUpgradeable.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity 0.8.30;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
}
}
}
IERC20.sol 82 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity 0.8.30;
/**
* @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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
uint256 amount
) external returns (bool);
}
draft-IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity 0.8.30;
/**
* @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.
*/
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].
*/
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);
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity 0.8.30;
/**
* @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);
}
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity 0.8.30;
/**
* @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);
}
}
}
Read Contract
checkCalldata 0x34b5ee92
getAllProxies 0x883edfb8 → address[]
getHashForP2pSigner 0x7714e03e → bytes32
getP2pOperator 0x0a1ca464 → address
getP2pSigner 0x4258b0b9 → address
getPendingP2pOperator 0x739e39b3 → address
getReferenceP2pYieldProxy 0x9572269e → address
predictP2pYieldProxyAddress 0x84baa36c → address
supportsInterface 0x01ffc9a7 → bool
Write Contract 5 functions
These functions modify contract state and require a wallet transaction to execute.
acceptP2pOperator 0x766248ed
No parameters
deposit 0xb3fb6579
address _asset
uint256 _amount
uint96 _clientBasisPoints
uint256 _p2pSignerSigDeadline
bytes _p2pSignerSignature
returns: address
initialize 0x8129fc1c
No parameters
transferP2pOperator 0x168b258a
address _newP2pOperator
transferP2pSigner 0xb1094ea8
address _newP2pSigner
Recent Transactions
No transactions found for this address