diff --git a/contracts/base/BasePaymaster.sol b/contracts/base/BasePaymaster.sol index 8b7e1e0..b3d487a 100644 --- a/contracts/base/BasePaymaster.sol +++ b/contracts/base/BasePaymaster.sol @@ -13,6 +13,7 @@ import "account-abstraction/contracts/core/UserOperationLib.sol"; * provides helper methods for staking. * Validates that the postOp is called only by the entryPoint. */ + abstract contract BasePaymaster is IPaymaster, SoladyOwnable { IEntryPoint public immutable entryPoint; @@ -25,10 +26,44 @@ abstract contract BasePaymaster is IPaymaster, SoladyOwnable { entryPoint = _entryPoint; } - //sanity check: make sure this EntryPoint was compiled against the same - // IEntryPoint of this paymaster - function _validateEntryPointInterface(IEntryPoint _entryPoint) internal virtual { - require(IERC165(address(_entryPoint)).supportsInterface(type(IEntryPoint).interfaceId), "IEntryPoint interface mismatch"); + /** + * Add stake for this paymaster. + * This method can also carry eth value to add to the current stake. + * @param unstakeDelaySec - The unstake delay for this paymaster. Can only be increased. + */ + function addStake(uint32 unstakeDelaySec) external payable onlyOwner { + entryPoint.addStake{ value: msg.value }(unstakeDelaySec); + } + + /** + * Unlock the stake, in order to withdraw it. + * The paymaster can't serve requests once unlocked, until it calls addStake again + */ + function unlockStake() external onlyOwner { + entryPoint.unlockStake(); + } + + /** + * Withdraw the entire paymaster's stake. + * stake must be unlocked first (and then wait for the unstakeDelay to be over) + * @param withdrawAddress - The address to send withdrawn value. + */ + function withdrawStake(address payable withdrawAddress) external onlyOwner { + entryPoint.withdrawStake(withdrawAddress); + } + + /// @inheritdoc IPaymaster + function postOp( + PostOpMode mode, + bytes calldata context, + uint256 actualGasCost, + uint256 actualUserOpFeePerGas + ) + external + override + { + _requireFromEntryPoint(); + _postOp(mode, context, actualGasCost, actualUserOpFeePerGas); } /// @inheritdoc IPaymaster @@ -36,11 +71,47 @@ abstract contract BasePaymaster is IPaymaster, SoladyOwnable { PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost - ) external override returns (bytes memory context, uint256 validationData) { + ) + external + override + returns (bytes memory context, uint256 validationData) + { _requireFromEntryPoint(); return _validatePaymasterUserOp(userOp, userOpHash, maxCost); } + /** + * Add a deposit for this paymaster, used for paying for transaction fees. + */ + function deposit() external payable virtual { + entryPoint.depositTo{ value: msg.value }(address(this)); + } + + /** + * Withdraw value from the deposit. + * @param withdrawAddress - Target to send to. + * @param amount - Amount to withdraw. + */ + function withdrawTo(address payable withdrawAddress, uint256 amount) external virtual onlyOwner { + entryPoint.withdrawTo(withdrawAddress, amount); + } + + /** + * Return current paymaster's deposit on the entryPoint. + */ + function getDeposit() public view returns (uint256) { + return entryPoint.balanceOf(address(this)); + } + + //sanity check: make sure this EntryPoint was compiled against the same + // IEntryPoint of this paymaster + function _validateEntryPointInterface(IEntryPoint _entryPoint) internal virtual { + require( + IERC165(address(_entryPoint)).supportsInterface(type(IEntryPoint).interfaceId), + "IEntryPoint interface mismatch" + ); + } + /** * Validate a user operation. * @param userOp - The user operation. @@ -51,18 +122,10 @@ abstract contract BasePaymaster is IPaymaster, SoladyOwnable { PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost - ) internal virtual returns (bytes memory context, uint256 validationData); - - /// @inheritdoc IPaymaster - function postOp( - PostOpMode mode, - bytes calldata context, - uint256 actualGasCost, - uint256 actualUserOpFeePerGas - ) external override { - _requireFromEntryPoint(); - _postOp(mode, context, actualGasCost, actualUserOpFeePerGas); - } + ) + internal + virtual + returns (bytes memory context, uint256 validationData); /** * Post-operation handler. @@ -84,68 +147,19 @@ abstract contract BasePaymaster is IPaymaster, SoladyOwnable { bytes calldata context, uint256 actualGasCost, uint256 actualUserOpFeePerGas - ) internal virtual { + ) + internal + virtual + { (mode, context, actualGasCost, actualUserOpFeePerGas); // unused params // subclass must override this method if validatePaymasterUserOp returns a context revert("must override"); } - /** - * Add a deposit for this paymaster, used for paying for transaction fees. - */ - function deposit() public virtual payable { - entryPoint.depositTo{value: msg.value}(address(this)); - } - - /** - * Withdraw value from the deposit. - * @param withdrawAddress - Target to send to. - * @param amount - Amount to withdraw. - */ - function withdrawTo( - address payable withdrawAddress, - uint256 amount - ) public virtual onlyOwner { - entryPoint.withdrawTo(withdrawAddress, amount); - } - - /** - * Add stake for this paymaster. - * This method can also carry eth value to add to the current stake. - * @param unstakeDelaySec - The unstake delay for this paymaster. Can only be increased. - */ - function addStake(uint32 unstakeDelaySec) external payable onlyOwner { - entryPoint.addStake{value: msg.value}(unstakeDelaySec); - } - - /** - * Return current paymaster's deposit on the entryPoint. - */ - function getDeposit() public view returns (uint256) { - return entryPoint.balanceOf(address(this)); - } - - /** - * Unlock the stake, in order to withdraw it. - * The paymaster can't serve requests once unlocked, until it calls addStake again - */ - function unlockStake() external onlyOwner { - entryPoint.unlockStake(); - } - - /** - * Withdraw the entire paymaster's stake. - * stake must be unlocked first (and then wait for the unstakeDelay to be over) - * @param withdrawAddress - The address to send withdrawn value. - */ - function withdrawStake(address payable withdrawAddress) external onlyOwner { - entryPoint.withdrawStake(withdrawAddress); - } - /** * Validate the call is made from a valid entrypoint */ function _requireFromEntryPoint() internal virtual { require(msg.sender == address(entryPoint), "Sender not EntryPoint"); } -} \ No newline at end of file +} diff --git a/contracts/interfaces/IBiconomySponsorshipPaymaster.sol b/contracts/interfaces/IBiconomySponsorshipPaymaster.sol index ed4da78..5f47d1a 100644 --- a/contracts/interfaces/IBiconomySponsorshipPaymaster.sol +++ b/contracts/interfaces/IBiconomySponsorshipPaymaster.sol @@ -2,18 +2,16 @@ pragma solidity ^0.8.26; interface IBiconomySponsorshipPaymaster { - event PostopCostChanged(uint256 indexed _oldValue, uint256 indexed _newValue); - event FixedPriceMarkupChanged(uint32 indexed _oldValue, uint32 indexed _newValue); + event PostopCostChanged(uint256 indexed oldValue, uint256 indexed newValue); + event FixedPriceMarkupChanged(uint32 indexed oldValue, uint32 indexed newValue); - event VerifyingSignerChanged(address indexed _oldSigner, address indexed _newSigner, address indexed _actor); + event VerifyingSignerChanged(address indexed oldSigner, address indexed newSigner, address indexed actor); - event FeeCollectorChanged( - address indexed _oldFeeCollector, address indexed _newFeeCollector, address indexed _actor - ); - event GasDeposited(address indexed _paymasterId, uint256 indexed _value); - event GasWithdrawn(address indexed _paymasterId, address indexed _to, uint256 indexed _value); - event GasBalanceDeducted(address indexed _paymasterId, uint256 indexed _charge, bytes32 indexed userOpHash); - event PremiumCollected(address indexed _paymasterId, uint256 indexed _premium); + event FeeCollectorChanged(address indexed oldFeeCollector, address indexed newFeeCollector, address indexed actor); + event GasDeposited(address indexed paymasterId, uint256 indexed value); + event GasWithdrawn(address indexed paymasterId, address indexed to, uint256 indexed value); + event GasBalanceDeducted(address indexed paymasterId, uint256 indexed charge, bytes32 indexed userOpHash); + event PremiumCollected(address indexed paymasterId, uint256 indexed premium); event Received(address indexed sender, uint256 value); - event TokensWithdrawn(address indexed _token, address indexed _to, uint256 indexed _amount, address actor); -} \ No newline at end of file + event TokensWithdrawn(address indexed token, address indexed to, uint256 indexed amount, address actor); +} diff --git a/contracts/mocks/Imports.sol b/contracts/mocks/Imports.sol index 7b0976a..131ae80 100644 --- a/contracts/mocks/Imports.sol +++ b/contracts/mocks/Imports.sol @@ -8,4 +8,3 @@ import "account-abstraction/contracts/core/EntryPointSimulations.sol"; import "@biconomy-devx/erc7579-msa/contracts/SmartAccount.sol"; import "@biconomy-devx/erc7579-msa/contracts/factory/AccountFactory.sol"; - diff --git a/contracts/mocks/MockValidator.sol b/contracts/mocks/MockValidator.sol index 2c3d359..7682958 100644 --- a/contracts/mocks/MockValidator.sol +++ b/contracts/mocks/MockValidator.sol @@ -1,3 +1,3 @@ pragma solidity ^0.8.26; -import "@biconomy-devx/erc7579-msa/test/foundry/mocks/MockValidator.sol"; \ No newline at end of file +import "@biconomy-devx/erc7579-msa/test/foundry/mocks/MockValidator.sol"; diff --git a/contracts/references/SampleVerifyingPaymaster.sol b/contracts/references/SampleVerifyingPaymaster.sol index 46f12bf..1522c6e 100644 --- a/contracts/references/SampleVerifyingPaymaster.sol +++ b/contracts/references/SampleVerifyingPaymaster.sol @@ -20,7 +20,6 @@ import "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; * - the account checks a signature to prove identity and account ownership. */ contract VerifyingPaymaster is BasePaymaster { - using UserOperationLib for PackedUserOperation; address public immutable verifyingSigner; @@ -40,19 +39,25 @@ contract VerifyingPaymaster is BasePaymaster { * note that this signature covers all fields of the UserOperation, except the "paymasterAndData", * which will carry the signature itself. */ - function getHash(PackedUserOperation calldata userOp, uint48 validUntil, uint48 validAfter) - public view returns (bytes32) { + function getHash( + PackedUserOperation calldata userOp, + uint48 validUntil, + uint48 validAfter + ) + public + view + returns (bytes32) + { //can't use userOp.hash(), since it contains also the paymasterAndData itself. address sender = userOp.getSender(); - return - keccak256( + return keccak256( abi.encode( sender, userOp.nonce, keccak256(userOp.initCode), keccak256(userOp.callData), userOp.accountGasLimits, - uint256(bytes32(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_DATA_OFFSET])), + uint256(bytes32(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET:PAYMASTER_DATA_OFFSET])), userOp.preVerificationGas, userOp.gasFees, block.chainid, @@ -63,6 +68,15 @@ contract VerifyingPaymaster is BasePaymaster { ); } + function parsePaymasterAndData(bytes calldata paymasterAndData) + public + pure + returns (uint48 validUntil, uint48 validAfter, bytes calldata signature) + { + (validUntil, validAfter) = abi.decode(paymasterAndData[VALID_TIMESTAMP_OFFSET:], (uint48, uint48)); + signature = paymasterAndData[SIGNATURE_OFFSET:]; + } + /** * verify our external signer signed this request. * the "paymasterAndData" is expected to be the paymaster and a signature over the entire request params @@ -70,14 +84,27 @@ contract VerifyingPaymaster is BasePaymaster { * paymasterAndData[20:84] : abi.encode(validUntil, validAfter) * paymasterAndData[84:] : signature */ - function _validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32 /*userOpHash*/, uint256 requiredPreFund) - internal view override returns (bytes memory context, uint256 validationData) { + function _validatePaymasterUserOp( + PackedUserOperation calldata userOp, + bytes32, /*userOpHash*/ + uint256 requiredPreFund + ) + internal + view + override + returns (bytes memory context, uint256 validationData) + { (requiredPreFund); - (uint48 validUntil, uint48 validAfter, bytes calldata signature) = parsePaymasterAndData(userOp.paymasterAndData); + (uint48 validUntil, uint48 validAfter, bytes calldata signature) = + parsePaymasterAndData(userOp.paymasterAndData); //ECDSA library supports both 64 and 65-byte long signatures. - // we only "require" it here so that the revert reason on invalid signature will be of "VerifyingPaymaster", and not "ECDSA" - require(signature.length == 64 || signature.length == 65, "VerifyingPaymaster: invalid signature length in paymasterAndData"); + // we only "require" it here so that the revert reason on invalid signature will be of "VerifyingPaymaster", and + // not "ECDSA" + require( + signature.length == 64 || signature.length == 65, + "VerifyingPaymaster: invalid signature length in paymasterAndData" + ); bytes32 hash = MessageHashUtils.toEthSignedMessageHash(getHash(userOp, validUntil, validAfter)); //don't revert on signature failure: return SIG_VALIDATION_FAILED @@ -89,9 +116,4 @@ contract VerifyingPaymaster is BasePaymaster { // by the external service prior to signing it. return ("", _packValidationData(false, validUntil, validAfter)); } - - function parsePaymasterAndData(bytes calldata paymasterAndData) public pure returns (uint48 validUntil, uint48 validAfter, bytes calldata signature) { - (validUntil, validAfter) = abi.decode(paymasterAndData[VALID_TIMESTAMP_OFFSET :], (uint48, uint48)); - signature = paymasterAndData[SIGNATURE_OFFSET :]; - } -} \ No newline at end of file +} diff --git a/contracts/sponsorship/SponsorshipPaymasterWithPremium.sol b/contracts/sponsorship/SponsorshipPaymasterWithPremium.sol index 47f7c65..2e3abf4 100644 --- a/contracts/sponsorship/SponsorshipPaymasterWithPremium.sol +++ b/contracts/sponsorship/SponsorshipPaymasterWithPremium.sol @@ -19,16 +19,21 @@ import { IBiconomySponsorshipPaymaster } from "../interfaces/IBiconomySponsorshi * @author livingrockrises * @notice Based on Infinitism 'VerifyingPaymaster' contract * @dev This contract is used to sponsor the transaction fees of the user operations - * Uses a verifying signer to provide the signature if predetermined conditions are met - * regarding the user operation calldata. Also this paymaster is Singleton in nature which + * Uses a verifying signer to provide the signature if predetermined conditions are met + * regarding the user operation calldata. Also this paymaster is Singleton in nature which * means multiple Dapps/Wallet clients willing to sponsor the transactions can share this paymaster. - * Maintains it's own accounting of the gas balance for each Dapp/Wallet client + * Maintains it's own accounting of the gas balance for each Dapp/Wallet client * and Manages it's own deposit on the EntryPoint. */ // @Todo: Add more methods in interface -contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, BiconomySponsorshipPaymasterErrors, IBiconomySponsorshipPaymaster { +contract BiconomySponsorshipPaymaster is + BasePaymaster, + ReentrancyGuard, + BiconomySponsorshipPaymasterErrors, + IBiconomySponsorshipPaymaster +{ using UserOperationLib for PackedUserOperation; using SignatureCheckerLib for address; @@ -42,22 +47,34 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom mapping(address => uint256) public paymasterIdBalances; - constructor(address _owner, IEntryPoint _entryPoint, address _verifyingSigner, address _feeCollector) BasePaymaster(_owner, _entryPoint) { + constructor( + address _owner, + IEntryPoint _entryPoint, + address _verifyingSigner, + address _feeCollector + ) + BasePaymaster(_owner, _entryPoint) + { // TODO // Check for zero address verifyingSigner = _verifyingSigner; feeCollector = _feeCollector; } + receive() external payable { + emit Received(msg.sender, msg.value); + } + /** - * @dev Add a deposit for this paymaster and given paymasterId (Dapp Depositor address), used for paying for transaction fees + * @dev Add a deposit for this paymaster and given paymasterId (Dapp Depositor address), used for paying for + * transaction fees * @param paymasterId dapp identifier for which deposit is being made */ function depositFor(address paymasterId) external payable nonReentrant { if (paymasterId == address(0)) revert PaymasterIdCanNotBeZero(); if (msg.value == 0) revert DepositCanNotBeZero(); paymasterIdBalances[paymasterId] += msg.value; - entryPoint.depositTo{value: msg.value}(address(this)); + entryPoint.depositTo{ value: msg.value }(address(this)); emit GasDeposited(paymasterId, msg.value); } @@ -68,14 +85,15 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom * @notice If _newVerifyingSigner is set to zero address, it will revert with an error. * After setting the new signer address, it will emit an event VerifyingSignerChanged. */ - function setSigner( - address _newVerifyingSigner - ) external payable onlyOwner { + function setSigner(address _newVerifyingSigner) external payable onlyOwner { uint256 size; - assembly { size := extcodesize(_newVerifyingSigner) } - if(size > 0) revert VerifyingSignerCanNotBeContract(); - if (_newVerifyingSigner == address(0)) + assembly { + size := extcodesize(_newVerifyingSigner) + } + if (size > 0) revert VerifyingSignerCanNotBeContract(); + if (_newVerifyingSigner == address(0)) { revert VerifyingSignerCanNotBeZero(); + } address oldSigner = verifyingSigner; assembly { sstore(verifyingSigner.slot, _newVerifyingSigner) @@ -90,9 +108,7 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom * @notice If _newFeeCollector is set to zero address, it will revert with an error. * After setting the new fee collector address, it will emit an event FeeCollectorChanged. */ - function setFeeCollector( - address _newFeeCollector - ) external payable onlyOwner { + function setFeeCollector(address _newFeeCollector) external payable onlyOwner { if (_newFeeCollector == address(0)) revert FeeCollectorCanNotBeZero(); address oldFeeCollector = feeCollector; assembly { @@ -106,41 +122,37 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom * @param value The new value to be set as the unaccountedEPGasOverhead. * @notice only to be called by the owner of the contract. */ - function setPostopCost( - uint48 value - ) external payable onlyOwner { - require(value <= 200000, "Gas overhead too high"); + function setPostopCost(uint48 value) external payable onlyOwner { + require(value <= 200_000, "Gas overhead too high"); uint256 oldValue = postopCost; postopCost = value; emit PostopCostChanged(oldValue, value); } /** - * @dev get the current deposit for paymasterId (Dapp Depositor address) - * @param paymasterId dapp identifier + * @dev Override the default implementation. */ - function getBalance( - address paymasterId - ) external view returns (uint256 balance) { - balance = paymasterIdBalances[paymasterId]; + function deposit() external payable virtual override { + revert("Use depositFor() instead"); } /** - @dev Override the default implementation. + * @dev pull tokens out of paymaster in case they were sent to the paymaster at any point. + * @param token the token deposit to withdraw + * @param target address to send to + * @param amount amount to withdraw */ - function deposit() public payable virtual override { - revert("Use depositFor() instead"); + function withdrawERC20(IERC20 token, address target, uint256 amount) external payable onlyOwner nonReentrant { + _withdrawERC20(token, target, amount); } /** - * @dev Withdraws the specified amount of gas tokens from the paymaster's balance and transfers them to the specified address. + * @dev Withdraws the specified amount of gas tokens from the paymaster's balance and transfers them to the + * specified address. * @param withdrawAddress The address to which the gas tokens should be transferred. * @param amount The amount of gas tokens to withdraw. */ - function withdrawTo( - address payable withdrawAddress, - uint256 amount - ) public override nonReentrant { + function withdrawTo(address payable withdrawAddress, uint256 amount) external override nonReentrant { if (withdrawAddress == address(0)) revert CanNotWithdrawToZeroAddress(); uint256 currentBalance = paymasterIdBalances[msg.sender]; require(amount <= currentBalance, "Sponsorship Paymaster: Insufficient funds to withdraw from gas tank"); @@ -149,6 +161,19 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom emit GasWithdrawn(msg.sender, withdrawAddress, amount); } + function withdrawEth(address payable recipient, uint256 amount) external onlyOwner { + (bool success,) = recipient.call{ value: amount }(""); + require(success, "withdraw failed"); + } + + /** + * @dev get the current deposit for paymasterId (Dapp Depositor address) + * @param paymasterId dapp identifier + */ + function getBalance(address paymasterId) external view returns (uint256 balance) { + balance = paymasterIdBalances[paymasterId]; + } + /** * return the hash we're going to sign off-chain (and validate on-chain) * this method is called by the off-chain service, to sign the request. @@ -156,19 +181,27 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom * note that this signature covers all fields of the UserOperation, except the "paymasterAndData", * which will carry the signature itself. */ - function getHash(PackedUserOperation calldata userOp, address paymasterId, uint48 validUntil, uint48 validAfter, uint32 priceMarkup) - public view returns (bytes32) { + function getHash( + PackedUserOperation calldata userOp, + address paymasterId, + uint48 validUntil, + uint48 validAfter, + uint32 priceMarkup + ) + public + view + returns (bytes32) + { //can't use userOp.hash(), since it contains also the paymasterAndData itself. address sender = userOp.getSender(); - return - keccak256( + return keccak256( abi.encode( sender, userOp.nonce, keccak256(userOp.initCode), keccak256(userOp.callData), userOp.accountGasLimits, - uint256(bytes32(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_DATA_OFFSET])), + uint256(bytes32(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET:PAYMASTER_DATA_OFFSET])), userOp.preVerificationGas, userOp.gasFees, block.chainid, @@ -181,6 +214,61 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom ); } + function parsePaymasterAndData(bytes calldata paymasterAndData) + public + pure + returns ( + address paymasterId, + uint48 validUntil, + uint48 validAfter, + uint32 priceMarkup, + bytes calldata signature + ) + { + paymasterId = address(bytes20(paymasterAndData[VALID_PND_OFFSET:VALID_PND_OFFSET + 20])); + validUntil = uint48(bytes6(paymasterAndData[VALID_PND_OFFSET + 20:VALID_PND_OFFSET + 26])); + validAfter = uint48(bytes6(paymasterAndData[VALID_PND_OFFSET + 26:VALID_PND_OFFSET + 32])); + priceMarkup = uint32(bytes4(paymasterAndData[VALID_PND_OFFSET + 32:VALID_PND_OFFSET + 36])); + signature = paymasterAndData[VALID_PND_OFFSET + 36:]; + } + + /// @notice Performs post-operation tasks, such as deducting the sponsored gas cost from the paymasterId's balance + /// @dev This function is called after a user operation has been executed or reverted. + /// @param context The context containing the token amount and user sender address. + /// @param actualGasCost The actual gas cost of the transaction. + /// @param actualUserOpFeePerGas - the gas price this UserOp pays. This value is based on the UserOp's maxFeePerGas + // and maxPriorityFee (and basefee) + // It is not the same as tx.gasprice, which is what the bundler pays. + function _postOp( + PostOpMode, + bytes calldata context, + uint256 actualGasCost, + uint256 actualUserOpFeePerGas + ) + internal + override + { + unchecked { + (address paymasterId, uint32 dynamicMarkup, bytes32 userOpHash) = + abi.decode(context, (address, uint32, bytes32)); + + uint256 balToDeduct = actualGasCost + postopCost * actualUserOpFeePerGas; + + uint256 costIncludingPremium = (balToDeduct * dynamicMarkup) / PRICE_DENOMINATOR; + + // deduct with premium + paymasterIdBalances[paymasterId] -= costIncludingPremium; + + uint256 actualPremium = costIncludingPremium - balToDeduct; + // "collect" premium + paymasterIdBalances[feeCollector] += actualPremium; + + emit GasBalanceDeducted(paymasterId, costIncludingPremium, userOpHash); + // Review if we should emit balToDeduct as well + emit PremiumCollected(paymasterId, actualPremium); + } + } + /** * verify our external signer signed this request. * the "paymasterAndData" is expected to be the paymaster and a signature over the entire request params @@ -191,18 +279,25 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom * paymasterAndData[84:88] : priceMarkup * paymasterAndData[88:] : signature */ - function _validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 requiredPreFund) - internal view override returns (bytes memory context, uint256 validationData) { - ( - address paymasterId, - uint48 validUntil, - uint48 validAfter, - uint32 priceMarkup, - bytes calldata signature - ) = parsePaymasterAndData(userOp.paymasterAndData); + function _validatePaymasterUserOp( + PackedUserOperation calldata userOp, + bytes32 userOpHash, + uint256 requiredPreFund + ) + internal + view + override + returns (bytes memory context, uint256 validationData) + { + (address paymasterId, uint48 validUntil, uint48 validAfter, uint32 priceMarkup, bytes calldata signature) = + parsePaymasterAndData(userOp.paymasterAndData); //ECDSA library supports both 64 and 65-byte long signatures. - // we only "require" it here so that the revert reason on invalid signature will be of "VerifyingPaymaster", and not "ECDSA" - require(signature.length == 64 || signature.length == 65, "VerifyingPaymaster: invalid signature length in paymasterAndData"); + // we only "require" it here so that the revert reason on invalid signature will be of "VerifyingPaymaster", and + // not "ECDSA" + require( + signature.length == 64 || signature.length == 65, + "VerifyingPaymaster: invalid signature length in paymasterAndData" + ); bool validSig = verifyingSigner.isValidSignatureNow( ECDSA_solady.toEthSignedMessageHash(getHash(userOp, paymasterId, validUntil, validAfter, priceMarkup)), @@ -220,99 +315,23 @@ contract BiconomySponsorshipPaymaster is BasePaymaster, ReentrancyGuard, Biconom // Send 1e6 for No markup // Send between 0 and 1e6 for discount - uint256 effectiveCost = ((requiredPreFund + (postopCost * maxFeePerGas)) * priceMarkup) / - PRICE_DENOMINATOR; - - require(effectiveCost <= paymasterIdBalances[paymasterId], "Sponsorship Paymaster: paymasterId does not have enough deposit"); + uint256 effectiveCost = ((requiredPreFund + (postopCost * maxFeePerGas)) * priceMarkup) / PRICE_DENOMINATOR; - context = abi.encode( - paymasterId, - priceMarkup, - userOpHash + require( + effectiveCost <= paymasterIdBalances[paymasterId], + "Sponsorship Paymaster: paymasterId does not have enough deposit" ); + context = abi.encode(paymasterId, priceMarkup, userOpHash); + //no need for other on-chain validation: entire UserOp should have been checked // by the external service prior to signing it. return (context, _packValidationData(false, validUntil, validAfter)); } - /// @notice Performs post-operation tasks, such as deducting the sponsored gas cost from the paymasterId's balance - /// @dev This function is called after a user operation has been executed or reverted. - /// @param context The context containing the token amount and user sender address. - /// @param actualGasCost The actual gas cost of the transaction. - /// @param actualUserOpFeePerGas - the gas price this UserOp pays. This value is based on the UserOp's maxFeePerGas - // and maxPriorityFee (and basefee) - // It is not the same as tx.gasprice, which is what the bundler pays. - function _postOp(PostOpMode, bytes calldata context, uint256 actualGasCost, uint256 actualUserOpFeePerGas) internal override { - unchecked { - ( - address paymasterId, - uint32 dynamicMarkup, - bytes32 userOpHash - ) = abi.decode(context, (address, uint32, bytes32)); - - uint256 balToDeduct = actualGasCost + - postopCost * - actualUserOpFeePerGas; - - uint256 costIncludingPremium = (balToDeduct * dynamicMarkup) / - PRICE_DENOMINATOR; - - // deduct with premium - paymasterIdBalances[paymasterId] -= costIncludingPremium; - - uint256 actualPremium = costIncludingPremium - balToDeduct; - // "collect" premium - paymasterIdBalances[feeCollector] += actualPremium; - - emit GasBalanceDeducted(paymasterId, costIncludingPremium, userOpHash); - // Review if we should emit balToDeduct as well - emit PremiumCollected(paymasterId, actualPremium); - } - } - - function parsePaymasterAndData( - bytes calldata paymasterAndData - ) - public - pure - returns ( - address paymasterId, - uint48 validUntil, - uint48 validAfter, - uint32 priceMarkup, - bytes calldata signature - ) - { - paymasterId = address(bytes20(paymasterAndData[VALID_PND_OFFSET:VALID_PND_OFFSET+20])); - validUntil = uint48(bytes6(paymasterAndData[VALID_PND_OFFSET+20:VALID_PND_OFFSET+26])); - validAfter = uint48(bytes6(paymasterAndData[VALID_PND_OFFSET+26:VALID_PND_OFFSET+32])); - priceMarkup = uint32(bytes4(paymasterAndData[VALID_PND_OFFSET+32:VALID_PND_OFFSET+36])); - signature = paymasterAndData[VALID_PND_OFFSET+36:]; - } - - receive() external payable { - emit Received(msg.sender, msg.value); - } - - function withdrawEth(address payable recipient, uint256 amount) external onlyOwner { - (bool success,) = recipient.call{value: amount}(""); - require(success, "withdraw failed"); - } - - /** - * @dev pull tokens out of paymaster in case they were sent to the paymaster at any point. - * @param token the token deposit to withdraw - * @param target address to send to - * @param amount amount to withdraw - */ - function withdrawERC20(IERC20 token, address target, uint256 amount) public payable onlyOwner nonReentrant { - _withdrawERC20(token, target, amount); - } - function _withdrawERC20(IERC20 token, address target, uint256 amount) private { if (target == address(0)) revert CanNotWithdrawToZeroAddress(); SafeTransferLib.safeTransfer(address(token), target, amount); emit TokensWithdrawn(address(token), target, amount, msg.sender); } -} \ No newline at end of file +} diff --git a/contracts/utils/SoladyOwnable.sol b/contracts/utils/SoladyOwnable.sol index 0cd57c4..8b680d3 100644 --- a/contracts/utils/SoladyOwnable.sol +++ b/contracts/utils/SoladyOwnable.sol @@ -1,10 +1,10 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import {Ownable} from "solady/src/auth/Ownable.sol"; +import { Ownable } from "solady/src/auth/Ownable.sol"; contract SoladyOwnable is Ownable { constructor(address _owner) Ownable() { _initializeOwner(_owner); } -} \ No newline at end of file +} diff --git a/test/hardhat/biconomy-sponsorship-paymaster-specs.ts b/test/hardhat/biconomy-sponsorship-paymaster-specs.ts index dbfabb1..c3a48d4 100644 --- a/test/hardhat/biconomy-sponsorship-paymaster-specs.ts +++ b/test/hardhat/biconomy-sponsorship-paymaster-specs.ts @@ -1,23 +1,35 @@ import { ethers } from "hardhat"; import { expect } from "chai"; -import { AbiCoder, AddressLike, BytesLike, Signer, parseEther, toBeHex } from "ethers"; -import { - EntryPoint, - EntryPoint__factory, - MockValidator, - MockValidator__factory, - SmartAccount, - SmartAccount__factory, - AccountFactory, - AccountFactory__factory, - BiconomySponsorshipPaymaster, - BiconomySponsorshipPaymaster__factory +import { + AbiCoder, + AddressLike, + BytesLike, + Signer, + parseEther, + toBeHex, +} from "ethers"; +import { + EntryPoint, + EntryPoint__factory, + MockValidator, + MockValidator__factory, + SmartAccount, + SmartAccount__factory, + AccountFactory, + AccountFactory__factory, + BiconomySponsorshipPaymaster, + BiconomySponsorshipPaymaster__factory, } from "../../typechain-types"; -import { DefaultsForUserOp, fillAndSign, fillSignAndPack, packUserOp, simulateValidation } from './utils/userOpHelpers' +import { + DefaultsForUserOp, + fillAndSign, + fillSignAndPack, + packUserOp, + simulateValidation, +} from "./utils/userOpHelpers"; import { parseValidationData } from "./utils/testUtils"; - export const AddressZero = ethers.ZeroAddress; const MOCK_VALID_UNTIL = "0x00000000deadbeef"; @@ -25,148 +37,174 @@ const MOCK_VALID_AFTER = "0x0000000000001234"; const MARKUP = 1100000; export const ENTRY_POINT_V7 = "0x0000000071727De22E5E9d8BAf0edAc6f37da032"; -const coder = AbiCoder.defaultAbiCoder() +const coder = AbiCoder.defaultAbiCoder(); export async function deployEntryPoint( - provider = ethers.provider - ): Promise { - const epf = await (await ethers.getContractFactory("EntryPoint")).deploy(); - // Retrieve the deployed contract bytecode - const deployedCode = await ethers.provider.getCode( - await epf.getAddress(), - ); - - // Use hardhat_setCode to set the contract code at the specified address - await ethers.provider.send("hardhat_setCode", [ENTRY_POINT_V7, deployedCode]); - - return epf.attach(ENTRY_POINT_V7) as EntryPoint; + provider = ethers.provider, +): Promise { + const epf = await (await ethers.getContractFactory("EntryPoint")).deploy(); + // Retrieve the deployed contract bytecode + const deployedCode = await ethers.provider.getCode(await epf.getAddress()); + + // Use hardhat_setCode to set the contract code at the specified address + await ethers.provider.send("hardhat_setCode", [ENTRY_POINT_V7, deployedCode]); + + return epf.attach(ENTRY_POINT_V7) as EntryPoint; } describe("EntryPoint with Biconomy Sponsorship Paymaster", function () { - let entryPoint: EntryPoint; - let depositorSigner: Signer; - let walletOwner: Signer; - let walletAddress: string, paymasterAddress: string; - let paymasterDepositorId: string; - let ethersSigner: Signer[]; - let offchainSigner: Signer, deployer: Signer, feeCollector: Signer; - let paymaster: BiconomySponsorshipPaymaster; - let smartWalletImp: SmartAccount; - let ecdsaModule: MockValidator; - let walletFactory: AccountFactory; - - beforeEach(async function () { - ethersSigner = await ethers.getSigners(); - entryPoint = await deployEntryPoint(); - - deployer = ethersSigner[0]; - offchainSigner = ethersSigner[1]; - depositorSigner = ethersSigner[2]; - feeCollector = ethersSigner[3]; - walletOwner = deployer; - - paymasterDepositorId = await depositorSigner.getAddress(); - - const offchainSignerAddress = await offchainSigner.getAddress(); - const walletOwnerAddress = await walletOwner.getAddress(); - const feeCollectorAddess = await feeCollector.getAddress(); - - ecdsaModule = await new MockValidator__factory( - deployer - ).deploy(); - - paymaster = - await new BiconomySponsorshipPaymaster__factory(deployer).deploy( - await deployer.getAddress(), - await entryPoint.getAddress(), - offchainSignerAddress, - feeCollectorAddess - ); - - smartWalletImp = await new SmartAccount__factory( - deployer - ).deploy(); - - walletFactory = await new AccountFactory__factory(deployer).deploy( - await smartWalletImp.getAddress(), - ); - - await walletFactory - .connect(deployer) - .addStake( 86400, { value: parseEther("2") }); - - const smartAccountDeploymentIndex = 0; - - // Module initialization data, encoded - const moduleInstallData = ethers.solidityPacked(["address"], [walletOwnerAddress]); - - await walletFactory.createAccount( - await ecdsaModule.getAddress(), - moduleInstallData, - smartAccountDeploymentIndex - ); - - const expected = await walletFactory.getCounterFactualAddress( - await ecdsaModule.getAddress(), - moduleInstallData, - smartAccountDeploymentIndex - ); - - walletAddress = expected; - - paymasterAddress = await paymaster.getAddress(); - - await paymaster - .connect(deployer) - .addStake(86400, { value: parseEther("2") }); - - await paymaster.depositFor(paymasterDepositorId, { value: parseEther("1") }); - - await entryPoint.depositTo(paymasterAddress, { value: parseEther("1") }); - - await deployer.sendTransaction({to: expected, value: parseEther("1"), data: '0x'}); - }); - - describe("Deployed Account : #validatePaymasterUserOp and #sendEmptySponsoredTx", () => { - it("succeed with valid signature", async () => { - const nonceKey = ethers.zeroPadBytes(await ecdsaModule.getAddress(), 24); - const userOp1 = await fillAndSign({ - sender: walletAddress, - paymaster: paymasterAddress, - paymasterData: ethers.concat([ - ethers.zeroPadValue(paymasterDepositorId, 20), - ethers.zeroPadValue(toBeHex(MOCK_VALID_UNTIL), 6), - ethers.zeroPadValue(toBeHex(MOCK_VALID_AFTER), 6), - ethers.zeroPadValue(toBeHex(MARKUP), 4), - '0x' + '00'.repeat(65) - ]), - paymasterPostOpGasLimit: 40_000, - }, walletOwner, entryPoint, 'getNonce', nonceKey) - const hash = await paymaster.getHash(packUserOp(userOp1), paymasterDepositorId, MOCK_VALID_UNTIL, MOCK_VALID_AFTER, MARKUP) - const sig = await offchainSigner.signMessage(ethers.getBytes(hash)) - const userOp = await fillSignAndPack({ - ...userOp1, - paymaster: paymasterAddress, - paymasterData: ethers.concat([ - ethers.zeroPadValue(paymasterDepositorId, 20), - ethers.zeroPadValue(toBeHex(MOCK_VALID_UNTIL), 6), - ethers.zeroPadValue(toBeHex(MOCK_VALID_AFTER), 6), - ethers.zeroPadValue(toBeHex(MARKUP), 4), - sig - ]), - paymasterPostOpGasLimit: 40_000, - }, walletOwner, entryPoint, 'getNonce', nonceKey) - // const parsedPnD = await paymaster.parsePaymasterAndData(userOp.paymasterAndData) - const res = await simulateValidation(userOp, await entryPoint.getAddress()) - const validationData = parseValidationData(res.returnInfo.paymasterValidationData) - expect(validationData).to.eql({ - aggregator: AddressZero, - validAfter: parseInt(MOCK_VALID_AFTER), - validUntil: parseInt(MOCK_VALID_UNTIL) - }) - - await entryPoint.handleOps([userOp], await deployer.getAddress()) - }); + let entryPoint: EntryPoint; + let depositorSigner: Signer; + let walletOwner: Signer; + let walletAddress: string, paymasterAddress: string; + let paymasterDepositorId: string; + let ethersSigner: Signer[]; + let offchainSigner: Signer, deployer: Signer, feeCollector: Signer; + let paymaster: BiconomySponsorshipPaymaster; + let smartWalletImp: SmartAccount; + let ecdsaModule: MockValidator; + let walletFactory: AccountFactory; + + beforeEach(async function () { + ethersSigner = await ethers.getSigners(); + entryPoint = await deployEntryPoint(); + + deployer = ethersSigner[0]; + offchainSigner = ethersSigner[1]; + depositorSigner = ethersSigner[2]; + feeCollector = ethersSigner[3]; + walletOwner = deployer; + + paymasterDepositorId = await depositorSigner.getAddress(); + + const offchainSignerAddress = await offchainSigner.getAddress(); + const walletOwnerAddress = await walletOwner.getAddress(); + const feeCollectorAddess = await feeCollector.getAddress(); + + ecdsaModule = await new MockValidator__factory(deployer).deploy(); + + paymaster = await new BiconomySponsorshipPaymaster__factory( + deployer, + ).deploy( + await deployer.getAddress(), + await entryPoint.getAddress(), + offchainSignerAddress, + feeCollectorAddess, + ); + + smartWalletImp = await new SmartAccount__factory(deployer).deploy(); + + walletFactory = await new AccountFactory__factory(deployer).deploy( + await smartWalletImp.getAddress(), + ); + + await walletFactory + .connect(deployer) + .addStake(86400, { value: parseEther("2") }); + + const smartAccountDeploymentIndex = 0; + + // Module initialization data, encoded + const moduleInstallData = ethers.solidityPacked( + ["address"], + [walletOwnerAddress], + ); + + await walletFactory.createAccount( + await ecdsaModule.getAddress(), + moduleInstallData, + smartAccountDeploymentIndex, + ); + + const expected = await walletFactory.getCounterFactualAddress( + await ecdsaModule.getAddress(), + moduleInstallData, + smartAccountDeploymentIndex, + ); + + walletAddress = expected; + + paymasterAddress = await paymaster.getAddress(); + + await paymaster + .connect(deployer) + .addStake(86400, { value: parseEther("2") }); + + await paymaster.depositFor(paymasterDepositorId, { + value: parseEther("1"), }); -}) + await entryPoint.depositTo(paymasterAddress, { value: parseEther("1") }); + + await deployer.sendTransaction({ + to: expected, + value: parseEther("1"), + data: "0x", + }); + }); + + describe("Deployed Account : #validatePaymasterUserOp and #sendEmptySponsoredTx", () => { + it("succeed with valid signature", async () => { + const nonceKey = ethers.zeroPadBytes(await ecdsaModule.getAddress(), 24); + const userOp1 = await fillAndSign( + { + sender: walletAddress, + paymaster: paymasterAddress, + paymasterData: ethers.concat([ + ethers.zeroPadValue(paymasterDepositorId, 20), + ethers.zeroPadValue(toBeHex(MOCK_VALID_UNTIL), 6), + ethers.zeroPadValue(toBeHex(MOCK_VALID_AFTER), 6), + ethers.zeroPadValue(toBeHex(MARKUP), 4), + "0x" + "00".repeat(65), + ]), + paymasterPostOpGasLimit: 40_000, + }, + walletOwner, + entryPoint, + "getNonce", + nonceKey, + ); + const hash = await paymaster.getHash( + packUserOp(userOp1), + paymasterDepositorId, + MOCK_VALID_UNTIL, + MOCK_VALID_AFTER, + MARKUP, + ); + const sig = await offchainSigner.signMessage(ethers.getBytes(hash)); + const userOp = await fillSignAndPack( + { + ...userOp1, + paymaster: paymasterAddress, + paymasterData: ethers.concat([ + ethers.zeroPadValue(paymasterDepositorId, 20), + ethers.zeroPadValue(toBeHex(MOCK_VALID_UNTIL), 6), + ethers.zeroPadValue(toBeHex(MOCK_VALID_AFTER), 6), + ethers.zeroPadValue(toBeHex(MARKUP), 4), + sig, + ]), + paymasterPostOpGasLimit: 40_000, + }, + walletOwner, + entryPoint, + "getNonce", + nonceKey, + ); + // const parsedPnD = await paymaster.parsePaymasterAndData(userOp.paymasterAndData) + const res = await simulateValidation( + userOp, + await entryPoint.getAddress(), + ); + const validationData = parseValidationData( + res.returnInfo.paymasterValidationData, + ); + expect(validationData).to.eql({ + aggregator: AddressZero, + validAfter: parseInt(MOCK_VALID_AFTER), + validUntil: parseInt(MOCK_VALID_UNTIL), + }); + + await entryPoint.handleOps([userOp], await deployer.getAddress()); + }); + }); +}); diff --git a/test/hardhat/utils/deployment.ts b/test/hardhat/utils/deployment.ts index 282831d..18ebef0 100644 --- a/test/hardhat/utils/deployment.ts +++ b/test/hardhat/utils/deployment.ts @@ -1,6 +1,12 @@ import { BytesLike, HDNodeWallet, Signer } from "ethers"; import { deployments, ethers } from "hardhat"; -import { AccountFactory, BiconomySponsorshipPaymaster, EntryPoint, MockValidator, SmartAccount } from "../../../typechain-types"; +import { + AccountFactory, + BiconomySponsorshipPaymaster, + EntryPoint, + MockValidator, + SmartAccount, +} from "../../../typechain-types"; import { TASK_DEPLOY } from "hardhat-deploy"; import { DeployResult } from "hardhat-deploy/dist/types"; @@ -14,39 +20,39 @@ export const ENTRY_POINT_V7 = "0x0000000071727De22E5E9d8BAf0edAc6f37da032"; * @returns A promise that resolves to the deployed contract instance. */ export async function deployContract( - contractName: string, - deployer: Signer, - ): Promise { - const ContractFactory = await ethers.getContractFactory( - contractName, - deployer, - ); - const contract = await ContractFactory.deploy(); - await contract.waitForDeployment(); - return contract as T; + contractName: string, + deployer: Signer, +): Promise { + const ContractFactory = await ethers.getContractFactory( + contractName, + deployer, + ); + const contract = await ContractFactory.deploy(); + await contract.waitForDeployment(); + return contract as T; } /** * Deploys the EntryPoint contract with a deterministic deployment. * @returns A promise that resolves to the deployed EntryPoint contract instance. */ -export async function getDeployedEntrypoint() : Promise { - const [deployer] = await ethers.getSigners(); - - // Deploy the contract normally to get its bytecode - const EntryPoint = await ethers.getContractFactory("EntryPoint"); - const entryPoint = await EntryPoint.deploy(); - await entryPoint.waitForDeployment(); - - // Retrieve the deployed contract bytecode - const deployedCode = await ethers.provider.getCode( - await entryPoint.getAddress(), - ); - - // Use hardhat_setCode to set the contract code at the specified address - await ethers.provider.send("hardhat_setCode", [ENTRY_POINT_V7, deployedCode]); - - return EntryPoint.attach(ENTRY_POINT_V7) as EntryPoint; +export async function getDeployedEntrypoint(): Promise { + const [deployer] = await ethers.getSigners(); + + // Deploy the contract normally to get its bytecode + const EntryPoint = await ethers.getContractFactory("EntryPoint"); + const entryPoint = await EntryPoint.deploy(); + await entryPoint.waitForDeployment(); + + // Retrieve the deployed contract bytecode + const deployedCode = await ethers.provider.getCode( + await entryPoint.getAddress(), + ); + + // Use hardhat_setCode to set the contract code at the specified address + await ethers.provider.send("hardhat_setCode", [ENTRY_POINT_V7, deployedCode]); + + return EntryPoint.attach(ENTRY_POINT_V7) as EntryPoint; } /** @@ -54,18 +60,18 @@ export async function getDeployedEntrypoint() : Promise { * @returns A promise that resolves to the deployed SA implementation contract instance. */ export async function getDeployedMSAImplementation(): Promise { - const accounts: Signer[] = await ethers.getSigners(); - const addresses = await Promise.all( - accounts.map((account) => account.getAddress()), - ); - - const SmartAccount = await ethers.getContractFactory("SmartAccount"); - const deterministicMSAImpl = await deployments.deploy("SmartAccount", { - from: addresses[0], - deterministicDeployment: true, - }); - - return SmartAccount.attach(deterministicMSAImpl.address) as SmartAccount; + const accounts: Signer[] = await ethers.getSigners(); + const addresses = await Promise.all( + accounts.map((account) => account.getAddress()), + ); + + const SmartAccount = await ethers.getContractFactory("SmartAccount"); + const deterministicMSAImpl = await deployments.deploy("SmartAccount", { + from: addresses[0], + deterministicDeployment: true, + }); + + return SmartAccount.attach(deterministicMSAImpl.address) as SmartAccount; } /** @@ -73,27 +79,27 @@ export async function getDeployedMSAImplementation(): Promise { * @returns A promise that resolves to the deployed EntryPoint contract instance. */ export async function getDeployedAccountFactory( - implementationAddress: string, - // Note: this could be converted to dto so that additional args can easily be passed - ): Promise { - const accounts: Signer[] = await ethers.getSigners(); - const addresses = await Promise.all( - accounts.map((account) => account.getAddress()), - ); - - const AccountFactory = await ethers.getContractFactory("AccountFactory"); - const deterministicAccountFactory = await deployments.deploy( - "AccountFactory", - { - from: addresses[0], - deterministicDeployment: true, - args: [implementationAddress], - }, - ); - - return AccountFactory.attach( - deterministicAccountFactory.address, - ) as AccountFactory; + implementationAddress: string, + // Note: this could be converted to dto so that additional args can easily be passed +): Promise { + const accounts: Signer[] = await ethers.getSigners(); + const addresses = await Promise.all( + accounts.map((account) => account.getAddress()), + ); + + const AccountFactory = await ethers.getContractFactory("AccountFactory"); + const deterministicAccountFactory = await deployments.deploy( + "AccountFactory", + { + from: addresses[0], + deterministicDeployment: true, + args: [implementationAddress], + }, + ); + + return AccountFactory.attach( + deterministicAccountFactory.address, + ) as AccountFactory; } /** @@ -101,41 +107,50 @@ export async function getDeployedAccountFactory( * @returns A promise that resolves to the deployed MockValidator contract instance. */ export async function getDeployedMockValidator(): Promise { - const accounts: Signer[] = await ethers.getSigners(); - const addresses = await Promise.all( - accounts.map((account) => account.getAddress()), - ); - - const MockValidator = await ethers.getContractFactory("MockValidator"); - const deterministicMockValidator = await deployments.deploy("MockValidator", { - from: addresses[0], - deterministicDeployment: true, - }); - - return MockValidator.attach( - deterministicMockValidator.address, - ) as MockValidator; + const accounts: Signer[] = await ethers.getSigners(); + const addresses = await Promise.all( + accounts.map((account) => account.getAddress()), + ); + + const MockValidator = await ethers.getContractFactory("MockValidator"); + const deterministicMockValidator = await deployments.deploy("MockValidator", { + from: addresses[0], + deterministicDeployment: true, + }); + + return MockValidator.attach( + deterministicMockValidator.address, + ) as MockValidator; } /** * Deploys the MockValidator contract with a deterministic deployment. * @returns A promise that resolves to the deployed MockValidator contract instance. */ -export async function getDeployedSponsorshipPaymaster(owner: string, entryPoint: string, verifyingSigner: string, feeCollector: string): Promise { - const accounts: Signer[] = await ethers.getSigners(); - const addresses = await Promise.all( - accounts.map((account) => account.getAddress()), - ); - - const BiconomySponsorshipPaymaster = await ethers.getContractFactory("BiconomySponsorshipPaymaster"); - const deterministicSponsorshipPaymaster = await deployments.deploy("BiconomySponsorshipPaymaster", { +export async function getDeployedSponsorshipPaymaster( + owner: string, + entryPoint: string, + verifyingSigner: string, + feeCollector: string, +): Promise { + const accounts: Signer[] = await ethers.getSigners(); + const addresses = await Promise.all( + accounts.map((account) => account.getAddress()), + ); + + const BiconomySponsorshipPaymaster = await ethers.getContractFactory( + "BiconomySponsorshipPaymaster", + ); + const deterministicSponsorshipPaymaster = await deployments.deploy( + "BiconomySponsorshipPaymaster", + { from: addresses[0], deterministicDeployment: true, args: [owner, entryPoint, verifyingSigner, feeCollector], - }); - - return BiconomySponsorshipPaymaster.attach( + }, + ); + + return BiconomySponsorshipPaymaster.attach( deterministicSponsorshipPaymaster.address, - ) as BiconomySponsorshipPaymaster; + ) as BiconomySponsorshipPaymaster; } - diff --git a/test/hardhat/utils/testUtils.ts b/test/hardhat/utils/testUtils.ts index 06c4218..abe1776 100644 --- a/test/hardhat/utils/testUtils.ts +++ b/test/hardhat/utils/testUtils.ts @@ -1,6 +1,15 @@ -import { AbiCoder, AddressLike, BigNumberish, Contract, Interface, dataSlice, parseEther, toBeHex } from 'ethers'; -import { ethers } from 'hardhat' -import { EntryPoint__factory, IERC20 } from '../../../typechain-types'; +import { + AbiCoder, + AddressLike, + BigNumberish, + Contract, + Interface, + dataSlice, + parseEther, + toBeHex, +} from "ethers"; +import { ethers } from "hardhat"; +import { EntryPoint__factory, IERC20 } from "../../../typechain-types"; // define mode and exec type enums export const CALLTYPE_SINGLE = "0x00"; // 1 byte @@ -13,171 +22,189 @@ export const UNUSED = "0x00000000"; // 4 bytes export const MODE_PAYLOAD = "0x00000000000000000000000000000000000000000000"; // 22 bytes export const AddressZero = ethers.ZeroAddress; -export const HashZero = ethers.ZeroHash -export const ONE_ETH = parseEther('1') -export const TWO_ETH = parseEther('2') -export const FIVE_ETH = parseEther('5') -export const maxUint48 = (2 ** 48) - 1 +export const HashZero = ethers.ZeroHash; +export const ONE_ETH = parseEther("1"); +export const TWO_ETH = parseEther("2"); +export const FIVE_ETH = parseEther("5"); +export const maxUint48 = 2 ** 48 - 1; -export const tostr = (x: any): string => x != null ? x.toString() : 'null' +export const tostr = (x: any): string => (x != null ? x.toString() : "null"); -const coder = AbiCoder.defaultAbiCoder() +const coder = AbiCoder.defaultAbiCoder(); export interface ValidationData { - aggregator: string - validAfter: number - validUntil: number + aggregator: string; + validAfter: number; + validUntil: number; } export const panicCodes: { [key: number]: string } = { - // from https://docs.soliditylang.org/en/v0.8.0/control-structures.html - 0x01: 'assert(false)', - 0x11: 'arithmetic overflow/underflow', - 0x12: 'divide by zero', - 0x21: 'invalid enum value', - 0x22: 'storage byte array that is incorrectly encoded', - 0x31: '.pop() on an empty array.', - 0x32: 'array sout-of-bounds or negative index', - 0x41: 'memory overflow', - 0x51: 'zero-initialized variable of internal function type' -} + // from https://docs.soliditylang.org/en/v0.8.0/control-structures.html + 0x01: "assert(false)", + 0x11: "arithmetic overflow/underflow", + 0x12: "divide by zero", + 0x21: "invalid enum value", + 0x22: "storage byte array that is incorrectly encoded", + 0x31: ".pop() on an empty array.", + 0x32: "array sout-of-bounds or negative index", + 0x41: "memory overflow", + 0x51: "zero-initialized variable of internal function type", +}; export const Erc20 = [ - "function transfer(address _receiver, uint256 _value) public returns (bool success)", - "function transferFrom(address, address, uint256) public returns (bool)", - "function approve(address _spender, uint256 _value) public returns (bool success)", - "function allowance(address _owner, address _spender) public view returns (uint256 remaining)", - "function balanceOf(address _owner) public view returns (uint256 balance)", - "event Approval(address indexed _owner, address indexed _spender, uint256 _value)", - ]; - + "function transfer(address _receiver, uint256 _value) public returns (bool success)", + "function transferFrom(address, address, uint256) public returns (bool)", + "function approve(address _spender, uint256 _value) public returns (bool success)", + "function allowance(address _owner, address _spender) public view returns (uint256 remaining)", + "function balanceOf(address _owner) public view returns (uint256 balance)", + "event Approval(address indexed _owner, address indexed _spender, uint256 _value)", +]; + export const Erc20Interface = new ethers.Interface(Erc20); export const encodeTransfer = ( - target: string, - amount: string | number - ): string => { - return Erc20Interface.encodeFunctionData("transfer", [target, amount]); + target: string, + amount: string | number, +): string => { + return Erc20Interface.encodeFunctionData("transfer", [target, amount]); }; export const encodeTransferFrom = ( - from: string, - target: string, - amount: string | number - ): string => { - return Erc20Interface.encodeFunctionData("transferFrom", [ - from, - target, - amount, - ]); + from: string, + target: string, + amount: string | number, +): string => { + return Erc20Interface.encodeFunctionData("transferFrom", [ + from, + target, + amount, + ]); }; // rethrow "cleaned up" exception. // - stack trace goes back to method (or catch) line, not inner provider // - attempt to parse revert data (needed for geth) // use with ".catch(rethrow())", so that current source file/line is meaningful. -export function rethrow (): (e: Error) => void { - const callerStack = new Error().stack!.replace(/Error.*\n.*at.*\n/, '').replace(/.*at.* \(internal[\s\S]*/, '') +export function rethrow(): (e: Error) => void { + const callerStack = new Error() + .stack!.replace(/Error.*\n.*at.*\n/, "") + .replace(/.*at.* \(internal[\s\S]*/, ""); if (arguments[0] != null) { - throw new Error('must use .catch(rethrow()), and NOT .catch(rethrow)') + throw new Error("must use .catch(rethrow()), and NOT .catch(rethrow)"); } return function (e: Error) { - const solstack = e.stack!.match(/((?:.* at .*\.sol.*\n)+)/) - const stack = (solstack != null ? solstack[1] : '') + callerStack + const solstack = e.stack!.match(/((?:.* at .*\.sol.*\n)+)/); + const stack = (solstack != null ? solstack[1] : "") + callerStack; // const regex = new RegExp('error=.*"data":"(.*?)"').compile() - const found = /error=.*?"data":"(.*?)"/.exec(e.message) - let message: string + const found = /error=.*?"data":"(.*?)"/.exec(e.message); + let message: string; if (found != null) { - const data = found[1] - message = decodeRevertReason(data) ?? e.message + ' - ' + data.slice(0, 100) + const data = found[1]; + message = + decodeRevertReason(data) ?? e.message + " - " + data.slice(0, 100); } else { - message = e.message + message = e.message; } - const err = new Error(message) - err.stack = 'Error: ' + message + '\n' + stack - throw err - } + const err = new Error(message); + err.stack = "Error: " + message + "\n" + stack; + throw err; + }; } const decodeRevertReasonContracts = new Interface([ ...EntryPoint__factory.createInterface().fragments, - 'error ECDSAInvalidSignature()' -]) // .filter(f => f.type === 'error')) - -export function decodeRevertReason (data: string | Error, nullIfNoMatch = true): string | null { - if (typeof data !== 'string') { - const err = data as any - data = (err.data ?? err.error?.data) as string - if (typeof data !== 'string') throw err + "error ECDSAInvalidSignature()", +]); // .filter(f => f.type === 'error')) + +export function decodeRevertReason( + data: string | Error, + nullIfNoMatch = true, +): string | null { + if (typeof data !== "string") { + const err = data as any; + data = (err.data ?? err.error?.data) as string; + if (typeof data !== "string") throw err; } - const methodSig = data.slice(0, 10) - const dataParams = '0x' + data.slice(10) + const methodSig = data.slice(0, 10); + const dataParams = "0x" + data.slice(10); // can't add Error(string) to xface... - if (methodSig === '0x08c379a0') { - const [err] = coder.decode(['string'], dataParams) + if (methodSig === "0x08c379a0") { + const [err] = coder.decode(["string"], dataParams); // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - return `Error(${err})` - } else if (methodSig === '0x4e487b71') { - const [code] = coder.decode(['uint256'], dataParams) - return `Panic(${panicCodes[code] ?? code} + ')` + return `Error(${err})`; + } else if (methodSig === "0x4e487b71") { + const [code] = coder.decode(["uint256"], dataParams); + return `Panic(${panicCodes[code] ?? code} + ')`; } try { - const err = decodeRevertReasonContracts.parseError(data) + const err = decodeRevertReasonContracts.parseError(data); // treat any error "bytes" argument as possible error to decode (e.g. FailedOpWithRevert, PostOpReverted) const args = err!.args.map((arg: any, index) => { switch (err?.fragment.inputs[index].type) { - case 'bytes' : return decodeRevertReason(arg) - case 'string': return `"${(arg as string)}"` - default: return arg + case "bytes": + return decodeRevertReason(arg); + case "string": + return `"${arg as string}"`; + default: + return arg; } - }) - return `${err!.name}(${args.join(',')})` + }); + return `${err!.name}(${args.join(",")})`; } catch (e) { // throw new Error('unsupported errorSig ' + data) if (!nullIfNoMatch) { - return data + return data; } - return null + return null; } } -export function tonumber (x: any): number { +export function tonumber(x: any): number { try { - return parseFloat(x.toString()) + return parseFloat(x.toString()); } catch (e: any) { - console.log('=== failed to parseFloat:', x, (e).message) - return NaN + console.log("=== failed to parseFloat:", x, e.message); + return NaN; } } // just throw 1eth from account[0] to the given address (or contract instance) -export async function fund (contractOrAddress: string | Contract, amountEth = '1'): Promise { - let address: string - if (typeof contractOrAddress === 'string') { - address = contractOrAddress - } else { - address = await contractOrAddress.getAddress() - } - const [firstSigner] = await ethers.getSigners(); - await firstSigner.sendTransaction({ to: address, value: parseEther(amountEth) }) +export async function fund( + contractOrAddress: string | Contract, + amountEth = "1", +): Promise { + let address: string; + if (typeof contractOrAddress === "string") { + address = contractOrAddress; + } else { + address = await contractOrAddress.getAddress(); + } + const [firstSigner] = await ethers.getSigners(); + await firstSigner.sendTransaction({ + to: address, + value: parseEther(amountEth), + }); } -export async function getBalance (address: string): Promise { - const balance = await ethers.provider.getBalance(address) - return parseInt(balance.toString()) +export async function getBalance(address: string): Promise { + const balance = await ethers.provider.getBalance(address); + return parseInt(balance.toString()); } -export async function getTokenBalance (token: IERC20, address: string): Promise { - const balance = await token.balanceOf(address) - return parseInt(balance.toString()) +export async function getTokenBalance( + token: IERC20, + address: string, +): Promise { + const balance = await token.balanceOf(address); + return parseInt(balance.toString()); } -export async function isDeployed (addr: string): Promise { - const code = await ethers.provider.getCode(addr) - return code.length > 2 +export async function isDeployed(addr: string): Promise { + const code = await ethers.provider.getCode(addr); + return code.length > 2; } // Getting initcode for AccountFactory which accepts one validator (with ECDSA owner required for installation) @@ -202,28 +229,29 @@ export async function getInitCode( return factoryAddress + factoryDeploymentData; } -export function callDataCost (data: string): number { - return ethers.getBytes(data) - .map(x => x === 0 ? 4 : 16) - .reduce((sum, x) => sum + x) +export function callDataCost(data: string): number { + return ethers + .getBytes(data) + .map((x) => (x === 0 ? 4 : 16)) + .reduce((sum, x) => sum + x); } -export function parseValidationData (validationData: BigNumberish): ValidationData { - const data = ethers.zeroPadValue(toBeHex(validationData), 32) +export function parseValidationData( + validationData: BigNumberish, +): ValidationData { + const data = ethers.zeroPadValue(toBeHex(validationData), 32); // string offsets start from left (msb) - const aggregator = dataSlice(data, 32 - 20) - let validUntil = parseInt(dataSlice(data, 32 - 26, 32 - 20)) + const aggregator = dataSlice(data, 32 - 20); + let validUntil = parseInt(dataSlice(data, 32 - 26, 32 - 20)); if (validUntil === 0) { - validUntil = maxUint48 + validUntil = maxUint48; } - const validAfter = parseInt(dataSlice(data, 0, 6)) + const validAfter = parseInt(dataSlice(data, 0, 6)); return { aggregator, validAfter, - validUntil - } + validUntil, + }; } - - diff --git a/test/hardhat/utils/types.ts b/test/hardhat/utils/types.ts index 791fc10..7dd52fa 100644 --- a/test/hardhat/utils/types.ts +++ b/test/hardhat/utils/types.ts @@ -1,34 +1,30 @@ -import { - AddressLike, - BigNumberish, - BytesLike, - } from "ethers"; +import { AddressLike, BigNumberish, BytesLike } from "ethers"; export interface UserOperation { - sender: AddressLike; // Or string - nonce?: BigNumberish; - initCode?: BytesLike; - callData?: BytesLike; - callGasLimit?: BigNumberish; - verificationGasLimit?: BigNumberish; - preVerificationGas?: BigNumberish; - maxFeePerGas?: BigNumberish; - maxPriorityFeePerGas?: BigNumberish; - paymaster?: AddressLike; // Or string - paymasterVerificationGasLimit?: BigNumberish; - paymasterPostOpGasLimit?: BigNumberish; - paymasterData?: BytesLike; - signature?: BytesLike; - } + sender: AddressLike; // Or string + nonce?: BigNumberish; + initCode?: BytesLike; + callData?: BytesLike; + callGasLimit?: BigNumberish; + verificationGasLimit?: BigNumberish; + preVerificationGas?: BigNumberish; + maxFeePerGas?: BigNumberish; + maxPriorityFeePerGas?: BigNumberish; + paymaster?: AddressLike; // Or string + paymasterVerificationGasLimit?: BigNumberish; + paymasterPostOpGasLimit?: BigNumberish; + paymasterData?: BytesLike; + signature?: BytesLike; +} - export interface PackedUserOperation { - sender: AddressLike; // Or string - nonce: BigNumberish; - initCode: BytesLike; - callData: BytesLike; - accountGasLimits: BytesLike; - preVerificationGas: BigNumberish; - gasFees: BytesLike; - paymasterAndData: BytesLike; - signature: BytesLike; - } \ No newline at end of file +export interface PackedUserOperation { + sender: AddressLike; // Or string + nonce: BigNumberish; + initCode: BytesLike; + callData: BytesLike; + accountGasLimits: BytesLike; + preVerificationGas: BigNumberish; + gasFees: BytesLike; + paymasterAndData: BytesLike; + signature: BytesLike; +} diff --git a/test/hardhat/utils/userOpHelpers.ts b/test/hardhat/utils/userOpHelpers.ts index 8dc582c..50fccd5 100644 --- a/test/hardhat/utils/userOpHelpers.ts +++ b/test/hardhat/utils/userOpHelpers.ts @@ -1,157 +1,230 @@ import { ethers } from "hardhat"; -import { EntryPoint, EntryPointSimulations__factory, IEntryPointSimulations } from "../../../typechain-types"; +import { + EntryPoint, + EntryPointSimulations__factory, + IEntryPointSimulations, +} from "../../../typechain-types"; import { PackedUserOperation, UserOperation } from "./types"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; -import { TransactionRequest } from '@ethersproject/abstract-provider' -import { AbiCoder, BigNumberish, BytesLike, Contract, Signer, dataSlice, keccak256, toBeHex } from "ethers"; +import { TransactionRequest } from "@ethersproject/abstract-provider"; +import { + AbiCoder, + BigNumberish, + BytesLike, + Contract, + Signer, + dataSlice, + keccak256, + toBeHex, +} from "ethers"; import { toGwei } from "./general"; import { callDataCost, decodeRevertReason, rethrow } from "./testUtils"; -import EntryPointSimulationsJson from '../../../artifacts/account-abstraction/contracts/core/EntryPointSimulations.sol/EntryPointSimulations.json' +import EntryPointSimulationsJson from "../../../artifacts/account-abstraction/contracts/core/EntryPointSimulations.sol/EntryPointSimulations.json"; const AddressZero = ethers.ZeroAddress; -const coder = AbiCoder.defaultAbiCoder() +const coder = AbiCoder.defaultAbiCoder(); -export function packUserOp (userOp: UserOperation): PackedUserOperation { +export function packUserOp(userOp: UserOperation): PackedUserOperation { + const { + sender, + nonce, + initCode = "0x", + callData = "0x", + callGasLimit = 1_500_000, + verificationGasLimit = 1_500_000, + preVerificationGas = 2_000_000, + maxFeePerGas = toGwei("20"), + maxPriorityFeePerGas = toGwei("10"), + paymaster = ethers.ZeroAddress, + paymasterData = "0x", + paymasterVerificationGasLimit = 3_00_000, + paymasterPostOpGasLimit = 0, + signature = "0x", + } = userOp; - const { - sender, - nonce, - initCode = "0x", - callData = "0x", - callGasLimit = 1_500_000, - verificationGasLimit = 1_500_000, - preVerificationGas = 2_000_000, - maxFeePerGas = toGwei("20"), - maxPriorityFeePerGas = toGwei("10"), - paymaster = ethers.ZeroAddress, - paymasterData = "0x", - paymasterVerificationGasLimit = 3_00_000, - paymasterPostOpGasLimit = 0, - signature = "0x", - } = userOp; - - const accountGasLimits = packAccountGasLimits(verificationGasLimit, callGasLimit) - const gasFees = packAccountGasLimits(maxPriorityFeePerGas, maxFeePerGas) - let paymasterAndData = '0x' - if (paymaster.toString().length >= 20 && paymaster !== ethers.ZeroAddress) { - paymasterAndData = packPaymasterData( - userOp.paymaster as string, - paymasterVerificationGasLimit, - paymasterPostOpGasLimit, - paymasterData as string, - ) as string; - } - return { - sender: userOp.sender, - nonce: userOp.nonce || 0, - callData: userOp.callData || '0x', - accountGasLimits, - initCode: userOp.initCode || '0x', - preVerificationGas: userOp.preVerificationGas || 50000, - gasFees, - paymasterAndData, - signature: userOp.signature || '0x' - } + const accountGasLimits = packAccountGasLimits( + verificationGasLimit, + callGasLimit, + ); + const gasFees = packAccountGasLimits(maxPriorityFeePerGas, maxFeePerGas); + let paymasterAndData = "0x"; + if (paymaster.toString().length >= 20 && paymaster !== ethers.ZeroAddress) { + paymasterAndData = packPaymasterData( + userOp.paymaster as string, + paymasterVerificationGasLimit, + paymasterPostOpGasLimit, + paymasterData as string, + ) as string; + } + return { + sender: userOp.sender, + nonce: userOp.nonce || 0, + callData: userOp.callData || "0x", + accountGasLimits, + initCode: userOp.initCode || "0x", + preVerificationGas: userOp.preVerificationGas || 50000, + gasFees, + paymasterAndData, + signature: userOp.signature || "0x", + }; } -export function encodeUserOp (userOp: UserOperation, forSignature = true): string { - const packedUserOp = packUserOp(userOp) - if (forSignature) { - return coder.encode( - ['address', 'uint256', 'bytes32', 'bytes32', - 'bytes32', 'uint256', 'bytes32', - 'bytes32'], - [packedUserOp.sender, packedUserOp.nonce, keccak256(packedUserOp.initCode), keccak256(packedUserOp.callData), - packedUserOp.accountGasLimits, packedUserOp.preVerificationGas, packedUserOp.gasFees, - keccak256(packedUserOp.paymasterAndData)]) - } else { - // for the purpose of calculating gas cost encode also signature (and no keccak of bytes) - return coder.encode( - ['address', 'uint256', 'bytes', 'bytes', - 'bytes32', 'uint256', 'bytes32', - 'bytes', 'bytes'], - [packedUserOp.sender, packedUserOp.nonce, packedUserOp.initCode, packedUserOp.callData, - packedUserOp.accountGasLimits, packedUserOp.preVerificationGas, packedUserOp.gasFees, - packedUserOp.paymasterAndData, packedUserOp.signature]) - } +export function encodeUserOp( + userOp: UserOperation, + forSignature = true, +): string { + const packedUserOp = packUserOp(userOp); + if (forSignature) { + return coder.encode( + [ + "address", + "uint256", + "bytes32", + "bytes32", + "bytes32", + "uint256", + "bytes32", + "bytes32", + ], + [ + packedUserOp.sender, + packedUserOp.nonce, + keccak256(packedUserOp.initCode), + keccak256(packedUserOp.callData), + packedUserOp.accountGasLimits, + packedUserOp.preVerificationGas, + packedUserOp.gasFees, + keccak256(packedUserOp.paymasterAndData), + ], + ); + } else { + // for the purpose of calculating gas cost encode also signature (and no keccak of bytes) + return coder.encode( + [ + "address", + "uint256", + "bytes", + "bytes", + "bytes32", + "uint256", + "bytes32", + "bytes", + "bytes", + ], + [ + packedUserOp.sender, + packedUserOp.nonce, + packedUserOp.initCode, + packedUserOp.callData, + packedUserOp.accountGasLimits, + packedUserOp.preVerificationGas, + packedUserOp.gasFees, + packedUserOp.paymasterAndData, + packedUserOp.signature, + ], + ); + } } // Can be moved to testUtils export function packPaymasterData( - paymaster: string, - paymasterVerificationGasLimit: BigNumberish, - postOpGasLimit: BigNumberish, - paymasterData: BytesLike, - ): BytesLike { - return ethers.concat([ - paymaster, - ethers.zeroPadValue(toBeHex(Number(paymasterVerificationGasLimit)), 16), - ethers.zeroPadValue(toBeHex(Number(postOpGasLimit)), 16), - paymasterData, - ]); + paymaster: string, + paymasterVerificationGasLimit: BigNumberish, + postOpGasLimit: BigNumberish, + paymasterData: BytesLike, +): BytesLike { + return ethers.concat([ + paymaster, + ethers.zeroPadValue(toBeHex(Number(paymasterVerificationGasLimit)), 16), + ethers.zeroPadValue(toBeHex(Number(postOpGasLimit)), 16), + paymasterData, + ]); } // Can be moved to testUtils -export function packAccountGasLimits (verificationGasLimit: BigNumberish, callGasLimit: BigNumberish): string { - return ethers.concat([ - ethers.zeroPadValue(toBeHex(Number(verificationGasLimit)), 16), ethers.zeroPadValue(toBeHex(Number(callGasLimit)), 16) - ]) +export function packAccountGasLimits( + verificationGasLimit: BigNumberish, + callGasLimit: BigNumberish, +): string { + return ethers.concat([ + ethers.zeroPadValue(toBeHex(Number(verificationGasLimit)), 16), + ethers.zeroPadValue(toBeHex(Number(callGasLimit)), 16), + ]); } // Can be moved to testUtils -export function unpackAccountGasLimits (accountGasLimits: string): { verificationGasLimit: number, callGasLimit: number } { - return { verificationGasLimit: parseInt(accountGasLimits.slice(2, 34), 16), callGasLimit: parseInt(accountGasLimits.slice(34), 16) } +export function unpackAccountGasLimits(accountGasLimits: string): { + verificationGasLimit: number; + callGasLimit: number; +} { + return { + verificationGasLimit: parseInt(accountGasLimits.slice(2, 34), 16), + callGasLimit: parseInt(accountGasLimits.slice(34), 16), + }; } -export function getUserOpHash (op: UserOperation, entryPoint: string, chainId: number): string { - const userOpHash = keccak256(encodeUserOp(op, true)) - const enc = coder.encode( - ['bytes32', 'address', 'uint256'], - [userOpHash, entryPoint, chainId]) - return keccak256(enc) +export function getUserOpHash( + op: UserOperation, + entryPoint: string, + chainId: number, +): string { + const userOpHash = keccak256(encodeUserOp(op, true)); + const enc = coder.encode( + ["bytes32", "address", "uint256"], + [userOpHash, entryPoint, chainId], + ); + return keccak256(enc); } export const DefaultsForUserOp: UserOperation = { - sender: AddressZero, - nonce: 0, - initCode: '0x', - callData: '0x', - callGasLimit: 0, - verificationGasLimit: 150000, // default verification gas. will add create2 cost (3200+200*length) if initCode exists - preVerificationGas: 21000, // should also cover calldata cost. - maxFeePerGas: 0, - maxPriorityFeePerGas: 1e9, - paymaster: AddressZero, - paymasterData: '0x', - paymasterVerificationGasLimit: 3e5, - paymasterPostOpGasLimit: 0, - signature: '0x' -} + sender: AddressZero, + nonce: 0, + initCode: "0x", + callData: "0x", + callGasLimit: 0, + verificationGasLimit: 150000, // default verification gas. will add create2 cost (3200+200*length) if initCode exists + preVerificationGas: 21000, // should also cover calldata cost. + maxFeePerGas: 0, + maxPriorityFeePerGas: 1e9, + paymaster: AddressZero, + paymasterData: "0x", + paymasterVerificationGasLimit: 3e5, + paymasterPostOpGasLimit: 0, + signature: "0x", +}; // Different compared to infinitism utils -export async function signUserOp (op: UserOperation, signer: Signer, entryPoint: string, chainId: number): Promise { - const message = getUserOpHash(op, entryPoint, chainId) +export async function signUserOp( + op: UserOperation, + signer: Signer, + entryPoint: string, + chainId: number, +): Promise { + const message = getUserOpHash(op, entryPoint, chainId); - const signature = await signer.signMessage(ethers.getBytes(message)); - - return { - ...op, - signature: signature - } + const signature = await signer.signMessage(ethers.getBytes(message)); + + return { + ...op, + signature: signature, + }; } -export function fillUserOpDefaults (op: Partial, defaults = DefaultsForUserOp): UserOperation { - const partial: any = { ...op } - // we want "item:undefined" to be used from defaults, and not override defaults, so we must explicitly - // remove those so "merge" will succeed. - for (const key in partial) { - if (partial[key] == null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete partial[key] - } +export function fillUserOpDefaults( + op: Partial, + defaults = DefaultsForUserOp, +): UserOperation { + const partial: any = { ...op }; + // we want "item:undefined" to be used from defaults, and not override defaults, so we must explicitly + // remove those so "merge" will succeed. + for (const key in partial) { + if (partial[key] == null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete partial[key]; } - const filled = { ...defaults, ...partial } - return filled + } + const filled = { ...defaults, ...partial }; + return filled; } // helper to fill structure: @@ -166,112 +239,151 @@ export function fillUserOpDefaults (op: Partial, defaults = Defau // sender - only in case of construction: fill sender from initCode. // callGasLimit: VERY crude estimation (by estimating call to account, and add rough entryPoint overhead // verificationGasLimit: hard-code default at 100k. should add "create2" cost -export async function fillUserOp (op: Partial, entryPoint?: EntryPoint, getNonceFunction = 'getNonce', nonceKey = "0"): Promise { - const op1 = { ...op } - const provider = ethers.provider - if (op.initCode != null && op.initCode !== "0x" ) { - const initAddr = dataSlice(op1.initCode!, 0, 20) - const initCallData = dataSlice(op1.initCode!, 20) - if (op1.nonce == null) op1.nonce = 0 - if (op1.sender == null) { - if (provider == null) throw new Error('no entrypoint/provider') - op1.sender = await entryPoint!.getSenderAddress(op1.initCode!).catch(e => e.errorArgs.sender) - } - if (op1.verificationGasLimit == null) { - if (provider == null) throw new Error('no entrypoint/provider') - const initEstimate = await provider.estimateGas({ - from: await entryPoint?.getAddress(), - to: initAddr, - data: initCallData, - gasLimit: 10e6 - }) - op1.verificationGasLimit = Number(DefaultsForUserOp.verificationGasLimit!) + Number(initEstimate) +export async function fillUserOp( + op: Partial, + entryPoint?: EntryPoint, + getNonceFunction = "getNonce", + nonceKey = "0", +): Promise { + const op1 = { ...op }; + const provider = ethers.provider; + if (op.initCode != null && op.initCode !== "0x") { + const initAddr = dataSlice(op1.initCode!, 0, 20); + const initCallData = dataSlice(op1.initCode!, 20); + if (op1.nonce == null) op1.nonce = 0; + if (op1.sender == null) { + if (provider == null) throw new Error("no entrypoint/provider"); + op1.sender = await entryPoint! + .getSenderAddress(op1.initCode!) + .catch((e) => e.errorArgs.sender); } + if (op1.verificationGasLimit == null) { + if (provider == null) throw new Error("no entrypoint/provider"); + const initEstimate = await provider.estimateGas({ + from: await entryPoint?.getAddress(), + to: initAddr, + data: initCallData, + gasLimit: 10e6, + }); + op1.verificationGasLimit = + Number(DefaultsForUserOp.verificationGasLimit!) + Number(initEstimate); } - if (op1.nonce == null) { - // TODO: nonce should be fetched from entrypoint based on key + } + if (op1.nonce == null) { + // TODO: nonce should be fetched from entrypoint based on key // if (provider == null) throw new Error('must have entryPoint to autofill nonce') // const c = new Contract(op.sender! as string, [`function ${getNonceFunction}() view returns(uint256)`], provider) // op1.nonce = await c[getNonceFunction]().catch(rethrow()) const nonce = await entryPoint?.getNonce(op1.sender!, nonceKey); op1.nonce = nonce ?? 0n; + } + if (op1.callGasLimit == null && op.callData != null) { + if (provider == null) + throw new Error("must have entryPoint for callGasLimit estimate"); + const gasEtimated = await provider.estimateGas({ + from: await entryPoint?.getAddress(), + to: op1.sender, + data: op1.callData as string, + }); + + // console.log('estim', op1.sender,'len=', op1.callData!.length, 'res=', gasEtimated) + // estimateGas assumes direct call from entryPoint. add wrapper cost. + op1.callGasLimit = gasEtimated; // .add(55000) + } + if (op1.paymaster != null) { + if (op1.paymasterVerificationGasLimit == null) { + op1.paymasterVerificationGasLimit = + DefaultsForUserOp.paymasterVerificationGasLimit; } - if (op1.callGasLimit == null && op.callData != null) { - if (provider == null) throw new Error('must have entryPoint for callGasLimit estimate') - const gasEtimated = await provider.estimateGas({ - from: await entryPoint?.getAddress(), - to: op1.sender, - data: op1.callData as string - }) - - // console.log('estim', op1.sender,'len=', op1.callData!.length, 'res=', gasEtimated) - // estimateGas assumes direct call from entryPoint. add wrapper cost. - op1.callGasLimit = gasEtimated // .add(55000) - } - if (op1.paymaster != null) { - if (op1.paymasterVerificationGasLimit == null) { - op1.paymasterVerificationGasLimit = DefaultsForUserOp.paymasterVerificationGasLimit - } - if (op1.paymasterPostOpGasLimit == null) { - op1.paymasterPostOpGasLimit = DefaultsForUserOp.paymasterPostOpGasLimit - } - } - if (op1.maxFeePerGas == null) { - if (provider == null) throw new Error('must have entryPoint to autofill maxFeePerGas') - const block = await provider.getBlock('latest') - op1.maxFeePerGas = Number(block!.baseFeePerGas!) + Number(op1.maxPriorityFeePerGas ?? DefaultsForUserOp.maxPriorityFeePerGas) - } - // TODO: this is exactly what fillUserOp below should do - but it doesn't. - // adding this manually - if (op1.maxPriorityFeePerGas == null) { - op1.maxPriorityFeePerGas = DefaultsForUserOp.maxPriorityFeePerGas - } - const op2 = fillUserOpDefaults(op1) - // if(op2 === undefined || op2 === null) { - // throw new Error('op2 is undefined or null') - // } - // eslint-disable-next-line @typescript-eslint/no-base-to-string - if (op2?.preVerificationGas?.toString() === '0') { - // TODO: we don't add overhead, which is ~21000 for a single TX, but much lower in a batch. - op2.preVerificationGas = callDataCost(encodeUserOp(op2, false)) + if (op1.paymasterPostOpGasLimit == null) { + op1.paymasterPostOpGasLimit = DefaultsForUserOp.paymasterPostOpGasLimit; } - return op2; + } + if (op1.maxFeePerGas == null) { + if (provider == null) + throw new Error("must have entryPoint to autofill maxFeePerGas"); + const block = await provider.getBlock("latest"); + op1.maxFeePerGas = + Number(block!.baseFeePerGas!) + + Number( + op1.maxPriorityFeePerGas ?? DefaultsForUserOp.maxPriorityFeePerGas, + ); + } + // TODO: this is exactly what fillUserOp below should do - but it doesn't. + // adding this manually + if (op1.maxPriorityFeePerGas == null) { + op1.maxPriorityFeePerGas = DefaultsForUserOp.maxPriorityFeePerGas; + } + const op2 = fillUserOpDefaults(op1); + // if(op2 === undefined || op2 === null) { + // throw new Error('op2 is undefined or null') + // } + // eslint-disable-next-line @typescript-eslint/no-base-to-string + if (op2?.preVerificationGas?.toString() === "0") { + // TODO: we don't add overhead, which is ~21000 for a single TX, but much lower in a batch. + op2.preVerificationGas = callDataCost(encodeUserOp(op2, false)); + } + return op2; } -export async function fillAndPack (op: Partial, entryPoint?: EntryPoint, getNonceFunction = 'getNonce'): Promise { - const userOp = await fillUserOp(op, entryPoint, getNonceFunction); - if(userOp === undefined) { - throw new Error('userOp is undefined') - } - return packUserOp(userOp) +export async function fillAndPack( + op: Partial, + entryPoint?: EntryPoint, + getNonceFunction = "getNonce", +): Promise { + const userOp = await fillUserOp(op, entryPoint, getNonceFunction); + if (userOp === undefined) { + throw new Error("userOp is undefined"); + } + return packUserOp(userOp); } -export async function fillAndSign (op: Partial, signer: Signer | Signer, entryPoint?: EntryPoint, getNonceFunction = 'getNonce', nonceKey = "0"): Promise { - const provider = ethers.provider - const op2 = await fillUserOp(op, entryPoint, getNonceFunction, nonceKey) - if(op2 === undefined) { - throw new Error('op2 is undefined') - } - - const chainId = await provider!.getNetwork().then(net => net.chainId) - const message = ethers.getBytes(getUserOpHash(op2, await entryPoint!.getAddress(), Number(chainId))) - - let signature - try { - signature = await signer.signMessage(message) - } catch (err: any) { - // attempt to use 'eth_sign' instead of 'personal_sign' which is not supported by Foundry Anvil - signature = await (signer as any)._legacySignMessage(message) - } - return { - ...op2, - signature - } +export async function fillAndSign( + op: Partial, + signer: Signer | Signer, + entryPoint?: EntryPoint, + getNonceFunction = "getNonce", + nonceKey = "0", +): Promise { + const provider = ethers.provider; + const op2 = await fillUserOp(op, entryPoint, getNonceFunction, nonceKey); + if (op2 === undefined) { + throw new Error("op2 is undefined"); + } + + const chainId = await provider!.getNetwork().then((net) => net.chainId); + const message = ethers.getBytes( + getUserOpHash(op2, await entryPoint!.getAddress(), Number(chainId)), + ); + + let signature; + try { + signature = await signer.signMessage(message); + } catch (err: any) { + // attempt to use 'eth_sign' instead of 'personal_sign' which is not supported by Foundry Anvil + signature = await (signer as any)._legacySignMessage(message); + } + return { + ...op2, + signature, + }; } - - export async function fillSignAndPack (op: Partial, signer: Signer | Signer, entryPoint?: EntryPoint, getNonceFunction = 'getNonce', nonceKey = "0"): Promise { - const filledAndSignedOp = await fillAndSign(op, signer, entryPoint, getNonceFunction, nonceKey) - return packUserOp(filledAndSignedOp) + +export async function fillSignAndPack( + op: Partial, + signer: Signer | Signer, + entryPoint?: EntryPoint, + getNonceFunction = "getNonce", + nonceKey = "0", +): Promise { + const filledAndSignedOp = await fillAndSign( + op, + signer, + entryPoint, + getNonceFunction, + nonceKey, + ); + return packUserOp(filledAndSignedOp); } /** @@ -281,67 +393,94 @@ export async function fillAndSign (op: Partial, signer: Signer | * @param entryPointAddress * @param txOverrides */ -export async function simulateValidation ( - userOp: PackedUserOperation, - entryPointAddress: string, - txOverrides?: any): Promise { - const entryPointSimulations = EntryPointSimulations__factory.createInterface() - const data = entryPointSimulations.encodeFunctionData('simulateValidation', [userOp]) - const tx: TransactionRequest = { - to: entryPointAddress, - data, - ...txOverrides - } - const stateOverride = { - [entryPointAddress]: { - code: EntryPointSimulationsJson.deployedBytecode - } - } - try { - const simulationResult = await ethers.provider.send('eth_call', [tx, 'latest', stateOverride]) - const res = entryPointSimulations.decodeFunctionResult('simulateValidation', simulationResult) - // note: here collapsing the returned "tuple of one" into a single value - will break for returning actual tuples - return res[0] - } catch (error: any) { - const revertData = error?.data - if (revertData != null) { - // note: this line throws the revert reason instead of returning it - entryPointSimulations.decodeFunctionResult('simulateValidation', revertData) - } - throw error +export async function simulateValidation( + userOp: PackedUserOperation, + entryPointAddress: string, + txOverrides?: any, +): Promise { + const entryPointSimulations = + EntryPointSimulations__factory.createInterface(); + const data = entryPointSimulations.encodeFunctionData("simulateValidation", [ + userOp, + ]); + const tx: TransactionRequest = { + to: entryPointAddress, + data, + ...txOverrides, + }; + const stateOverride = { + [entryPointAddress]: { + code: EntryPointSimulationsJson.deployedBytecode, + }, + }; + try { + const simulationResult = await ethers.provider.send("eth_call", [ + tx, + "latest", + stateOverride, + ]); + const res = entryPointSimulations.decodeFunctionResult( + "simulateValidation", + simulationResult, + ); + // note: here collapsing the returned "tuple of one" into a single value - will break for returning actual tuples + return res[0]; + } catch (error: any) { + const revertData = error?.data; + if (revertData != null) { + // note: this line throws the revert reason instead of returning it + entryPointSimulations.decodeFunctionResult( + "simulateValidation", + revertData, + ); } + throw error; + } } // TODO: this code is very much duplicated but "encodeFunctionData" is based on 20 overloads // TypeScript is not able to resolve overloads with variables: https://github.com/microsoft/TypeScript/issues/14107 -export async function simulateHandleOp ( - userOp: PackedUserOperation, - target: string, - targetCallData: string, - entryPointAddress: string, - txOverrides?: any): Promise { - const entryPointSimulations = EntryPointSimulations__factory.createInterface() - const data = entryPointSimulations.encodeFunctionData('simulateHandleOp', [userOp, target, targetCallData]) - const tx: TransactionRequest = { - to: entryPointAddress, - data, - ...txOverrides - } - const stateOverride = { - [entryPointAddress]: { - code: EntryPointSimulationsJson.deployedBytecode - } - } - try { - const simulationResult = await ethers.provider.send('eth_call', [tx, 'latest', stateOverride]) - const res = entryPointSimulations.decodeFunctionResult('simulateHandleOp', simulationResult) - // note: here collapsing the returned "tuple of one" into a single value - will break for returning actual tuples - return res[0] - } catch (error: any) { - const err = decodeRevertReason(error) - if (err != null) { - throw new Error(err) - } - throw error +export async function simulateHandleOp( + userOp: PackedUserOperation, + target: string, + targetCallData: string, + entryPointAddress: string, + txOverrides?: any, +): Promise { + const entryPointSimulations = + EntryPointSimulations__factory.createInterface(); + const data = entryPointSimulations.encodeFunctionData("simulateHandleOp", [ + userOp, + target, + targetCallData, + ]); + const tx: TransactionRequest = { + to: entryPointAddress, + data, + ...txOverrides, + }; + const stateOverride = { + [entryPointAddress]: { + code: EntryPointSimulationsJson.deployedBytecode, + }, + }; + try { + const simulationResult = await ethers.provider.send("eth_call", [ + tx, + "latest", + stateOverride, + ]); + const res = entryPointSimulations.decodeFunctionResult( + "simulateHandleOp", + simulationResult, + ); + // note: here collapsing the returned "tuple of one" into a single value - will break for returning actual tuples + return res[0]; + } catch (error: any) { + const err = decodeRevertReason(error); + if (err != null) { + throw new Error(err); } + throw error; } +}