-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlibrary-libere.sol
More file actions
405 lines (343 loc) · 15.6 KB
/
library-libere.sol
File metadata and controls
405 lines (343 loc) · 15.6 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "./Libere1155Core.sol";
/* ---------- Minimal ERC-5006 interface ---------- */
interface IERC5006 is IERC165 {
event CreateUserRecord(
uint256 indexed recordId,
address indexed owner,
address indexed user,
uint256 tokenId,
uint64 amount,
uint64 expiry
);
event DeleteUserRecord(uint256 indexed recordId);
function createUserRecord(address owner, address user, uint256 tokenId, uint64 amount, uint64 expiry) external returns (uint256 recordId);
function deleteUserRecord(uint256 recordId) external;
function usableBalanceOf(address user, uint256 tokenId) external view returns (uint256);
function frozenBalanceOf(address owner, uint256 tokenId) external view returns (uint256);
function userRecordOf(uint256 recordId) external view returns (uint256 tokenId, address owner, address user, uint64 amount, uint64 expiry);
}
/* ---------- EAS (RESMI: struct-based ABI) ---------- */
interface IEAS {
struct AttestationRequestData {
address recipient;
uint64 expirationTime;
bool revocable;
bytes32 refUID;
bytes data;
uint256 value;
}
struct AttestationRequest {
bytes32 schema;
AttestationRequestData data;
}
function attest(AttestationRequest calldata request) external payable returns (bytes32);
}
contract LibraryPool is IERC5006, IERC1155Receiver, ERC165, Ownable, ReentrancyGuard, EIP712 {
using ECDSA for bytes32;
/* ---------------- Events ---------------- */
event RentalPeriodSet(uint256 indexed tokenId, uint64 duration);
event Swept(uint256 indexed tokenId, uint256 removed, uint256 remainingActive);
event PermitRequiredSet(bool required);
event PermitSignerSet(address indexed signer);
event EASSet(address indexed eas, bytes32 indexed schemaId);
event EASAttested(bytes32 uid);
event EASAttestSkipped();
event EASAttestFailed(bytes reason); // encode minimal reason text
/* ---------------- External refs ---------------- */
Libere1155Core public immutable core;
/* ---------------- ERC-5006 storage ---------------- */
struct UserRecord {
uint256 tokenId;
address owner; // pool (owner of this contract)
address user;
uint64 amount; // 1
uint64 expiry; // unix seconds
bool active;
}
uint256 public nextRecordId = 1;
mapping(uint256 => UserRecord) private records;
mapping(address => mapping(uint256 => uint256)) private activeRecordOf; // user => tokenId => recordId
mapping(uint256 => uint256[]) private recordListByToken; // tokenId => record list
mapping(uint256 => uint256) private sweepCursor; // tokenId => cursor
/* ---------------- Borrow config ---------------- */
mapping(uint256 => uint64) public rentalPeriod; // default 3 days
uint256 public constant AUTO_SWEEP_QUOTA = 8;
/* ---------------- Allowlist (EIP-712) ---------------- */
address public permitSigner;
bool public permitRequired; // if true, permit (allowlist) required
mapping(address => uint256) public nonces;
/* ---------------- EAS wiring ---------------- */
IEAS public eas;
bytes32 public easSchemaId;
bool public easRevocable; // toggle agar cocok dengan properti schema (default false)
bool public easStrict; // jika true: revert bila EAS gagal; jika false: lanjut & emit EASAttestFailed
bytes32 public lastEASUid; // UID terakhir untuk verifikasi cepat
// ===== Constructor / EIP-712 domain =====
constructor(address admin, Libere1155Core core_)
Ownable(admin)
EIP712("LibereLibraryPool", "1")
{
core = core_;
easRevocable = false; // skema disarankan non-revocable
easStrict = false; // default: UX tidak putus jika EAS gagal
}
/* ---------------- Admin ---------------- */
function setPermitSigner(address signer) external onlyOwner {
permitSigner = signer;
emit PermitSignerSet(signer);
}
function setPermitRequired(bool required) external onlyOwner {
permitRequired = required;
emit PermitRequiredSet(required);
}
function setRentalPeriod(uint256 tokenId, uint64 seconds_) external onlyOwner {
rentalPeriod[tokenId] = seconds_;
emit RentalPeriodSet(tokenId, seconds_);
}
function setEAS(IEAS eas_, bytes32 schemaId_) external onlyOwner {
eas = eas_;
easSchemaId = schemaId_;
emit EASSet(address(eas_), schemaId_);
}
function setEASRevocable(bool v) external onlyOwner { easRevocable = v; }
function setEASStrict(bool v) external onlyOwner { easStrict = v; }
/* ---------------- EIP-712 Permit ---------------- */
bytes32 public constant BORROW_PERMIT_TYPEHASH =
keccak256("BorrowPermit(address user,address pool,uint256 tokenId,uint256 nonce,uint64 sigDeadline)");
function _verifyPermit(address user, uint256 tokenId, uint64 sigDeadline, bytes calldata sig) internal {
require(permitSigner != address(0), "permit signer not set");
require(block.timestamp <= sigDeadline, "permit expired");
bytes32 structHash = keccak256(abi.encode(
BORROW_PERMIT_TYPEHASH,
user,
address(this),
tokenId,
nonces[user],
sigDeadline
));
bytes32 digest = _hashTypedDataV4(structHash);
address recovered = ECDSA.recover(digest, sig);
require(recovered == permitSigner, "bad permit signature");
unchecked { nonces[user] += 1; }
}
/* ---------------- Helpers ---------------- */
function _now() internal view returns (uint64) { return uint64(block.timestamp); }
function _defaultPeriod(uint256 tokenId) internal view returns (uint64 p) { p = rentalPeriod[tokenId]; if (p==0) p = 3 days; }
/* ---------------- Stock views ---------------- */
function _frozenNow(uint256 tokenId) internal view returns (uint256 count) {
uint64 nowTs = _now();
uint256[] storage list = recordListByToken[tokenId];
for (uint256 i = 0; i < list.length; i++) {
UserRecord storage r = records[list[i]];
if (r.active && r.expiry > nowTs) count++;
}
}
/// @notice (available, frozenNow) real-time stocks
function previewAvailability(uint256 tokenId) external view returns (uint256 available, uint256 frozenNow) {
frozenNow = _frozenNow(tokenId);
uint256 stock = core.balanceOf(address(this), tokenId);
available = stock > frozenNow ? stock - frozenNow : 0;
}
/* ---------------- Borrow/Return ---------------- */
/// @notice Borrow tanpa permit (hanya jika permitRequired=false). Tetap 1:1 via 5006.
function borrowFromPool(uint256 tokenId) external nonReentrant returns (uint256 recordId) {
require(!permitRequired, "permit required");
recordId = _borrowAfterGate(tokenId, msg.sender);
}
/// @notice Borrow dengan EIP-712 permit (SSO allowlist). Wajib jika permitRequired=true.
function borrowFromPoolWithPermit(uint256 tokenId, uint64 sigDeadline, bytes calldata sig)
external nonReentrant returns (uint256 recordId)
{
if (permitRequired) {
_verifyPermit(msg.sender, tokenId, sigDeadline, sig);
} else if (permitSigner != address(0) && sig.length > 0) {
_verifyPermit(msg.sender, tokenId, sigDeadline, sig);
}
recordId = _borrowAfterGate(tokenId, msg.sender);
}
function _borrowAfterGate(uint256 tokenId, address user) internal returns (uint256 recordId) {
// 1) auto-sweep kecil
_sweepExpired(tokenId, AUTO_SWEEP_QUOTA);
// 2) seat tersedia?
uint256 frozen = _frozenNow(tokenId);
uint256 stock = core.balanceOf(address(this), tokenId);
require(stock > frozen, "no stock");
// 3) satu pinjaman aktif per user/judul
uint256 existing = activeRecordOf[user][tokenId];
if (existing != 0) {
(, , , , uint64 exp) = userRecordOf(existing);
require(exp <= _now() || !records[existing].active, "already borrowed");
}
// 4) buat record (amount=1)
uint64 expiry = _now() + _defaultPeriod(tokenId);
uint256 rid = createUserRecord(address(this), user, tokenId, 1, expiry);
// 5) EAS (opsional) — attestation LoanIssued
_attestLoan(user, tokenId, rid, expiry);
return rid;
}
function _attestLoan(address user, uint256 tokenId, uint256 rid, uint64 expiry) internal {
if (address(eas) == address(0) || easSchemaId == bytes32(0)) {
emit EASAttestSkipped();
return;
}
// PASTIKAN skema di EAS persis:
// "address pool,address user,uint256 tokenId,uint256 recordId,uint64 expiry,uint64 issuedAt"
bytes memory payload = abi.encode(
address(this), // pool
user, // user
tokenId,
rid,
expiry,
uint64(block.timestamp) // issuedAt
);
IEAS.AttestationRequest memory req = IEAS.AttestationRequest({
schema: easSchemaId,
data: IEAS.AttestationRequestData({
recipient: address(0), // atau user jika ingin
expirationTime: 0, // 0 = tidak expire di level attestation
revocable: easRevocable, // harus cocok dengan properti schema
refUID: bytes32(0),
data: payload,
value: 0
})
});
if (easStrict) {
// mode strict: biar error EAS kelihatan jelas (akan revert)
bytes32 uid = eas.attest(req);
lastEASUid = uid;
emit EASAttested(uid);
} else {
// mode non-strict: UX tidak putus kalau EAS gagal
try eas.attest(req) returns (bytes32 uid) {
lastEASUid = uid;
emit EASAttested(uid);
} catch {
emit EASAttestFailed("attest revert");
}
}
}
function returnBorrow(uint256 recordId) external nonReentrant {
(, , address user, , ) = userRecordOf(recordId);
require(msg.sender == user, "not borrower");
deleteUserRecord(recordId);
}
function returnMyBorrow(uint256 tokenId) external nonReentrant {
uint256 rid = activeRecordOf[msg.sender][tokenId];
require(rid != 0, "no active");
deleteUserRecord(rid);
}
/* ---------------- ERC-5006 core ---------------- */
function createUserRecord(
address owner, address user, uint256 tokenId, uint64 amount, uint64 expiry
) public override returns (uint256 recordId) {
require(owner == address(this), "owner must be pool");
require(user != address(0), "bad user");
require(amount == 1, "amount=1");
require(expiry > _now(), "expiry past");
uint256 frozen = _frozenNow(tokenId);
uint256 stock = core.balanceOf(address(this), tokenId);
require(stock > frozen, "no stock");
uint256 existing = activeRecordOf[user][tokenId];
if (existing != 0) {
(, , , , uint64 exp) = userRecordOf(existing);
require(exp <= _now() || !records[existing].active, "already borrowed");
}
recordId = nextRecordId++;
records[recordId] = UserRecord({
tokenId: tokenId,
owner: owner,
user: user,
amount: 1,
expiry: expiry,
active: true
});
activeRecordOf[user][tokenId] = recordId;
recordListByToken[tokenId].push(recordId);
emit CreateUserRecord(recordId, owner, user, tokenId, 1, expiry);
}
function deleteUserRecord(uint256 recordId) public override {
UserRecord storage r = records[recordId];
require(r.active, "not active");
bool isUser = (msg.sender == r.user);
bool isPool = (msg.sender == r.owner);
bool isAdmin = (msg.sender == owner());
bool expired = (r.expiry <= _now());
require(isUser || isPool || isAdmin || expired, "no permission");
r.active = false;
if (activeRecordOf[r.user][r.tokenId] == recordId) {
activeRecordOf[r.user][r.tokenId] = 0;
}
emit DeleteUserRecord(recordId);
}
function usableBalanceOf(address user, uint256 tokenId) public view override returns (uint256) {
uint256 rid = activeRecordOf[user][tokenId];
if (rid == 0) return 0;
UserRecord storage r = records[rid];
if (!r.active || r.expiry <= _now()) return 0;
return 1;
}
function frozenBalanceOf(address owner, uint256 tokenId) public view override returns (uint256) {
if (owner != address(this)) return 0;
return _frozenNow(tokenId);
}
function userRecordOf(uint256 recordId)
public view override
returns (uint256 tokenId, address owner, address user, uint64 amount, uint64 expiry)
{
UserRecord storage r = records[recordId];
return (r.tokenId, r.owner, r.user, r.amount, r.expiry);
}
/* ---------------- Sweep ---------------- */
function sweepExpiredRecords(uint256 tokenId, uint256 maxOps) external returns (uint256 removed) {
removed = _sweepExpired(tokenId, maxOps);
emit Swept(tokenId, removed, _frozenNow(tokenId));
}
function sweepExpiredGlobal(uint256[] calldata ids, uint256 maxPerToken) external returns (uint256 totalRemoved) {
for (uint256 i = 0; i < ids.length; i++) {
uint256 removed = _sweepExpired(ids[i], maxPerToken);
totalRemoved += removed;
emit Swept(ids[i], removed, _frozenNow(ids[i]));
}
}
function _sweepExpired(uint256 tokenId, uint256 maxOps) internal returns (uint256 removed) {
uint256[] storage list = recordListByToken[tokenId];
uint256 cursor = sweepCursor[tokenId];
uint256 n = list.length;
uint64 nowTs = _now();
while (cursor < n && removed < maxOps) {
uint256 rid = list[cursor];
UserRecord storage r = records[rid];
if (r.active && r.expiry <= nowTs) {
r.active = false;
if (activeRecordOf[r.user][r.tokenId] == rid) {
activeRecordOf[r.user][r.tokenId] = 0;
}
emit DeleteUserRecord(rid);
removed++;
}
cursor++;
}
if (cursor >= n) cursor = 0;
sweepCursor[tokenId] = cursor;
}
/* ---------------- IERC165 / IERC1155Receiver ---------------- */
function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) {
// ERC-5006 interface id (referensi)
return interfaceId == 0xc26d96cc || super.supportsInterface(interfaceId);
}
function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
external pure override returns (bytes4)
{ return this.onERC1155BatchReceived.selector; }
}