Verified contractExactMIT
BuyRouterV2
Address0x79ab0ccb6bb438c330a87a29f196c9d56c150bd7
- Balance
0 ETH
- Transactions
6
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,237,850
- Creation transaction
- 0x7e411133ef…eb832e98c3
2 files
- src/BuyRouterV2.solmain14.68 KB
- lib/solady/src/utils/ReentrancyGuard.sol2.33 KB
src/BuyRouterV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
interface ICredits {
function ownerOf(uint256 id) external view returns (address);
function seedOf(uint256 id) external view returns (bytes21);
function timestampOf(uint256 id) external view returns (uint64);
function setApprovalForAll(address op, bool ok) external;
}
interface ICreditScore {
function scoreOf(bytes21 seed, uint64 paidAt) external pure returns (uint256);
}
interface IScoreToken {
function balanceOf(address who) external view returns (uint256);
/// Wrap the given Credits into SCORE, delivering the SCORE to `to`. The SCORE token pulls each NFT from the
/// caller with `transferFrom`, so the caller must be an approved operator for Credits on the SCORE token.
function wrap(uint256[] calldata ids, address to) external;
}
/// @notice Version 2 of the one-transaction optimal buy. Everything BuyRouter (v1) does — fill OpenSea listings of
/// Credits through Seaport and swap ETH for SCORE on its Uniswap v4 pool, in a single call, with the 1% pool-matching
/// fee on the listing spend, refund-last of leftover ETH, a ReentrancyGuard, no owner/admin and two fixed call
/// targets — plus ONE new optional leg: wrap the bought Credits into SCORE in the same transaction.
///
/// With `wrapCredits == false` this behaves exactly like v1: the `seaportCall` recipient is the buyer, the Credits
/// arrive as NFTs in the buyer's wallet, and `scoreBought` is the pool SCORE delta.
///
/// With `wrapCredits == true` the `seaportCall` recipient is the ROUTER, so the bought Credits land here for the
/// duration of the transaction. The router then finds which of `creditIds` it now owns and calls
/// `ScoreToken.wrap(thoseIds, buyer)`, so the buyer receives SCORE instead of NFTs and ends up holding none of the
/// bought Credits. If wrapping is closed on chain (paused / migrating) `wrap` reverts and the whole buy reverts
/// with it — a fail-safe; the caller simply does not use wrap mode then.
///
/// The router is an approved Credits operator for the SCORE token (set once in the constructor), which is the only
/// approval it ever grants. It still holds no ETH, NFTs or SCORE between transactions, has no owner and no admin,
/// and only ever calls the two fixed addresses (Seaport, the Universal Router) plus the two fixed protocol
/// contracts (the SCORE token for `wrap`, the Credits collection for the one-time approval); no target is taken
/// from an argument.
contract BuyRouterV2 is ReentrancyGuard {
/// Seaport 1.6, the address OpenSea returns for every Credits listing. Never a call target from an argument.
address public constant SEAPORT = 0x0000000000000068F116a894984e2DB1123eB395;
/// Uniswap Universal Router. Never a call target from an argument.
address public constant UNIVERSAL_ROUTER = 0x66a9893cC07D91D95644AEDD05D03f95e1dBA8Af;
/// The Credits collection.
ICredits public constant CREDITS = ICredits(0x97630aA70AB14ed9883B41dAfccBc11349723043);
/// CreditScore, the same contract Statements uses (`src/CreditsBuyer.sol`). Scores a Credit from its seed
/// and payment time; returns points x 10,000 (80.0000 -> 800_000, 800.0000 -> 8_000_000).
ICreditScore public constant SCORE = ICreditScore(0x817A9cFfb4d6E7c206e745A4229001A472C1b7B7);
/// The SCORE token bought on the v4 pool and minted by wrapping. 1 SCORE (1e18 base units) == 1 Credit Score point.
IScoreToken public constant SCORE_TOKEN = IScoreToken(0x5d5FC76114b6Fe0FC41A26e38c0Df42c87577EC8);
/// A Credit's score comes back x 10,000; a SCORE point is 1e18. 1e14 turns the former into the latter, so
/// Credits and SCORE are summed in the same 1e18-per-point unit as `minTotalPoints`. The multiply is exact.
uint256 private constant POINT_SCALE = 1e14;
/// The pool-matching fee on the OpenSea (Credits) leg: 1% (100 bps) of the ETH actually spent on listings in
/// this call, charged on top of the listing payment (the buyer provides it in msg.value), so buying Credits
/// through the router costs the same 1% a SCORE buyer pays the pool. The swap leg is NOT charged here; the
/// pool already takes its own 1% on it. A swap-only buy (no listing spend) pays nothing.
uint256 private constant FEE_BPS = 100;
uint256 private constant BPS = 10_000;
/// How the fee splits, hardcoded like SEAPORT/UNIVERSAL_ROUTER: 5% dev, 47.5% Builder, the rest (47.5% plus any
/// integer-division dust) Burner, so the three shares always sum to the fee exactly and nothing is stranded.
uint256 private constant DEV_BPS = 500; // 5%
uint256 private constant BUILDER_BPS = 4750; // 47.5%; Burner takes the remainder (47.5% + dust)
/// Dev wallet (EOA). Scorepool's Builder accrues ETH for the keeper's build() (protocol-owned liquidity); its
/// Burner accrues ETH for burn() (buy & burn POOL). Both have `receive() payable`, so a plain transfer lands.
address public constant FEE_DEV = 0x40192BdadDe29be8FF0B5e96468540ff8E68286C;
address public constant FEE_BUILDER = 0xF858e3bc89978EF055E0BfFC37aF1381C8A77BF1;
address public constant FEE_BURNER = 0xc4CB3ccDd3aE6E4a417eE2161685C7891A3FE94b;
error SeaportFailed();
error SwapFailed();
error BelowMinScore(uint256 got, uint256 min);
error BelowMinTotal(uint256 got, uint256 min);
error RefundFailed();
error FeeTransferFailed();
/// `creditsToBuyer` is how many of `creditIds` the buyer holds at the end (0 in wrap mode), `creditPoints` their
/// Credit Score x 10,000, `wrapped` how many Credits were wrapped to SCORE for the buyer, `poolScore` the SCORE
/// received from the pool swap (1e18 per point), `totalGained` the buyer's whole SCORE increase (wrapped + pool),
/// `fee` the pool-matching fee on the listing spend, `refund` the ETH swept back. No address or amount that is
/// not the caller's own (or the fixed protocol fee) is logged.
event Bought(
address indexed buyer,
uint256 creditsToBuyer,
uint256 creditPoints,
uint256 wrapped,
uint256 poolScore,
uint256 totalGained,
uint256 fee,
uint256 refund
);
/// Approve the SCORE token as a Credits operator once, so `wrap` can pull the Credits the router buys in wrap
/// mode. The router only ever holds Credits mid-transaction, so this standing approval grants nothing that
/// persists between calls.
constructor() {
CREDITS.setApprovalForAll(address(SCORE_TOKEN), true);
}
/// Seaport and the Universal Router return unspent ETH to this contract with an empty-calldata call.
receive() external payable {}
/// Buy Credits and/or SCORE in one transaction. Everything is delivered to `msg.sender` (as NFTs, or — when
/// `wrapCredits` — the Credits are wrapped to SCORE for `msg.sender`); leftover ETH is swept back to
/// `msg.sender` last. Reverts (changing nothing) unless both minimums are met.
///
/// @param creditIds the Credits this plan intends to buy. Non-wrap: `seaportCall` recipient is msg.sender.
/// Wrap: `seaportCall` recipient is the router (address(this)).
/// @param seaportCall `fulfillAvailableAdvancedOrders(...)` built off chain; empty to skip the NFT leg
/// @param seaportValue ETH forwarded to Seaport (the most the listings can cost; the rest comes back)
/// @param swapInput Universal Router `execute(...)` for the ETH->SCORE swap; empty to skip the swap leg
/// @param swapValue ETH forwarded to the Universal Router (the swap's exact-in amount)
/// @param wrapCredits if true, wrap the bought Credits to SCORE for the buyer instead of leaving them as NFTs
/// @param minScoreOut least SCORE (1e18 per point) the caller will accept from the POOL swap leg specifically
/// @param minTotalPoints least total points the caller will accept: held Credits' score + all SCORE gained
/// (wrapped SCORE + pool SCORE), both at 1e18 per point
function buy(
uint256[] calldata creditIds,
bytes calldata seaportCall,
uint256 seaportValue,
bytes calldata swapInput,
uint256 swapValue,
bool wrapCredits,
uint256 minScoreOut,
uint256 minTotalPoints
) external payable nonReentrant {
address buyer = msg.sender;
uint256 scoreBefore = SCORE_TOKEN.balanceOf(buyer);
// Which of the planned Credits the buyer already held: those are not "arrived" and must not be counted as
// held points, so a Credit the buyer somehow owns before the call cannot inflate the total. (In wrap mode
// the buyer ends up holding none of the bought Credits, so this only ever excludes a pre-owned one.)
uint256 n = creditIds.length;
bool[] memory had = new bool[](n);
for (uint256 i; i < n; ++i) {
had[i] = _ownerIs(creditIds[i], buyer);
}
// (1) the listings. The recipient is baked into the calldata: msg.sender in non-wrap mode (the Credits never
// touch here), the router in wrap mode (the Credits land here so step (2) can wrap them). The fee is charged
// on what the listings ACTUALLY cost, measured as the net drop in the router's own balance across the call:
// we forward `seaportValue` and Seaport refunds whatever it did not spend, so the net drop is exactly the ETH
// the listings consumed. A stray starting balance cancels out; an empty Seaport leg leaves this at 0.
uint256 listingSpend;
if (seaportCall.length != 0) {
uint256 balBefore = address(this).balance;
(bool ok,) = SEAPORT.call{value: seaportValue}(seaportCall);
if (!ok) revert SeaportFailed();
listingSpend = balBefore - address(this).balance;
}
// (2) wrap, if asked. Find which of the planned Credits the router actually received and wrap exactly those
// to the buyer; passing an id the router does not own would make `wrap` revert. If wrapping is closed on
// chain, `wrap` reverts and takes the whole buy with it (fail-safe). Nothing to wrap -> skip.
uint256 wrapped;
if (wrapCredits) {
uint256[] memory arrived = new uint256[](n);
for (uint256 i; i < n; ++i) {
if (_ownerIs(creditIds[i], address(this))) {
arrived[wrapped] = creditIds[i];
unchecked {
++wrapped;
}
}
}
if (wrapped != 0) {
assembly {
mstore(arrived, wrapped) // shrink the array to exactly the ids that arrived
}
SCORE_TOKEN.wrap(arrived, buyer);
}
}
// (3) the pool swap. The TAKE recipient is baked in as msg.sender, so the SCORE arrives in the buyer's
// wallet. Measure the pool SCORE as the buyer's balance delta around THIS call only, so it excludes any
// SCORE the wrap leg just minted, and hold it to its own minimum.
uint256 beforeSwap = SCORE_TOKEN.balanceOf(buyer);
if (swapInput.length != 0) {
(bool ok,) = UNIVERSAL_ROUTER.call{value: swapValue}(swapInput);
if (!ok) revert SwapFailed();
}
uint256 poolScore = SCORE_TOKEN.balanceOf(buyer) - beforeSwap;
if (poolScore < minScoreOut) revert BelowMinScore(poolScore, minScoreOut);
// (4) the Credits the buyer actually holds now (non-wrap: the NFTs bought; wrap: none, since they were
// delivered to the router and wrapped away). A pre-owned Credit is excluded by `had`.
uint256 creditPoints; // x 10,000
uint256 heldToBuyer;
for (uint256 i; i < n; ++i) {
uint256 id = creditIds[i];
if (!had[i] && _ownerIs(id, buyer)) {
creditPoints += SCORE.scoreOf(CREDITS.seedOf(id), CREDITS.timestampOf(id));
unchecked {
++heldToBuyer;
}
}
}
// (5) the guard: held Credits' score plus ALL the SCORE the buyer gained (wrapped SCORE + pool SCORE), each
// at 1 SCORE per point. A wrapped Credit's SCORE equals its CreditScore points, so the total is the same
// number whether a Credit is held as an NFT or wrapped to SCORE.
uint256 totalGained = SCORE_TOKEN.balanceOf(buyer) - scoreBefore;
uint256 total = creditPoints * POINT_SCALE + totalGained;
if (total < minTotalPoints) revert BelowMinTotal(total, minTotalPoints);
// (6) the pool-matching fee: 1% of the ACTUAL listing spend, paid from the ETH the buyer sent on top of the
// listings. Dust from the integer split goes to the Burner, so dev + builder + burner == fee exactly. No fee
// on a swap-only buy.
uint256 fee = listingSpend * FEE_BPS / BPS;
if (fee != 0) {
uint256 devShare = fee * DEV_BPS / BPS;
uint256 builderShare = fee * BUILDER_BPS / BPS;
uint256 burnerShare = fee - devShare - builderShare;
_pay(FEE_DEV, devShare);
_pay(FEE_BUILDER, builderShare);
_pay(FEE_BURNER, burnerShare);
}
// (7) refund last. Sweeping the whole balance keeps nothing here between transactions.
uint256 refund = address(this).balance;
if (refund != 0) {
(bool ok,) = buyer.call{value: refund}("");
if (!ok) revert RefundFailed();
}
emit Bought(buyer, heldToBuyer, creditPoints, wrapped, poolScore, totalGained, fee, refund);
}
/// Send `amount` wei to a fixed fee sink with empty calldata, reverting the whole buy if it is not accepted.
/// Only ever called with the three hardcoded fee addresses, so this is not an arbitrary-transfer surface.
function _pay(address to, uint256 amount) private {
(bool ok,) = to.call{value: amount}("");
if (!ok) revert FeeTransferFailed();
}
/// True if `who` owns `id` now. A Credit that was burned or never minted makes `ownerOf` revert; a static
/// call lets that read as "not owned" instead of taking the whole buy down with it.
function _ownerIs(uint256 id, address who) private view returns (bool) {
(bool ok, bytes memory ret) =
address(CREDITS).staticcall(abi.encodeWithSelector(ICredits.ownerOf.selector, id));
return ok && ret.length == 32 && address(uint160(uint256(bytes32(ret)))) == who;
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1000000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/",
"v4-core/=lib/v4-core/",
"@uniswap/v4-core/=lib/v4-core/",
"v4-periphery/=lib/v4-periphery/",
"permit2/=lib/v4-periphery/lib/permit2/",
"@openzeppelin/contracts/=lib/v4-periphery/lib/openzeppelin-contracts/contracts/",
"solmate/=lib/v4-core/lib/solmate/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.