Address Contract Verified
Address
0x75705aFCccDf186b1Ce2564e8d3E0F92e3D9954C
Balance
0 ETH
Nonce
12
Code Size
8075 bytes
Creator
0x8217C507...00ec at tx 0x40597fd5...1a559d
Indexed Transactions
0
Contract Bytecode
8075 bytes
0x6080806040526004361015610012575f80fd5b5f3560e01c9081631bfa8601146108f65750806328e376121461077f57806347f881851461036d578063715018a6146107285780638288cb2b146103b55780638a439e831461036d5780638cf8350f1461032b5780638da5cb5b1461030457806396eb5ec014610155578063a5db29f5146102dc578063a8790bc614610220578063be5dd1d5146101be578063c76012af146101be578063c922644514610192578063cfbc9fd2146101555763f2fde38b146100cc575f80fd5b34610151576020366003190112610151576100e56109bb565b6100ed610c93565b6001600160a01b0316801561013e575f80546001600160a01b03198116831782556001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09080a3005b631e4fbdf760e01b5f525f60045260245ffd5b5f80fd5b34610151576020366003190112610151576001600160a01b036101766109bb565b165f526002602052602060ff60405f2054166040519015158152f35b34610151575f36600319011261015157604060055460018060a01b036001541682519182526020820152f35b346101515760203660031901126101515760043567ffffffffffffffff8111610151576101f160209136906004016109f3565b8160405191805191829101835e600390820190815281900382019020546040516001600160a01b039091168152f35b34610151576020366003190112610151576004356001600160a01b038116908190036101515761024e610c93565b801561029757600180546001600160a01b0319811683179091556001600160a01b03167f3e03c28af1c3575cac186d8766e992ece872fab0839a34006c220d890d1066c55f80a3005b60405162461bcd60e51b815260206004820152601c60248201527f496e76616c696420456666696369656e745061792061646472657373000000006044820152606490fd5b34610151575f366003190112610151576001546040516001600160a01b039091168152602090f35b34610151575f366003190112610151575f546040516001600160a01b039091168152602090f35b346101515760203660031901126101515760043560055481101561015157610354602091610ba2565b905460405160039290921b1c6001600160a01b03168152f35b34610151576020366003190112610151576001600160a01b0361038e6109bb565b165f5260046020526103b16103a560405f20610ad8565b60405191829182610b78565b0390f35b34610151576103c336610a49565b90916001600160a01b0381166103da811515610bce565b6001600160a01b038316156106e3576103f584511515610c1a565b6040519284519360208601948086835e60039082019081528190036020019020546001600160a01b03166106a55760405160208101906104498161043b85888b87610c5b565b03601f1981018352826109d1565b519020600154604051919461129c808401929091906001600160a01b031667ffffffffffffffff8411858510176105d557879585946104aa94610cba87396001600160a01b0391821681529181166020830152909116604082015260600190565b03905ff5801561069a5760018060a01b031692835f52600260205260405f20600160ff198254161790556020604051809287518091835e81016003815203019020836001600160601b0360a01b825416179055825f52600460205260405f20845167ffffffffffffffff81116105d5576105248254610aa0565b601f8111610655575b50806020601f82116001146105f4575f916105e9575b508160011b915f199060031b1c19161790555b600554680100000000000000008110156105d5577fa46310d7c2975d7c75325d2d07b8b9497166dd04c7ab948dfe42100f43ad98d56105ca6020966105a2846001899601600555610ba2565b81546001600160a01b0360039290921b91821b19169086901b17905560405191829182610b78565b0390a4604051908152f35b634e487b7160e01b5f52604160045260245ffd5b905086015187610543565b5f8481528181209250601f198416905b81811061063d57509083600194939210610625575b5050811b019055610556565b8801515f1960f88460031b161c191690558780610619565b9192602060018192868d015181550194019201610604565b825f5260205f20601f830160051c81019160208410610690575b601f0160051c01905b818110610685575061052d565b5f8155600101610678565b909150819061066f565b6040513d5f823e3d90fd5b60405162461bcd60e51b8152602060048201526016602482015275515220636f646520616c72656164792065786973747360501b6044820152606490fd5b60405162461bcd60e51b815260206004820152601c60248201527f496e76616c69642077616c6c6574206f776e65722061646472657373000000006044820152606490fd5b34610151575f36600319011261015157610740610c93565b5f80546001600160a01b0319811682556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346101515761078d36610a49565b9091906107a46001600160a01b0383161515610bce565b6001600160a01b038116156108b957826107c2602094511515610c1a565b6040516107d88161043b85878984019687610c5b565b5190209161086e61129c85604051946107f3828401876109d1565b82865281860192610cba8439600154604080516001600160a01b039384168582019081529284166020840152969092168183015285810391820186529061083d90606001866109d1565b60405194859383850197518091895e840190838201905f8252519283915e01015f815203601f1981018352826109d1565b51902090604051918383019160ff60f81b83523060601b602185015260358401526055830152605582526108a36075836109d1565b905190206040516001600160a01b039091168152f35b60405162461bcd60e51b8152602060048201526015602482015274496e76616c6964206f776e6572206164647265737360581b6044820152606490fd5b34610151575f366003190112610151576005549081815260208101809260055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0905f5b81811061099c57505050816109519103826109d1565b604051918291602083019060208452518091526040830191905f5b81811061097a575050500390f35b82516001600160a01b031684528594506020938401939092019160010161096c565b82546001600160a01b031684526020909301926001928301920161093b565b600435906001600160a01b038216820361015157565b90601f8019910116810190811067ffffffffffffffff8211176105d557604052565b81601f820112156101515780359067ffffffffffffffff82116105d55760405192610a28601f8401601f1916602001856109d1565b8284526020838301011161015157815f926020809301838601378301015290565b906060600319830112610151576004356001600160a01b038116810361015157916024359067ffffffffffffffff821161015157610a89916004016109f3565b906044356001600160a01b03811681036101515790565b90600182811c92168015610ace575b6020831014610aba57565b634e487b7160e01b5f52602260045260245ffd5b91607f1691610aaf565b9060405191825f825492610aeb84610aa0565b8084529360018116908115610b565750600114610b12575b50610b10925003836109d1565b565b90505f9291925260205f20905f915b818310610b3a575050906020610b10928201015f610b03565b6020919350806001915483858901015201910190918492610b21565b905060209250610b1094915060ff191682840152151560051b8201015f610b03565b602060409281835280519182918282860152018484015e5f828201840152601f01601f1916010190565b600554811015610bba5760055f5260205f2001905f90565b634e487b7160e01b5f52603260045260245ffd5b15610bd557565b60405162461bcd60e51b815260206004820152601860248201527f496e76616c6964206d65726368616e74206164647265737300000000000000006044820152606490fd5b15610c2157565b60405162461bcd60e51b8152602060048201526012602482015271125b9d985b1a590814548818dbd91948125160721b6044820152606490fd5b60209060289492805192839101825e01916001600160601b03199060601b1682526001600160601b03199060601b1660148201520190565b5f546001600160a01b03163303610ca657565b63118cdaa760e01b5f523360045260245ffdfe6080346101b657601f61129c38819003918201601f19168301916001600160401b038311848410176101ba578084926060946040528339810103126101b657610047816101ce565b602082015190916001600160a01b038216918290036101b657604061006c91016101ce565b6001600160a01b039092169182156101a3575f80546001600160a01b031981168517825560405194916001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09080a3600180556001600160a01b03169182156101615750801561011c57600280546001600160a01b031916919091179055600380546001600160a81b031916909117600160a01b1790556040516110b990816101e38239f35b60405162461bcd60e51b815260206004820152601c60248201527f496e76616c696420456666696369656e745061792061646472657373000000006044820152606490fd5b62461bcd60e51b815260206004820152601860248201527f496e76616c6964206d65726368616e74206164647265737300000000000000006044820152606490fd5b631e4fbdf760e01b5f525f60045260245ffd5b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b03821682036101b65756fe6080806040526004361015610140575b50361561001a575f80fd5b60035461002c60ff8260a01c16610e4a565b34156101105760025460405163dd9a76ff60e01b81526001600160a01b0392831660048201525f60248201523460448201819052620dbba06064830152909260209284926084928492165af18015610105576100d2575b61008f34600454610ec0565b60045560018060a01b03600354165f6040513481523460208201527fc87d280560918d289b22a0b52eaa1dda72426184f275118ac1ed43183ac9ed8660403392a4005b6020813d6020116100fd575b816100eb60209383610e8a565b810103126100f95751610083565b5f80fd5b3d91506100de565b6040513d5f823e3d90fd5b60405162461bcd60e51b81526020600482015260086024820152674e6f2076616c756560c01b6044820152606490fd5b5f3560e01c90816322f3e2d414610e12575080633097729914610cd85780633aecd0e314610c4e5780633eff61e314610b49578063575de016146109f65780635af06e8f146109ad578063659bd43e146107e65780636e947298146107cb578063715018a61461077457806384411d65146107575780638da5cb5b14610730578063a2fba48414610678578063a5db29f514610650578063a5ff765114610628578063a8790bc61461056c578063acec338a14610527578063e3c1ed44146102975763f2fde38b14610212575f61000f565b346100f95760203660031901126100f95761022b610e34565b610233611005565b6001600160a01b03168015610284575f80546001600160a01b03198116831782556001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09080a3005b631e4fbdf760e01b5f525f60045260245ffd5b346100f95760203660031901126100f95760043567ffffffffffffffff81116100f957366023820112156100f95780600401359067ffffffffffffffff82116100f9573660248360051b830101116100f9576102f1610f2d565b61030260ff60035460a01c16610e4a565b81156104ed575f5b828110156104e757600581901b820160240135906001600160a01b0382168083036100f95780156104aa576040516370a0823160e01b815230600482015290602082602481845afa918215610105575f92610477575b5081610373575b5050600191500161030a565b6020826103e09561038f8260018060a01b036002541686610f4d565b60025460035460405163dd9a76ff60e01b81526001600160a01b03918216600482015292811660248401526044830193909352620dbba06064830152909687929091169082905f9082906084820190565b03925af1801561010557610446575b600193506103ff82600454610ec0565b600455838060a01b0360035416916040519080825260208201527fc87d280560918d289b22a0b52eaa1dda72426184f275118ac1ed43183ac9ed8660403392a48480610367565b6020843d821161046f575b8161045e60209383610e8a565b810103126100f957600193506103ef565b3d9150610451565b9091506020813d82116104a2575b8161049260209383610e8a565b810103126100f957519086610360565b3d9150610485565b60405162461bcd60e51b8152602060048201526015602482015274496e76616c696420746f6b656e206164647265737360581b6044820152606490fd5b60018055005b60405162461bcd60e51b8152602060048201526012602482015271139bc81d1bdad95b9cc81c1c9bdd9a59195960721b6044820152606490fd5b346100f95760203660031901126100f9576004358015158091036100f95761054d611005565b6003805460ff60a01b191660a09290921b60ff60a01b16919091179055005b346100f95760203660031901126100f9576004356001600160a01b038116908190036100f95761059a611005565b80156105e357600280546001600160a01b0319811683179091556001600160a01b03167f3e03c28af1c3575cac186d8766e992ece872fab0839a34006c220d890d1066c55f80a3005b60405162461bcd60e51b815260206004820152601c60248201527f496e76616c696420456666696369656e745061792061646472657373000000006044820152606490fd5b346100f9575f3660031901126100f9576003546040516001600160a01b039091168152602090f35b346100f9575f3660031901126100f9576002546040516001600160a01b039091168152602090f35b346100f95760203660031901126100f957610691610e34565b610699611005565b6001600160a01b031680156106eb57600380546001600160a01b0319811683179091556001600160a01b03167fc71a864d3f4bc0559344ce15f55b5e6a03a716ac1b44d4108555b3fc5cd827525f80a3005b60405162461bcd60e51b815260206004820152601860248201527f496e76616c6964206d65726368616e74206164647265737300000000000000006044820152606490fd5b346100f9575f3660031901126100f9575f546040516001600160a01b039091168152602090f35b346100f9575f3660031901126100f9576020600454604051908152f35b346100f9575f3660031901126100f95761078c611005565b5f80546001600160a01b0319811682556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346100f9575f3660031901126100f957602047604051908152f35b346100f95760403660031901126100f9576107ff610e34565b6024359061080b610f2d565b61081c60ff60035460a01c16610e4a565b6001600160a01b038116908115610968576020836108d69261086d6040516323b872dd60e01b8582015233602482015230604482015283606482015260648152610867608482610e8a565b8661102b565b6002546108859083906001600160a01b031687610f4d565b60025460035460405163dd9a76ff60e01b81526001600160a01b03918216600482015292811660248401526044830193909352620dbba06064830152909384929091169082905f9082906084820190565b03925af1801561010557610939575b506108f282600454610ec0565b60045560018060a01b0360035416916040519080825260208201527fc87d280560918d289b22a0b52eaa1dda72426184f275118ac1ed43183ac9ed8660403392a460018055005b6020813d602011610960575b8161095260209383610e8a565b810103126100f957516108e5565b3d9150610945565b60405162461bcd60e51b815260206004820152601860248201527f5573652072656365697665282920666f72206e617469766500000000000000006044820152606490fd5b346100f9575f3660031901126100f9576004546003546002546040805193845260a083901c60ff16151560208501526001600160a01b0392831690840152166060820152608090f35b346100f95760403660031901126100f957610a0f610e34565b60243590610a1b610f2d565b610a2c60ff60035460a01c16610e4a565b6001600160a01b03811690610a42821515610ee1565b8215610b0f576040516370a0823160e01b8152306004820152602081602481865afa80156101055784915f91610ada575b5010610a95576020836108d6926108858260018060a01b036002541687610f4d565b60405162461bcd60e51b815260206004820152601a60248201527f496e73756666696369656e7420746f6b656e2062616c616e63650000000000006044820152606490fd5b9150506020813d602011610b07575b81610af660209383610e8a565b810103126100f95783905185610a73565b3d9150610ae9565b60405162461bcd60e51b81526020600482015260126024820152710416d6f756e74206d757374206265203e20360741b6044820152606490fd5b346100f95760203660031901126100f957610b62610e34565b610b6a610f2d565b610b7b60ff60035460a01c16610e4a565b6001600160a01b038116610b90811515610ee1565b6040516370a0823160e01b815230600482015291602083602481855afa928315610105575f93610c1a575b508215610bde576020836108d6926108858260018060a01b036002541687610f4d565b60405162461bcd60e51b81526020600482015260146024820152734e6f20746f6b656e7320746f2070726f6365737360601b6044820152606490fd5b9092506020813d602011610c46575b81610c3660209383610e8a565b810103126100f957519183610bbb565b3d9150610c29565b346100f95760203660031901126100f957602460206001600160a01b03610c73610e34565b16604051928380926370a0823160e01b82523060048301525afa8015610105575f90610ca5575b602090604051908152f35b506020813d602011610cd0575b81610cbf60209383610e8a565b810103126100f95760209051610c9a565b3d9150610cb2565b346100f95760203660031901126100f957610cf1610e34565b610cf9610f2d565b610d0a60ff60035460a01c16610e4a565b6001600160a01b0381168015610dd6576040516370a0823160e01b815230600482015291602083602481855afa928315610105575f93610da2575b508215610d68576020836108d6926108858260018060a01b036002541687610f4d565b60405162461bcd60e51b81526020600482015260126024820152714e6f205553444320746f2070726f6365737360701b6044820152606490fd5b9092506020813d602011610dce575b81610dbe60209383610e8a565b810103126100f957519183610d45565b3d9150610db1565b60405162461bcd60e51b8152602060048201526014602482015273496e76616c69642055534443206164647265737360601b6044820152606490fd5b346100f9575f3660031901126100f95760209060ff60035460a01c1615158152f35b600435906001600160a01b03821682036100f957565b15610e5157565b60405162461bcd60e51b815260206004820152601160248201527057616c6c6574206e6f742061637469766560781b6044820152606490fd5b90601f8019910116810190811067ffffffffffffffff821117610eac57604052565b634e487b7160e01b5f52604160045260245ffd5b91908201809211610ecd57565b634e487b7160e01b5f52601160045260245ffd5b15610ee857565b60405162461bcd60e51b815260206004820152601f60248201527f5573652072656365697665282920666f72206e617469766520746f6b656e73006044820152606490fd5b600260015414610f3e576002600155565b633ee5aeb560e01b5f5260045ffd5b60205f604051938285019063095ea7b360e01b825260018060a01b031695866024870152604486015260448552610f85606486610e8a565b84519082855af15f513d82610fe0575b505015610fa157505050565b610fd9610fde936040519063095ea7b360e01b602083015260248201525f604482015260448152610fd3606482610e8a565b8261102b565b61102b565b565b909150610ffd57506001600160a01b0381163b15155b5f80610f95565b600114610ff6565b5f546001600160a01b0316330361101857565b63118cdaa760e01b5f523360045260245ffd5b905f602091828151910182855af115610105575f513d61107a57506001600160a01b0381163b155b61105a5750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b6001141561105356fea26469706673582212203260c18326c97dae681d964e614da3f07b839bbef4c295cf1f14c1465f0eb02764736f6c634300081e0033a26469706673582212204285022144ba7239624e2a0d8877df086beb79d7afc2b80b7c20c6d6b8fe08e164736f6c634300081e0033
Verified Source Code Full Match
Compiler: v0.8.30+commit.73712a01
EVM: cancun
Optimization: Yes (200 runs)
QRPaymentWalletFactory.sol 197 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Create2.sol"; import "./QRPaymentWallet.sol"; /** * @title QRPaymentWalletFactory * @author Mileston * @notice Factory contract for creating QR payment wallets with deterministic addresses * @dev Uses CREATE2 to generate predictable wallet addresses for QR codes. Each QR code * gets a unique wallet address that can be computed off-chain before deployment. * @custom:security-contact [email protected] */ contract QRPaymentWalletFactory is Ownable { // Events /** * @notice Emitted when a new QR payment wallet is created * @param wallet Address of the created wallet * @param merchant Address of the merchant * @param qrCodeId Unique identifier for the QR code * @param salt Salt used for CREATE2 deployment */ event QRWalletCreated( address indexed wallet, address indexed merchant, string qrCodeId, bytes32 indexed salt ); /** * @notice Emitted when the EfficientPay contract is updated * @param oldEfficientPay Previous EfficientPay address * @param newEfficientPay New EfficientPay address */ event EfficientPayUpdated( address indexed oldEfficientPay, address indexed newEfficientPay ); // State variables address payable public efficientPay; mapping(address => bool) public isQRWallet; mapping(string => address) public qrCodeToWallet; mapping(address => string) public walletToQRCode; address[] public allWallets; /** * @notice Constructor for the factory * @param _efficientPay Address of the EfficientPay contract */ constructor(address payable _efficientPay) Ownable(msg.sender) { require(_efficientPay != address(0), "Invalid EfficientPay address"); efficientPay = _efficientPay; } /** * @notice Creates a new QR payment wallet * @dev Uses CREATE2 to generate a deterministic address based on the QR code ID * @param merchant Address of the merchant to receive payments * @param qrCodeId Unique identifier for the QR code * @param walletOwner Address of the wallet owner (can be the merchant or a separate admin) * @return wallet Address of the created wallet */ function createQRWallet( address merchant, string memory qrCodeId, address walletOwner ) external returns (address wallet) { require(merchant != address(0), "Invalid merchant address"); require(walletOwner != address(0), "Invalid wallet owner address"); require(bytes(qrCodeId).length > 0, "Invalid QR code ID"); require( qrCodeToWallet[qrCodeId] == address(0), "QR code already exists" ); // Generate salt from QR code ID, merchant, and wallet owner bytes32 salt = keccak256( abi.encodePacked(qrCodeId, merchant, walletOwner) ); // Create the wallet using CREATE2 wallet = address( new QRPaymentWallet{salt: salt}(walletOwner, efficientPay, merchant) ); // Register the wallet isQRWallet[wallet] = true; qrCodeToWallet[qrCodeId] = wallet; walletToQRCode[wallet] = qrCodeId; allWallets.push(wallet); emit QRWalletCreated(wallet, merchant, qrCodeId, salt); } /** * @notice Computes the address of a QR wallet before deployment * @dev Can be used to generate QR codes with wallet addresses before deployment * @param merchant Address of the merchant * @param qrCodeId Unique identifier for the QR code * @param owner Address of the wallet owner * @return wallet Address that the wallet will have when deployed */ function computeQRWalletAddress( address merchant, string memory qrCodeId, address owner ) external view returns (address wallet) { require(merchant != address(0), "Invalid merchant address"); require(owner != address(0), "Invalid owner address"); require(bytes(qrCodeId).length > 0, "Invalid QR code ID"); bytes32 salt = keccak256(abi.encodePacked(qrCodeId, merchant, owner)); bytes32 hash = keccak256( abi.encodePacked( bytes1(0xff), address(this), salt, keccak256( abi.encodePacked( type(QRPaymentWallet).creationCode, abi.encode(owner, efficientPay, merchant) ) ) ) ); wallet = address(uint160(uint256(hash))); } /** * @notice Updates the EfficientPay contract address * @dev Only callable by owner. Affects all future wallet deployments. * @param _efficientPay New EfficientPay address */ function setEfficientPay(address payable _efficientPay) external onlyOwner { require(_efficientPay != address(0), "Invalid EfficientPay address"); address oldEfficientPay = address(efficientPay); efficientPay = _efficientPay; emit EfficientPayUpdated(oldEfficientPay, _efficientPay); } /** * @notice Gets all created wallets * @return Array of all wallet addresses */ function getAllWallets() external view returns (address[] memory) { return allWallets; } /** * @notice Gets the QR code ID for a wallet * @param wallet Address of the wallet * @return QR code ID associated with the wallet */ function getQRCodeForWallet( address wallet ) external view returns (string memory) { return walletToQRCode[wallet]; } /** * @notice Gets the wallet address for a QR code ID * @param qrCodeId QR code ID * @return Wallet address associated with the QR code */ function getWalletForQRCode( string memory qrCodeId ) external view returns (address) { return qrCodeToWallet[qrCodeId]; } /** * @notice Checks if an address is a QR payment wallet * @param wallet Address to check * @return True if the address is a QR payment wallet */ function isQRPaymentWallet(address wallet) external view returns (bool) { return isQRWallet[wallet]; } /** * @notice Gets factory statistics * @return _totalWallets Total number of wallets created * @return _efficientPay Current EfficientPay address */ function getFactoryStats() external view returns (uint256 _totalWallets, address _efficientPay) { return (allWallets.length, address(efficientPay)); } }
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Create2.sol 92 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev There's no code to deploy.
*/
error Create2EmptyBytecode();
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (bytecode.length == 0) {
revert Create2EmptyBytecode();
}
assembly ("memory-safe") {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
// if no address was created, and returndata is not empty, bubble revert
if and(iszero(addr), not(iszero(returndatasize()))) {
let p := mload(0x40)
returndatacopy(p, 0, returndatasize())
revert(p, returndatasize())
}
}
if (addr == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
assembly ("memory-safe") {
let ptr := mload(0x40) // Get free memory pointer
// | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
// |-------------------|---------------------------------------------------------------------------|
// | bytecodeHash | CCCCCCCCCCCCC...CC |
// | salt | BBBBBBBBBBBBB...BB |
// | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
// | 0xFF | FF |
// |-------------------|---------------------------------------------------------------------------|
// | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
// | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
mstore8(start, 0xff)
addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
}
QRPaymentWallet.sol 304 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import "./EfficientPay.sol";
/**
* @title QRPaymentWallet
* @author Mileston
* @notice Smart contract wallet for QR code payments that automatically processes received funds
* @dev Each QR code generates a unique wallet address that can receive payments and automatically
* process them through the EfficientPay contract. Supports native tokens and ERC20 tokens.
* @custom:security-contact [email protected]
*/
contract QRPaymentWallet is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address payable;
// Events
/**
* @notice Emitted when a payment is received and processed
* @param payer Address of the user who sent the payment
* @param token Address of the token used (0x0 for native token)
* @param amount Amount received
* @param merchant Address of the merchant who received the processed payment
* @param processedAmount Amount processed through EfficientPay
*/
event PaymentReceived(
address indexed payer,
address indexed token,
uint256 amount,
address indexed merchant,
uint256 processedAmount
);
/**
* @notice Emitted when the EfficientPay contract is updated
* @param oldEfficientPay Previous EfficientPay address
* @param newEfficientPay New EfficientPay address
*/
event EfficientPayUpdated(
address indexed oldEfficientPay,
address indexed newEfficientPay
);
/**
* @notice Emitted when the merchant address is updated
* @param oldMerchant Previous merchant address
* @param newMerchant New merchant address
*/
event MerchantUpdated(
address indexed oldMerchant,
address indexed newMerchant
);
// State variables
address payable public efficientPay;
address public merchant;
bool public isActive;
uint256 public totalProcessed;
/**
* @notice Constructor for QR payment wallet
* @param owner_ Address of the wallet owner (can be the merchant or a separate admin)
* @param _efficientPay Address of the EfficientPay contract
* @param merchant_ Address of the merchant to receive payments
*/
constructor(
address owner_,
address payable _efficientPay,
address merchant_
) Ownable(owner_) {
require(merchant_ != address(0), "Invalid merchant address");
require(_efficientPay != address(0), "Invalid EfficientPay address");
efficientPay = _efficientPay;
merchant = merchant_;
isActive = true;
}
/**
* @notice Receives native token payments (ETH, POL, AVAX) and processes them
* @dev Automatically processes the payment through EfficientPay contract with slippage protection
*/
receive() external payable {
require(isActive, "Wallet not active");
require(msg.value > 0, "No value");
EfficientPay(payable(efficientPay)).pay{value: msg.value}(
merchant,
address(0),
msg.value,
900_000 // 0.9 USD (6 decimals)
);
totalProcessed += msg.value;
emit PaymentReceived(
msg.sender,
address(0),
msg.value,
merchant,
msg.value
);
}
/**
* @notice Processes ERC20 token payments
* @dev Called by users who want to pay with ERC20 tokens
* @param token Address of the ERC20 token
* @param amount Amount of tokens to pay
*/
function payWithToken(address token, uint256 amount) external nonReentrant {
require(isActive, "Wallet not active");
require(token != address(0), "Use receive() for native");
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
SafeERC20.forceApprove(IERC20(token), efficientPay, amount);
EfficientPay(payable(efficientPay)).pay(
merchant,
token,
amount,
900_000 // 0.9 USD (6 decimals)
);
totalProcessed += amount;
emit PaymentReceived(msg.sender, token, amount, merchant, amount);
}
/**
* @notice Processes all available ERC20 tokens in the wallet
* @dev This function processes all tokens that have a balance > 0
* @param tokens Array of token addresses to process
*/
function processAllTokens(address[] calldata tokens) external nonReentrant {
require(isActive, "Wallet not active");
require(tokens.length > 0, "No tokens provided");
for (uint256 i = 0; i < tokens.length; i++) {
address token = tokens[i];
require(token != address(0), "Invalid token address");
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
SafeERC20.forceApprove(IERC20(token), efficientPay, balance);
EfficientPay(payable(efficientPay)).pay(
merchant,
token,
balance,
900_000 // 0.9 USD (6 decimals)
);
totalProcessed += balance;
emit PaymentReceived(
msg.sender,
token,
balance,
merchant,
balance
);
}
}
}
/**
* @notice Processes any ERC20 token payment (including USDC, USDT, DAI, etc.)
* @dev This function can be called by anyone to process ERC20 tokens that were sent directly to the wallet
* @param token Address of the ERC20 token to process
* @param amount Amount of tokens to process
*/
function processERC20Token(
address token,
uint256 amount
) external nonReentrant {
require(isActive, "Wallet not active");
require(token != address(0), "Use receive() for native tokens");
require(amount > 0, "Amount must be > 0");
uint256 balance = IERC20(token).balanceOf(address(this));
require(balance >= amount, "Insufficient token balance");
SafeERC20.forceApprove(IERC20(token), efficientPay, amount);
EfficientPay(payable(efficientPay)).pay(
merchant,
token,
amount,
900_000 // 0.9 USD (6 decimals)
);
totalProcessed += amount;
emit PaymentReceived(msg.sender, token, amount, merchant, amount);
}
/**
* @notice Processes all available tokens of a specific ERC20 token
* @dev Convenience function to process all balance of a specific token
* @param token Address of the ERC20 token to process
*/
function processAllERC20Token(address token) external nonReentrant {
require(isActive, "Wallet not active");
require(token != address(0), "Use receive() for native tokens");
uint256 balance = IERC20(token).balanceOf(address(this));
require(balance > 0, "No tokens to process");
SafeERC20.forceApprove(IERC20(token), efficientPay, balance);
EfficientPay(payable(efficientPay)).pay(
merchant,
token,
balance,
900_000 // 0.9 USD (6 decimals)
);
totalProcessed += balance;
emit PaymentReceived(msg.sender, token, balance, merchant, balance);
}
/**
* @notice Processes all available USDC in the wallet (convenience function)
* @dev This is a convenience wrapper for processAllERC20Token(usdcAddress)
* @param usdcAddress Address of the USDC token
*/
function processAllUSDC(address usdcAddress) external nonReentrant {
require(isActive, "Wallet not active");
require(usdcAddress != address(0), "Invalid USDC address");
uint256 balance = IERC20(usdcAddress).balanceOf(address(this));
require(balance > 0, "No USDC to process");
SafeERC20.forceApprove(IERC20(usdcAddress), efficientPay, balance);
EfficientPay(payable(efficientPay)).pay(
merchant,
usdcAddress,
balance,
900_000 // 0.9 USD (6 decimals)
);
totalProcessed += balance;
emit PaymentReceived(
msg.sender,
usdcAddress,
balance,
merchant,
balance
);
}
/**
* @notice Updates the EfficientPay contract address
* @dev Only callable by owner
* @param _efficientPay New EfficientPay address
*/
function setEfficientPay(address payable _efficientPay) external onlyOwner {
require(_efficientPay != address(0), "Invalid EfficientPay address");
address oldEfficientPay = efficientPay;
efficientPay = _efficientPay;
emit EfficientPayUpdated(oldEfficientPay, _efficientPay);
}
/**
* @notice Updates the merchant address
* @dev Only callable by owner
* @param _merchant New merchant address
*/
function setMerchant(address _merchant) external onlyOwner {
require(_merchant != address(0), "Invalid merchant address");
address oldMerchant = merchant;
merchant = _merchant;
emit MerchantUpdated(oldMerchant, _merchant);
}
/**
* @notice Activates or deactivates the wallet
* @dev Only callable by owner
* @param _isActive New active status
*/
function setActive(bool _isActive) external onlyOwner {
isActive = _isActive;
}
/**
* @notice Gets the wallet's ETH balance
* @return Current ETH balance
*/
function getETHBalance() external view returns (uint256) {
return address(this).balance;
}
/**
* @notice Gets the wallet's token balance
* @param token Address of the token
* @return Current token balance
*/
function getTokenBalance(address token) external view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
/**
* @notice Gets wallet statistics
* @return _totalProcessed Total amount processed
* @return _isActive Current active status
* @return _merchant Current merchant address
* @return _efficientPay Current EfficientPay address
*/
function getWalletStats()
external
view
returns (
uint256 _totalProcessed,
bool _isActive,
address _merchant,
address _efficientPay
)
{
return (totalProcessed, isActive, merchant, efficientPay);
}
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
Errors.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
ReentrancyGuard.sol 87 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
SafeERC20.sol 212 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
Address.sol 150 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
AggregatorV3Interface.sol 20 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
EfficientPay.sol 606 lines
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@uniswap/swap-router-contracts/interfaces/IV3SwapRouter.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "../interfaces/IWETH9.sol"; /** * @title EfficientPay * @author Mileston * @notice Upgradeable smart contract for processing payments in various tokens with automatic conversion to USDC * @dev This contract supports native token payments (ETH, POL, AVAX) and ERC20 tokens, automatically swapping them to USDC * using Uniswap V3. It includes safety mechanisms to return funds if swaps fail and maintains payment history. * @custom:security-contact [email protected] * @custom:security This contract has been audited and includes reentrancy protection */ contract EfficientPay is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable { using SafeERC20 for IERC20; using Address for address payable; /** * @notice Structure to store payment transaction details * @param payer Address of the user making the payment * @param merchant Address of the merchant receiving the payment * @param tokenIn Address of the token used for payment (0x0 for native token) * @param amountIn Amount of input token sent * @param amountUSDC Amount of USDC received after conversion * @param fee Fee amount taken by the protocol * @param timestamp Block timestamp when payment was processed * @param txHash Unique hash identifying this payment transaction */ struct PaymentRecord { address payer; address merchant; address tokenIn; uint256 amountIn; uint256 amountUSDC; uint256 fee; uint256 timestamp; bytes32 txHash; } // Storage variables mapping(address => PaymentRecord[]) public paymentHistory; mapping(address => PaymentRecord[]) public merchantHistory; mapping(address => bool) public isSupportedToken; mapping(address => string) public tokenSymbol; mapping(bytes32 => bool) public paymentSuccess; address public USDC; address public nativeToken; IV3SwapRouter public swapRouter; address public feeReceiver; // Constants uint256 public constant FEE_BPS = 40; // 0.4% fee (40 basis points) uint256 public constant BPS_DENOM = 10000; // 100% in basis points uint24 public constant UNISWAP_POOL_FEE = 500; // 0.05% pool fee // Events /** * @notice Emitted when a payment is successfully processed * @param payer Address of the user making the payment * @param merchant Address of the merchant receiving the payment * @param tokenIn Address of the input token * @param amountIn Amount of input token sent * @param amountUSDC Amount of USDC received * @param fee Fee amount taken * @param txHash Unique transaction hash */ event PaymentProcessed( address indexed payer, address indexed merchant, address indexed tokenIn, uint256 amountIn, uint256 amountUSDC, uint256 fee, bytes32 txHash ); /** * @notice Emitted when a token swap is completed * @param payer Address of the user * @param tokenIn Address of the input token * @param amountIn Amount of input token * @param amountOutUSDC Amount of USDC received */ event TokenSwapped( address indexed payer, address tokenIn, uint256 amountIn, uint256 amountOutUSDC ); /** * @notice Emitted when a supported token is added * @param token Address of the token * @param symbol Symbol of the token */ event SupportedTokenAdded(address token, string symbol); /** * @notice Emitted when a supported token is removed * @param token Address of the token */ event SupportedTokenRemoved(address token); /** * @notice Emitted when a swap fails for debugging purposes * @param payer Address of the user * @param tokenIn Address of the input token * @param amountIn Amount of input token * @param reason Reason for the swap failure */ event DebugSwapError( address indexed payer, address tokenIn, uint256 amountIn, string reason ); /** * @notice Emitted when the fee receiver is updated * @param oldFeeReceiver Previous fee receiver address * @param newFeeReceiver New fee receiver address */ event FeeReceiverUpdated( address indexed oldFeeReceiver, address indexed newFeeReceiver ); /** * @notice Emitted when a batch payment is made * @param sender Address of the sender * @param recipients Array of recipient addresses * @param amounts Array of USDC amounts sent to each recipient * @param total Total USDC amount sent * @param fee Total fee taken */ event BatchPayment( address indexed sender, address[] recipients, uint256[] amounts, uint256 total, uint256 fee ); /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /** * @notice Initializes the contract with supported tokens and configuration * @dev This function can only be called once during deployment * @param supportedTokens Array of token addresses to support * @param symbols Array of token symbols corresponding to supportedTokens * @param _usdc Address of the USDC token * @param _nativeToken Address of the wrapped native token (WETH, WMATIC, etc.) * @param _swapRouter Address of the Uniswap V3 SwapRouter * @param feeReceiver_ Address of the fee receiver */ function initialize( address[] memory supportedTokens, string[] memory symbols, address _usdc, address _nativeToken, address _swapRouter, address feeReceiver_ ) public initializer { require(supportedTokens.length == symbols.length, "Mismatched input"); require(_usdc != address(0), "Invalid USDC address"); require(_nativeToken != address(0), "Invalid native token address"); require(_swapRouter != address(0), "Invalid swap router address"); require(feeReceiver_ != address(0), "Invalid fee receiver"); __Ownable_init(msg.sender); __ReentrancyGuard_init(); __UUPSUpgradeable_init(); USDC = _usdc; nativeToken = _nativeToken; swapRouter = IV3SwapRouter(_swapRouter); feeReceiver = feeReceiver_; for (uint256 i = 0; i < supportedTokens.length; i++) { // Allow address(0) for native token isSupportedToken[supportedTokens[i]] = true; tokenSymbol[supportedTokens[i]] = symbols[i]; emit SupportedTokenAdded(supportedTokens[i], symbols[i]); } } /** * @notice Processes a payment by converting input token to USDC and transferring to merchant * @dev Supports native tokens (ETH, POL, AVAX) and ERC20 tokens. Native tokens are wrapped before swapping. * If swap fails, funds are returned to the user. Fee is calculated as 0.4% of USDC amount. * @param merchant Address of the merchant to receive the payment * @param tokenIn Address of the token to pay with (0x0 for native token) * @param amountIn Amount of input token to pay * @param minAmountOut Minimum amount of USDC to receive (slippage protection) * @return txHash Unique identifier for this payment transaction */ function pay( address merchant, address tokenIn, uint256 amountIn, uint256 minAmountOut // optional, can be 0 ) external payable nonReentrant returns (bytes32) { require(merchant != address(0), "Invalid merchant"); require(isSupportedToken[tokenIn], "Token not supported"); require(amountIn > 0, "Amount must be > 0"); uint256 usdcAmount; uint256 feeAmount; if (tokenIn == USDC) { // Direct USDC payment - no swap needed IERC20(USDC).safeTransferFrom(msg.sender, address(this), amountIn); usdcAmount = amountIn; } else if (tokenIn == address(0)) { // Native token payment (ETH, POL, AVAX) require(msg.value == amountIn, "Native token value mismatch"); usdcAmount = _swapWithUniswapV3Native(amountIn, minAmountOut); } else { // ERC20 token payment IERC20(tokenIn).safeTransferFrom( msg.sender, address(this), amountIn ); usdcAmount = _swapWithUniswapV3ERC20( tokenIn, amountIn, minAmountOut ); } // Calculate fee (0.4% of USDC amount) feeAmount = (usdcAmount * FEE_BPS) / BPS_DENOM; uint256 merchantAmount = usdcAmount - feeAmount; // Transfer USDC to merchant and fee to fee receiver IERC20(USDC).safeTransfer(merchant, merchantAmount); IERC20(USDC).safeTransfer(feeReceiver, feeAmount); // Create payment record PaymentRecord memory rec = PaymentRecord({ payer: msg.sender, merchant: merchant, tokenIn: tokenIn, amountIn: amountIn, amountUSDC: usdcAmount, fee: feeAmount, timestamp: block.timestamp, txHash: keccak256( abi.encodePacked( msg.sender, merchant, tokenIn, amountIn, block.timestamp ) ) }); // Store payment records paymentHistory[msg.sender].push(rec); merchantHistory[merchant].push(rec); paymentSuccess[rec.txHash] = true; emit PaymentProcessed( msg.sender, merchant, tokenIn, amountIn, usdcAmount, feeAmount, rec.txHash ); return rec.txHash; } /** * @notice Swaps an ERC20 token to USDC and sends USDC to the user * @param tokenIn Address of the input token * @param amountIn Amount of input token to swap * @param minAmountOut Minimum amount of USDC to receive */ function swapToUSDC( address tokenIn, uint256 amountIn, uint256 minAmountOut ) external nonReentrant { require(isSupportedToken[tokenIn], "Token not supported"); require(tokenIn != address(0), "Use swapNativeToUSDC for native"); require(amountIn > 0, "Amount must be > 0"); IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn); uint256 usdcAmount = _swapWithUniswapV3ERC20( tokenIn, amountIn, minAmountOut ); uint256 fee = (usdcAmount * FEE_BPS) / BPS_DENOM; uint256 userAmount = usdcAmount - fee; IERC20(USDC).safeTransfer(msg.sender, userAmount); IERC20(USDC).safeTransfer(feeReceiver, fee); } /** * @notice Swaps native token to USDC and sends USDC to the user * @param minAmountOut Minimum amount of USDC to receive */ function swapNativeToUSDC( uint256 minAmountOut ) external payable nonReentrant { require(isSupportedToken[address(0)], "Native token not supported"); require(msg.value > 0, "Amount must be > 0"); uint256 usdcAmount = _swapWithUniswapV3Native(msg.value, minAmountOut); uint256 fee = (usdcAmount * FEE_BPS) / BPS_DENOM; uint256 userAmount = usdcAmount - fee; IERC20(USDC).safeTransfer(msg.sender, userAmount); IERC20(USDC).safeTransfer(feeReceiver, fee); } /** * @notice Batch sends USDC to multiple recipients with a 0.4% fee * @param recipients Array of recipient addresses * @param amounts Array of USDC amounts to send to each recipient */ function batchPayUSDC( address[] calldata recipients, uint256[] calldata amounts ) external nonReentrant { require(recipients.length == amounts.length, "Mismatched input"); require( recipients.length > 0 && recipients.length <= 100, "Invalid recipient count" ); uint256 total = 0; for (uint256 i = 0; i < amounts.length; i++) { require(recipients[i] != address(0), "Invalid recipient"); require(amounts[i] > 0, "Zero amount"); total += amounts[i]; } uint256 fee = (total * FEE_BPS) / BPS_DENOM; uint256 totalWithFee = total + fee; IERC20(USDC).safeTransferFrom(msg.sender, address(this), totalWithFee); for (uint256 i = 0; i < recipients.length; i++) { IERC20(USDC).safeTransfer(recipients[i], amounts[i]); } IERC20(USDC).safeTransfer(feeReceiver, fee); emit BatchPayment(msg.sender, recipients, amounts, total, fee); } /** * @notice Swaps native token (ETH, POL, AVAX) to USDC using Uniswap V3 * @dev Wraps native token to WETH/WMATIC/etc. before swapping. If swap fails, * unwraps and returns native token to user. * @param amountIn Amount of native token to swap * @param minAmountOut Minimum amount of USDC to receive * @return amountOut Amount of USDC received */ function _swapWithUniswapV3Native( uint256 amountIn, uint256 minAmountOut ) internal returns (uint256 amountOut) { // Wrap native token to WETH/WMATIC/etc. IWETH9(nativeToken).deposit{value: amountIn}(); // Approve wrapped token for swap router IERC20(nativeToken).approve(address(swapRouter), amountIn); // Perform the swap IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter .ExactInputSingleParams({ tokenIn: nativeToken, tokenOut: USDC, fee: UNISWAP_POOL_FEE, recipient: address(this), amountIn: amountIn, amountOutMinimum: minAmountOut, sqrtPriceLimitX96: 0 }); try swapRouter.exactInputSingle(params) returns (uint256 amountOut_) { amountOut = amountOut_; emit TokenSwapped(msg.sender, address(0), amountIn, amountOut); } catch (bytes memory reason) { // If swap fails, unwrap and return native token to user IWETH9(nativeToken).withdraw(amountIn); payable(msg.sender).transfer(amountIn); string memory revertMsg = _getRevertMsg(reason); emit DebugSwapError(msg.sender, address(0), amountIn, revertMsg); revert(revertMsg); } } /** * @notice Swaps ERC20 token to USDC using Uniswap V3 * @dev If swap fails, returns the original token to user * @param tokenIn Address of the input token * @param amountIn Amount of input token to swap * @param minAmountOut Minimum amount of USDC to receive * @return amountOut Amount of USDC received */ function _swapWithUniswapV3ERC20( address tokenIn, uint256 amountIn, uint256 minAmountOut ) internal returns (uint256 amountOut) { // Approve input token for swap router IERC20(tokenIn).approve(address(swapRouter), amountIn); // Perform the swap IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter .ExactInputSingleParams({ tokenIn: tokenIn, tokenOut: USDC, fee: UNISWAP_POOL_FEE, recipient: address(this), amountIn: amountIn, amountOutMinimum: minAmountOut, sqrtPriceLimitX96: 0 }); try swapRouter.exactInputSingle(params) returns (uint256 amountOut_) { amountOut = amountOut_; emit TokenSwapped(msg.sender, tokenIn, amountIn, amountOut); } catch (bytes memory reason) { // If swap fails, return tokens to user IERC20(tokenIn).transfer(msg.sender, amountIn); string memory revertMsg = _getRevertMsg(reason); emit DebugSwapError(msg.sender, tokenIn, amountIn, revertMsg); revert(revertMsg); } } /** * @notice Extracts revert message from bytes data * @dev Helper function to decode revert messages from failed swaps * @param _returnData Bytes data from the revert * @return Revert message as string */ function _getRevertMsg( bytes memory _returnData ) internal pure returns (string memory) { if (_returnData.length < 68) return "Swap failed: Unknown error"; assembly { _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); } // View functions /** * @notice Gets payment history for a specific wallet * @param wallet Address of the wallet * @return Array of payment records */ function getPaymentHistory( address wallet ) external view returns (PaymentRecord[] memory) { return paymentHistory[wallet]; } /** * @notice Gets payment history for a specific merchant * @param merchant Address of the merchant * @return Array of payment records */ function getMerchantHistory( address merchant ) external view returns (PaymentRecord[] memory) { return merchantHistory[merchant]; } /** * @notice Checks if a payment transaction was successful * @param txHash Hash of the payment transaction * @return True if payment was successful */ function wasPaymentSuccessful(bytes32 txHash) external view returns (bool) { return paymentSuccess[txHash]; } // Admin functions /** * @notice Adds a new supported token * @dev Only callable by contract owner * @param token Address of the token to add * @param symbol Symbol of the token */ function addSupportedToken( address token, string memory symbol ) external onlyOwner { isSupportedToken[token] = true; tokenSymbol[token] = symbol; emit SupportedTokenAdded(token, symbol); } /** * @notice Removes a supported token * @dev Only callable by contract owner * @param token Address of the token to remove */ function removeSupportedToken(address token) external onlyOwner { isSupportedToken[token] = false; emit SupportedTokenRemoved(token); } /** * @notice Updates the USDC token address * @dev Only callable by contract owner * @param _usdc New USDC token address */ function setUSDC(address _usdc) external onlyOwner { require(_usdc != address(0), "Invalid USDC address"); USDC = _usdc; } /** * @notice Updates the native token address * @dev Only callable by contract owner * @param _nativeToken New native token address */ function setNativeToken(address _nativeToken) external onlyOwner { require(_nativeToken != address(0), "Invalid native token address"); nativeToken = _nativeToken; } /** * @notice Updates the swap router address * @dev Only callable by contract owner * @param _swapRouter New swap router address */ function setSwapRouter(address _swapRouter) external onlyOwner { require(_swapRouter != address(0), "Invalid swap router address"); swapRouter = IV3SwapRouter(_swapRouter); } /** * @notice Updates the fee receiver address * @dev Only callable by contract owner * @param _feeReceiver New fee receiver address */ function setFeeReceiver(address _feeReceiver) external onlyOwner { require(_feeReceiver != address(0), "Invalid fee receiver address"); address oldFeeReceiver = feeReceiver; feeReceiver = _feeReceiver; emit FeeReceiverUpdated(oldFeeReceiver, _feeReceiver); } /** * @notice Withdraws stuck ERC20 tokens from the contract * @dev Only callable by contract owner. Emergency function to recover stuck tokens. * @param token Address of the token to withdraw */ function withdrawStuckToken(address token) external onlyOwner { uint256 balance = IERC20(token).balanceOf(address(this)); if (balance > 0) { IERC20(token).transfer(owner(), balance); } } /** * @notice Withdraws stuck ETH from the contract * @dev Only callable by contract owner. Emergency function to recover stuck ETH. */ function withdrawStuckETH() external onlyOwner { uint256 balance = address(this).balance; if (balance > 0) { payable(owner()).transfer(balance); } } /** * @notice Authorizes contract upgrades * @dev Only callable by contract owner * @param newImplementation Address of the new implementation */ function _authorizeUpgrade( address newImplementation ) internal override onlyOwner {} /** * @notice Allows the contract to receive ETH * @dev Required for native token deposits */ receive() external payable {} }
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
Initializable.sol 238 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
OwnableUpgradeable.sol 119 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
ReentrancyGuardUpgradeable.sol 108 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
UUPSUpgradeable.sol 152 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
IV3SwapRouter.sol 69 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IV3SwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
TransferHelper.sol 60 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
IWETH9.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface IWETH9 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
draft-IERC1822.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
ERC1967Utils.sol 177 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.22;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
IUniswapV3SwapCallback.sol 21 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* 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[ERC 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);
}
IBeacon.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
IERC1967.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
StorageSlot.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
Read Contract
allWallets 0x8cf8350f → address
computeQRWalletAddress 0x28e37612 → address
efficientPay 0xa5db29f5 → address
getAllWallets 0x1bfa8601 → address[]
getFactoryStats 0xc9226445 → uint256, address
getQRCodeForWallet 0x8a439e83 → string
getWalletForQRCode 0xbe5dd1d5 → address
isQRPaymentWallet 0x96eb5ec0 → bool
isQRWallet 0xcfbc9fd2 → bool
owner 0x8da5cb5b → address
qrCodeToWallet 0xc76012af → address
walletToQRCode 0x47f88185 → string
Write Contract 4 functions
These functions modify contract state and require a wallet transaction to execute.
createQRWallet 0x8288cb2b
address merchant
string qrCodeId
address walletOwner
returns: address
renounceOwnership 0x715018a6
No parameters
setEfficientPay 0xa8790bc6
address _efficientPay
transferOwnership 0xf2fde38b
address newOwner
Recent Transactions
No transactions found for this address