-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSeller.sol
285 lines (247 loc) · 9.86 KB
/
Seller.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0 <0.9.0;
import "@divergencetech/ethier/contracts/utils/Monotonic.sol";
import "@divergencetech/ethier/contracts//utils/OwnerPausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
@notice An abstract contract providing the _purchase() function to:
- Enforce per-wallet / per-transaction limits
- Calculate required cost, forwarding to a beneficiary, and refunding extra
*/
abstract contract Seller is OwnerPausable, ReentrancyGuard {
using Address for address payable;
using Monotonic for Monotonic.Increaser;
using Strings for uint256;
/**
@dev Note that the address limits are vulnerable to wallet farming.
@param maxPerAddress Unlimited if zero.
@param maxPerTex Unlimited if zero.
@param freeQuota Maximum number that can be purchased free of charge by
the contract owner.
@param reserveFreeQuota Whether to excplitly reserve the freeQuota amount
and not let it be eroded by regular purchases.
@param lockFreeQuota If true, calls to setSellerConfig() will ignore changes
to freeQuota. Can be locked after initial setting, but not unlocked. This
allows a contract owner to commit to a maximum number of reserved items.
@param lockTotalInventory Similar to lockFreeQuota but applied to
totalInventory.
*/
struct SellerConfig {
uint256 totalInventory;
uint256 maxPerAddress;
uint256 maxPerTx;
uint248 freeQuota;
bool reserveFreeQuota;
bool lockFreeQuota;
bool lockTotalInventory;
}
constructor(SellerConfig memory config, address payable _beneficiary) {
setSellerConfig(config);
setBeneficiary(_beneficiary);
}
/// @notice Configuration of purchase limits.
SellerConfig public sellerConfig;
/// @notice Sets the seller config.
function setSellerConfig(SellerConfig memory config) public onlyOwner {
require(
config.totalInventory >= config.freeQuota,
"Seller: excessive free quota"
);
require(
config.totalInventory >= _totalSold.current(),
"Seller: inventory < already sold"
);
require(
config.freeQuota >= purchasedFreeOfCharge.current(),
"Seller: free quota < already used"
);
// Overriding the in-memory fields before copying the whole struct, as
// against writing individual fields, gives a greater guarantee of
// correctness as the code is simpler to read.
if (sellerConfig.lockTotalInventory) {
config.lockTotalInventory = true;
config.totalInventory = sellerConfig.totalInventory;
}
if (sellerConfig.lockFreeQuota) {
config.lockFreeQuota = true;
config.freeQuota = sellerConfig.freeQuota;
}
sellerConfig = config;
}
/// @notice Recipient of revenues.
address payable public beneficiary;
/// @notice Sets the recipient of revenues.
function setBeneficiary(address payable _beneficiary) public onlyOwner {
beneficiary = _beneficiary;
}
/**
@dev Must return the current cost of a batch of items. This may be constant
or, for example, decreasing for a Dutch auction or increasing for a bonding
curve.
@param n The number of items being purchased.
*/
function cost(uint256 n) public view virtual returns (uint256);
/**
@dev Called by both _purchase() and purchaseFreeOfCharge() after all limits
have been put in place; must perform all contract-specific sale logic, e.g.
ERC721 minting. When _handlePurchase() is called, the value returned by
Seller.totalSold() will be the pre-purchase amount.
@param to The recipient of the item(s).
@param n The number of items allowed to be purchased, which MAY be less than
to the number passed to _purchase() but SHALL be greater than zero.
@param freeOfCharge Indicates that the call originated from
purchaseFreeOfCharge() and not _purchase().
*/
function _handlePurchase(
address to,
uint256 n,
bool freeOfCharge
) internal virtual;
Monotonic.Increaser private _totalSold;
/// @notice Returns the total number of items sold by this contract.
function totalSold() public view returns (uint256) {
return _totalSold.current();
}
/**
@dev This isn't public as it may be skewed due to differences in msg.sender
and tx.origin, which it treats in the same way such that
sum(_bought)>=totalSold().
*/
mapping(address => uint256) private _bought;
/**
@notice Returns min(n, max(extra items addr can purchase)) and reverts if 0.
@param zeroMsg The message with which to revert on 0 extra.
*/
function _capExtra(
uint256 n,
address addr,
string memory zeroMsg
) internal view returns (uint256) {
uint256 extra = sellerConfig.maxPerAddress - _bought[addr];
if (extra == 0) {
revert(string(abi.encodePacked("Seller: ", zeroMsg)));
}
return Math.min(n, extra);
}
/// @notice Emitted when a buyer is refunded.
event Refund(address indexed buyer, uint256 amount);
/// @notice Emitted on all purchases of non-zero amount.
event Revenue(
address indexed beneficiary,
uint256 numPurchased,
uint256 amount
);
Monotonic.Increaser private purchasedFreeOfCharge;
/**
@notice Allows the contract owner to purchase without payment, within the
quota enforced by the SellerConfig.
*/
function purchaseFreeOfCharge(address to, uint256 n)
public
onlyOwner
whenNotPaused
{
uint256 freeQuota = sellerConfig.freeQuota;
n = Math.min(n, freeQuota - purchasedFreeOfCharge.current());
require(n > 0, "Seller: Free quota exceeded");
uint256 totalInventory = sellerConfig.totalInventory;
n = Math.min(n, totalInventory - _totalSold.current());
require(n > 0, "Seller: Sold out");
_handlePurchase(to, n, true);
_totalSold.add(n);
purchasedFreeOfCharge.add(n);
assert(_totalSold.current() <= totalInventory);
assert(purchasedFreeOfCharge.current() <= freeQuota);
}
/**
@notice Enforces all purchase limits (counts and costs) before calling
_handlePurchase(), after which the received funds are disbursed to the
beneficiary, less any required refunds.
@param to The final recipient of the item(s).
@param requested The number of items requested for purchase, which MAY be
reduced when passed to _handlePurchase().
*/
function _purchase(address to, uint256 requested)
internal
nonReentrant
whenNotPaused
{
SellerConfig memory config = sellerConfig;
uint256 n = config.maxPerTx == 0
? requested
: Math.min(requested, config.maxPerTx);
uint256 maxAvailable = config.reserveFreeQuota
? config.totalInventory - config.freeQuota
: config.totalInventory;
n = Math.min(n, maxAvailable - _totalSold.current());
require(n > 0, "Seller: Sold out");
if (config.maxPerAddress > 0) {
bool alsoLimitSender = _msgSender() != to;
bool alsoLimitOrigin = tx.origin != _msgSender() && tx.origin != to;
n = _capExtra(n, to, "Buyer limit");
if (alsoLimitSender) {
n = _capExtra(n, _msgSender(), "Sender limit");
}
if (alsoLimitOrigin) {
n = _capExtra(n, tx.origin, "Origin limit");
}
_bought[to] += n;
if (alsoLimitSender) {
_bought[_msgSender()] += n;
}
if (alsoLimitOrigin) {
_bought[tx.origin] += n;
}
}
uint256 _cost = cost(n);
if (msg.value < _cost) {
revert(
string(
abi.encodePacked(
"Seller: Costs ",
(_cost / 1e9).toString(),
" GWei"
)
)
);
}
/**
* ##### EFFECTS
*/
_handlePurchase(to, n, false);
_totalSold.add(n);
assert(_totalSold.current() <= config.totalInventory);
/**
* ##### INTERACTIONS
*/
// Ideally we'd be using a PullPayment here, but the user experience is
// poor when there's a variable cost or the number of items purchased
// has been capped. We've addressed reentrancy with both a nonReentrant
// modifier and the checks, effects, interactions pattern.
if (_cost > 0) {
beneficiary.sendValue(_cost);
emit Revenue(beneficiary, n, _cost);
}
if (msg.value > _cost) {
address payable reimburse = payable(_msgSender());
uint256 refund = msg.value - _cost;
// Using Address.sendValue() here would mask the revertMsg upon
// reentrancy, but we want to expose it to allow for more precise
// testing. This otherwise uses the exact same pattern as
// Address.sendValue().
(bool success, bytes memory returnData) = reimburse.call{
value: refund
}("");
// Although `returnData` will have a spurious prefix, all we really
// care about is that it contains the ReentrancyGuard reversion
// message so we can check in the tests.
require(success, string(returnData));
emit Refund(reimburse, refund);
}
}
}