Verified contractExactMIT
LATDistributor
Address0x1925ad57d43eecc9e5273e23aad2d0e80130d23e
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- No
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,465,147
- Creation transaction
- 0x2d61a68414…e3b1def392
10 files
- LAT1.solmain32.55 KB
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.81 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4.77 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
LAT1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/// @title LAT Distributor
/// @notice Nhận toàn bộ cung LAT khi khởi tạo, chia cho nhiều nhóm (team, quỹ, cộng đồng...)
/// theo lịch vesting tuyến tính (linear vesting) có cliff. Không ai — kể cả deployer —
/// có thể rút sớm hơn lịch hoặc thay đổi SỐ LƯỢNG/THỜI GIAN của lịch sau khi đã thiết lập.
///
/// LỊCH SỬ HARDENING:
/// 4. Chặn gửi excess/rescue về chính địa chỉ contract.
/// 5. Khi tạo schedule, bắt buộc cliff (nếu có) vẫn CHƯA trôi qua tại thời điểm tạo.
/// 6. Sửa lỗ hổng DoS do giới hạn gas block: tách flow thành 2 pha —
/// Pha 1: addBeneficiaries(...) — deployer gọi NHIỀU LẦN theo batch nhỏ tùy ý,
/// chỉ ghi schedule, KHÔNG rút token, KHÔNG thể sửa/xoá sau khi ghi.
/// Pha 2: finalize() — deployer gọi ĐÚNG MỘT LẦN, rút đúng tổng totalAllocated
/// token trong một transaction riêng (nhẹ gas), rồi khoá vĩnh viễn mọi
/// thay đổi lịch (addBeneficiaries sẽ revert sau khi finalized).
/// 7. Sửa lỗi biên (off-by-one) cho phép tạo lịch "vest sẵn ngay từ lúc tạo":
/// điều kiện cũ dùng >= nên nếu start+duration (hoặc start+cliff) trùng đúng
/// block.timestamp lúc tạo, vestedAmount() trả về toàn bộ ngay lập tức, phá vỡ
/// bất biến "không rút sớm hơn lịch". Đổi sang > để cliff/duration luôn còn
/// hiệu lực thực sự tại thời điểm tạo lịch.
/// 8. Thêm expectedBeneficiaryCount: số lượng beneficiary dự kiến được chốt
/// ĐÚNG MỘT LẦN qua setExpectedBeneficiaryCount() trước khi add batch đầu tiên.
/// finalize() giờ bắt buộc beneficiaries.length == expectedBeneficiaryCount,
/// để tránh deployer lỡ tay finalize khi mới add được một phần danh sách —
/// một sai sót không thể khắc phục vì finalize là one-way.
/// 9. FIX — modifier onlyDeployer thiếu placeholder `_;` (bản cũ là
/// `require(...); ;` — dấu chấm phẩy rỗng, không phải placeholder), khiến
/// mọi hàm dùng modifier này không compile được / không bao giờ chạy thân hàm.
/// 10. FIX — constructor khai báo tham số tên `token` (trùng với state variable
/// `token` gây shadowing) nhưng lại dùng biến `token_` chưa từng khai báo.
/// Đổi tên tham số thành `token_` cho khớp và không đụng state variable.
/// 11. FIX — check cliff trong addBeneficiaries (kế thừa từ fix #7) yêu cầu
/// `start + cliff > block.timestamp` một cách TUYỆT ĐỐI, kể cả khi cliff = 0.
/// Hệ quả: không thể tạo lịch bắt đầu ngay lập tức (start = block.timestamp)
/// dù không hề vi phạm bất biến "không vest tức thì" — vì bất biến đó đã được
/// bảo đảm đầy đủ bởi check duration (start + duration > block.timestamp,
/// kết hợp cliff <= duration). Check cliff riêng là dư thừa và sai, đã bị xoá;
/// chỉ còn giữ lại check duration.
/// 12. BỔ SUNG (không đổi bất biến) — thêm các view function tiện cho audit/dashboard
/// off-chain trước và sau finalize: getSchedule() trả về schedule + vested/
/// releasable hiện tại trong một lần gọi; getAllBeneficiaries() trả toàn bộ
/// danh sách (an toàn vì MAX_BENEFICIARIES = 200, không có rủi ro out-of-gas
/// khi đọc qua eth_call — các hàm này KHÔNG ghi state); getAllSchedulesSummary()
/// trả tổng hợp nhanh (đã add bao nhiêu, còn thiếu bao nhiêu so với
/// expectedBeneficiaryCount) để deployer tự kiểm tra trước khi gọi finalize(),
/// giảm rủi ro finalize nhầm hoặc set sai expectedBeneficiaryCount.
/// Đây thuần tuý là các hàm đọc (view), không ảnh hưởng gì tới tính bất biến
/// "không ai sửa được lịch sau khi tạo".
/// 13. V1.1 — BỔ SUNG (không đổi bất biến) — thêm releaseFor() và releaseBatch():
/// cho phép BẤT KỲ địa chỉ nào (vd. một keeper bot / dịch vụ automation) trả gas
/// để kích hoạt release hộ một hoặc nhiều beneficiary. Token của mỗi lần release
/// VẪN LUÔN LUÔN chỉ được chuyển đến đúng địa chỉ beneficiary đã ghi cứng trong
/// schedule tại thời điểm addBeneficiaries — người gọi releaseFor/releaseBatch
/// không có cách nào redirect token đi nơi khác, không cần cấp quyền gì thêm.
/// releaseBatch xử lý nhiều địa chỉ trong một transaction và CHỦ ĐỘNG BỎ QUA
/// (không revert) các beneficiary có releasable = 0 tại thời điểm gọi, để một
/// địa chỉ "chưa tới lượt" không làm fail toàn bộ batch. release()/releaseFor()/
/// releaseBatch() giờ dùng chung logic nội bộ _release() để tránh lặp code.
/// Thêm isBeneficiary() làm view tiện tra cứu nhanh cho dashboard off-chain.
/// 14. V1.2 — BỔ SUNG (không đổi SỐ LƯỢNG/LỊCH TRÌNH, chỉ đổi ĐỊA CHỈ NHẬN) —
/// thêm cơ chế beneficiary tự chuyển quyền nhận token sang địa chỉ khác, theo mô
/// hình 2 bước propose/accept (giống Ownable2Step) để tránh gõ nhầm địa chỉ và
/// mất vĩnh viễn quyền vesting:
/// - proposeBeneficiaryTransfer(newAddr): CHỈ beneficiary hiện tại được gọi,
/// đề xuất địa chỉ mới. Chưa có gì thay đổi ở bước này.
/// - acceptBeneficiaryTransfer(oldAddr): CHỈ đúng địa chỉ mới (msg.sender ==
/// newAddr đã được đề xuất) mới gọi được, để tự xác nhận mình kiểm soát được
/// private key của địa chỉ mới trước khi chuyển. Toàn bộ schedule (totalAmount,
/// released, start, cliff, duration) được dời nguyên vẹn sang địa chỉ mới;
/// địa chỉ cũ bị xoá hoàn toàn khỏi schedules/beneficiaries.
/// - cancelBeneficiaryTransfer(): beneficiary hiện tại huỷ đề xuất đang chờ.
/// Deployer KHÔNG có vai trò gì trong toàn bộ luồng này — không thể khởi tạo,
/// không thể chặn, không thể tự ý chuyển hộ. Cơ chế hoạt động cả trước và sau
/// finalize() vì nó không đụng tới totalAllocated hay dòng tiền token, chỉ đổi
/// "ai là người nhận" của một entitlement đã tồn tại.
/// 15. V1.2 — BỔ SUNG (tiện lợi, không đổi bất biến) — thêm finalizeWithPermit():
/// cho phép deployer finalize trong ĐÚNG MỘT transaction bằng chữ ký EIP-2612
/// permit, thay vì phải gọi approve() riêng ở một transaction trước đó. Dùng
/// chung logic _finalize() nội bộ với finalize() cũ. Chỉ dùng được nếu token
/// triển khai IERC20Permit; nếu không, deployer vẫn dùng finalize() như cũ.
///
/// LƯU Ý VẬN HÀNH (không phải logic hợp đồng, nhưng quan trọng khi triển khai thực tế):
/// - `deployer` là immutable và không có cơ chế transfer quyền. Khuyến nghị MẠNH:
/// deploy với `deployer` = địa chỉ ví multisig (vd. Gnosis Safe), KHÔNG dùng
/// EOA đơn — vì mất key của EOA đồng nghĩa các hàm quản trị
/// (setExpectedBeneficiaryCount, addBeneficiaries, finalize, sweepExcessToken,
/// rescueToken) sẽ vĩnh viễn không gọi được.
/// - Trước khi gọi finalize(), phải approve() đủ đúng totalAllocated token cho
/// contract này (hoặc dùng finalizeWithPermit() nếu token hỗ trợ). Nên dùng
/// getAllSchedulesSummary()/readyToFinalize() để double-check off-chain.
/// - setExpectedBeneficiaryCount và finalize đều là hành động một chiều (one-way),
/// không có đường sửa nếu gọi sai. Luôn dry-run trên testnet trước.
/// - Hợp đồng cố tình KHÔNG có cơ chế revoke/pause — vesting là bất biến và
/// không thể thu hồi theo đúng thiết kế ban đầu. Nếu nghiệp vụ về sau cần khả
/// năng thu hồi cho nhân sự rời sớm, đó là một trade-off phải cân nhắc kỹ vì
/// nó phá vỡ chính bất biến mà hợp đồng này được thiết kế để bảo vệ — nên xử
/// lý bằng một hợp đồng/phiên bản khác, không nên chắp vá vào đây.
/// - release()/releaseFor()/releaseBatch() không có cách nào chuyển token đến
/// địa chỉ khác ngoài beneficiary gốc — kể cả khi bên thứ ba trả gas, an toàn
/// để dùng cho automation không cần cấp quyền on-chain gì thêm.
/// - Cơ chế transfer địa chỉ (mục 14) đổi "ai nhận", KHÔNG đổi "nhận bao nhiêu,
/// khi nào" — đây là điểm khác biệt quan trọng so với revoke. Nếu beneficiary
/// tự ý propose nhầm địa chỉ, họ có thể cancelBeneficiaryTransfer() bất cứ lúc
/// nào TRƯỚC khi bên nhận accept; sau khi accept thì không thể đảo ngược, vì
/// vậy off-chain nên luôn xác nhận kỹ địa chỉ mới trước khi accept.
contract LATDistributor is ReentrancyGuard {
using SafeERC20 for IERC20;
struct VestingSchedule {
address beneficiary;
uint256 totalAmount;
uint256 released;
uint64 start; // thời điểm bắt đầu tính vesting (unix timestamp)
uint64 cliff; // khoảng thời gian khoá, tính từ start (giây)
uint64 duration; // tổng thời gian vesting, tính từ start (giây)
}
/// @notice Dùng cho các view function tổng hợp — không dùng để lưu state.
struct ScheduleView {
address beneficiary;
uint256 totalAmount;
uint256 released;
uint64 start;
uint64 cliff;
uint64 duration;
uint256 vested;
uint256 releasable;
}
IERC20 public immutable token;
address public immutable deployer;
// finalized = true nghĩa là: không thể thêm/sửa/xoá beneficiary nữa, và token
// (đúng bằng totalAllocated) đã được kéo vào contract đúng một lần duy nhất.
bool public finalized;
// Số lượng beneficiary dự kiến, chốt một lần trước khi add batch đầu tiên.
// finalize() bắt buộc phải add đủ đúng số này mới cho phép khoá — tránh
// finalize nhầm khi danh sách chưa hoàn tất.
uint256 public expectedBeneficiaryCount;
bool public expectedCountSet;
// Tổng số beneficiary được phép trên TOÀN BỘ vòng đời hợp đồng (cộng dồn qua nhiều
// batch addBeneficiaries), để chặn tình huống danh sách phình quá lớn không kiểm soát.
uint256 public constant MAX_BENEFICIARIES = 200;
// Số beneficiary tối đa được xử lý trong MỘT lần gọi addBeneficiaries, để đảm bảo
// mỗi transaction luôn nằm an toàn dưới trần gas của một block.
uint256 public constant MAX_BENEFICIARIES_PER_BATCH = 50;
// beneficiary => lịch vesting
mapping(address => VestingSchedule) public schedules;
address[] public beneficiaries;
// V1.2 — beneficiary hiện tại => địa chỉ mới đang được đề xuất chuyển tới.
// address(0) nghĩa là không có đề xuất nào đang chờ.
mapping(address => address) public pendingBeneficiaryTransfer;
// Tổng số token đã cam kết cho tất cả schedule (cộng dồn qua các batch), và tổng đã release.
uint256 public totalAllocated;
uint256 public totalReleased;
event ExpectedBeneficiaryCountSet(uint256 count);
event ScheduleCreated(address indexed beneficiary, uint256 amount, uint64 start, uint64 cliff, uint64 duration);
event Finalized(uint256 totalAllocated, uint256 beneficiaryCount);
event TokensReleased(address indexed beneficiary, uint256 amount);
event TokenRescued(address indexed token, address indexed to, uint256 amount);
event ExcessSwept(address indexed to, uint256 amount);
event BeneficiaryTransferProposed(address indexed from, address indexed to);
event BeneficiaryTransferCancelled(address indexed from, address indexed to);
event BeneficiaryTransferAccepted(address indexed from, address indexed to, uint256 totalAmount, uint256 released);
modifier onlyDeployer() {
require(msg.sender == deployer, "Chi deployer duoc phep");
_;
}
constructor(address token_) {
require(token_ != address(0), "Token khong duoc la dia chi zero");
token = IERC20(token_);
deployer = msg.sender;
}
/// @notice Chốt số lượng beneficiary dự kiến trước khi bắt đầu add. Chỉ gọi được
/// đúng một lần, trước finalize(). Dùng để finalize() có thể xác nhận danh sách
/// đã được add đầy đủ, tránh khoá nhầm giữa chừng.
function setExpectedBeneficiaryCount(uint256 count) external onlyDeployer {
require(!expectedCountSet, "Da chot so luong roi");
require(!finalized, "Da finalize roi");
require(count > 0 && count <= MAX_BENEFICIARIES, "So luong khong hop le");
expectedBeneficiaryCount = count;
expectedCountSet = true;
emit ExpectedBeneficiaryCountSet(count);
}
/// @notice PHA 1 — Thêm một batch beneficiary vào danh sách vesting. Có thể gọi nhiều
/// lần (nhiều transaction) trước khi finalize(), để tránh vượt trần gas của một block
/// khi tổng số beneficiary lớn. KHÔNG kéo token vào contract ở bước này — token chỉ
/// được kéo đúng một lần trong finalize(), nên schedule ở đây vẫn hoàn toàn bất biến
/// một khi đã ghi (không có hàm sửa/xoá).
function addBeneficiaries(
address[] calldata _beneficiaries,
uint256[] calldata _amounts,
uint64[] calldata _starts,
uint64[] calldata _cliffs,
uint64[] calldata _durations
) external onlyDeployer nonReentrant {
require(expectedCountSet, "Chua chot so luong beneficiary du kien");
require(!finalized, "Da finalize roi, khong the them nua");
require(
_beneficiaries.length == _amounts.length &&
_amounts.length == _starts.length &&
_starts.length == _cliffs.length &&
_cliffs.length == _durations.length,
"Mang khong khop do dai"
);
require(_beneficiaries.length > 0, "Danh sach rong");
require(_beneficiaries.length <= MAX_BENEFICIARIES_PER_BATCH, "Qua nhieu beneficiary trong 1 lan goi");
require(
beneficiaries.length + _beneficiaries.length <= MAX_BENEFICIARIES,
"Vuot qua tong so beneficiary cho phep"
);
require(
beneficiaries.length + _beneficiaries.length <= expectedBeneficiaryCount,
"Vuot qua so luong beneficiary du kien"
);
uint256 sumAdded;
for (uint256 i = 0; i < _beneficiaries.length; i++) {
address b = _beneficiaries[i];
uint256 amt = _amounts[i];
require(b != address(0), "Beneficiary khong duoc la dia chi zero");
require(b != address(this), "Beneficiary khong duoc la chinh contract");
require(amt > 0, "Amount phai > 0");
require(_durations[i] > 0, "Duration phai > 0");
require(_cliffs[i] <= _durations[i], "Cliff khong duoc lon hon duration");
require(schedules[b].totalAmount == 0, "Beneficiary bi trung lap");
// Chỉ cần đảm bảo lịch CHƯA vest hết ngay lúc tạo. Vì cliff <= duration
// luôn đúng, check duration này là đủ để bảo vệ bất biến đó; không cần
// (và không nên) bắt cliff cũng phải nằm trong tương lai một cách tuyệt
// đối, vì điều đó chặn nhầm cả các lịch cliff = 0 bắt đầu ngay lập tức.
require(
uint256(_starts[i]) + uint256(_durations[i]) > block.timestamp,
"Lich vesting da ket thuc truoc khi duoc tao"
);
schedules[b] = VestingSchedule({
beneficiary: b,
totalAmount: amt,
released: 0,
start: _starts[i],
cliff: _cliffs[i],
duration: _durations[i]
});
beneficiaries.push(b);
sumAdded += amt;
emit ScheduleCreated(b, amt, _starts[i], _cliffs[i], _durations[i]);
}
totalAllocated += sumAdded;
}
/// @notice Logic dùng chung cho finalize()/finalizeWithPermit(): khoá vĩnh viễn
/// danh sách schedule và kéo đúng totalAllocated token vào contract trong MỘT
/// lệnh transferFrom duy nhất (nhẹ gas, không phụ thuộc số lượng beneficiary).
function _finalize() internal {
require(!finalized, "Da finalize roi");
require(expectedCountSet, "Chua chot so luong beneficiary du kien");
require(beneficiaries.length == expectedBeneficiaryCount, "Chua add du so luong beneficiary du kien");
finalized = true;
uint256 balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), totalAllocated);
uint256 received = token.balanceOf(address(this)) - balanceBefore;
require(received == totalAllocated, "Token co phi/rebase khong duoc ho tro");
emit Finalized(totalAllocated, beneficiaries.length);
}
/// @notice PHA 2 — Khoá vĩnh viễn danh sách schedule và kéo đúng totalAllocated token
/// vào contract. Chỉ gọi được đúng một lần, và chỉ khi đã add đủ đúng
/// expectedBeneficiaryCount beneficiary. Yêu cầu deployer đã approve() đủ token
/// cho contract này ở một transaction trước đó.
function finalize() external onlyDeployer nonReentrant {
_finalize();
}
/// @notice V1.2 — Giống finalize(), nhưng gộp bước approve vào cùng transaction
/// bằng chữ ký EIP-2612 permit của deployer, thay vì cần một tx approve() riêng
/// trước đó. Chỉ dùng được nếu `token` triển khai IERC20Permit; nếu token không
/// hỗ trợ permit, lệnh permit() bên dưới sẽ tự revert và deployer nên dùng
/// finalize() thông thường thay thế.
function finalizeWithPermit(
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external onlyDeployer nonReentrant {
IERC20Permit(address(token)).permit(msg.sender, address(this), totalAllocated, deadline, v, r, s);
_finalize();
}
function vestedAmount(address beneficiary) public view returns (uint256) {
VestingSchedule memory s = schedules[beneficiary];
if (s.totalAmount == 0) return 0;
uint256 cliffTime = uint256(s.start) + uint256(s.cliff);
if (block.timestamp < cliffTime) {
return 0;
}
uint256 endTime = uint256(s.start) + uint256(s.duration);
if (block.timestamp >= endTime) {
return s.totalAmount;
}
return (s.totalAmount * (block.timestamp - s.start)) / s.duration;
}
function releasableAmount(address beneficiary) public view returns (uint256) {
return vestedAmount(beneficiary) - schedules[beneficiary].released;
}
/// @notice Logic release dùng chung cho release()/releaseFor()/releaseBatch().
/// KHÔNG kiểm tra `finalized` ở đây — các hàm external gọi nó phải tự kiểm tra
/// trước, để tránh lặp require không cần thiết trong vòng lặp của releaseBatch.
/// Trả về 0 (không revert) nếu chưa có gì để release, để releaseBatch có thể
/// bỏ qua một địa chỉ "chưa tới lượt" mà không làm fail cả batch.
function _release(address beneficiary) internal returns (uint256 amount) {
amount = releasableAmount(beneficiary);
if (amount == 0) {
return 0;
}
schedules[beneficiary].released += amount;
totalReleased += amount;
token.safeTransfer(beneficiary, amount);
emit TokensReleased(beneficiary, amount);
}
/// @notice Beneficiary tự rút token đã vest cho chính mình.
function release() external nonReentrant {
require(finalized, "Chua finalize, token chua duoc khoa vao contract");
uint256 amount = _release(msg.sender);
require(amount > 0, "Chua co token de rut");
}
/// @notice V1.1 — Cho phép BẤT KỲ ai (vd. keeper bot trả gas hộ) kích hoạt release
/// cho một beneficiary cụ thể. Token luôn chỉ chuyển đến đúng địa chỉ `beneficiary`
/// đã ghi trong schedule — người gọi hàm này không nhận được gì và không thể đổi
/// địa chỉ nhận. Hữu ích khi beneficiary không tự thao tác on-chain được.
function releaseFor(address beneficiary) external nonReentrant {
require(finalized, "Chua finalize, token chua duoc khoa vao contract");
require(schedules[beneficiary].totalAmount > 0, "Beneficiary khong ton tai");
uint256 amount = _release(beneficiary);
require(amount > 0, "Chua co token de rut cho beneficiary nay");
}
/// @notice V1.1 — Release hộ nhiều beneficiary trong một transaction. Địa chỉ nào
/// chưa có gì để release (releasable = 0) sẽ được BỎ QUA thay vì làm revert cả
/// batch. Không giới hạn quyền gọi — ai trả gas cũng được, token vẫn luôn về đúng
/// từng beneficiary tương ứng. Không dùng cho danh sách quá lớn trong 1 tx để
/// tránh vượt gas limit của block (khuyến nghị chia batch ở phía off-chain).
function releaseBatch(address[] calldata benes) external nonReentrant {
require(finalized, "Chua finalize, token chua duoc khoa vao contract");
for (uint256 i = 0; i < benes.length; i++) {
_release(benes[i]);
}
}
/// @notice Tìm vị trí của một địa chỉ trong mảng beneficiaries. Dùng nội bộ cho
/// việc chuyển địa chỉ (V1.2). An toàn về gas vì beneficiaries.length <= 200.
function _findBeneficiaryIndex(address b) internal view returns (uint256 idx, bool found) {
uint256 n = beneficiaries.length;
for (uint256 i = 0; i < n; i++) {
if (beneficiaries[i] == b) {
return (i, true);
}
}
return (0, false);
}
/// @notice V1.2 — Beneficiary hiện tại đề xuất chuyển toàn bộ quyền nhận vesting
/// (nguyên vẹn totalAmount/released/start/cliff/duration) sang một địa chỉ khác.
/// Đây mới chỉ là bước ĐỀ XUẤT — chưa có gì thay đổi cho tới khi `newBeneficiary`
/// tự gọi acceptBeneficiaryTransfer(). Gọi lại hàm này sẽ ghi đè đề xuất cũ (nếu có).
function proposeBeneficiaryTransfer(address newBeneficiary) external {
require(schedules[msg.sender].totalAmount > 0, "Ban khong phai beneficiary");
require(newBeneficiary != address(0), "Dia chi moi khong duoc la zero");
require(newBeneficiary != msg.sender, "Dia chi moi phai khac dia chi hien tai");
require(newBeneficiary != address(this), "Dia chi moi khong duoc la chinh contract");
require(schedules[newBeneficiary].totalAmount == 0, "Dia chi moi da la beneficiary khac");
pendingBeneficiaryTransfer[msg.sender] = newBeneficiary;
emit BeneficiaryTransferProposed(msg.sender, newBeneficiary);
}
/// @notice V1.2 — Beneficiary hiện tại huỷ đề xuất chuyển địa chỉ đang chờ (nếu có).
function cancelBeneficiaryTransfer() external {
address pending = pendingBeneficiaryTransfer[msg.sender];
require(pending != address(0), "Khong co de xuat nao dang cho");
delete pendingBeneficiaryTransfer[msg.sender];
emit BeneficiaryTransferCancelled(msg.sender, pending);
}
/// @notice V1.2 — Địa chỉ MỚI tự gọi để xác nhận nhận chuyển quyền vesting từ
/// `oldBeneficiary`. Bắt buộc đúng msg.sender đã được `oldBeneficiary` đề xuất,
/// để đảm bảo người nhận thực sự kiểm soát private key của địa chỉ mới trước khi
/// dời entitlement — tránh mất vĩnh viễn quyền vesting do gõ nhầm địa chỉ.
/// Toàn bộ schedule được dời nguyên vẹn (không đổi totalAmount/released/start/
/// cliff/duration); địa chỉ cũ bị xoá hoàn toàn khỏi schedules và beneficiaries.
/// Hoạt động cả trước và sau finalize() vì không đụng tới totalAllocated hay
/// dòng token, chỉ đổi người nhận của một entitlement đã tồn tại.
function acceptBeneficiaryTransfer(address oldBeneficiary) external {
require(pendingBeneficiaryTransfer[oldBeneficiary] == msg.sender, "Khong co de xuat hop le cho ban");
require(schedules[msg.sender].totalAmount == 0, "Dia chi cua ban da la beneficiary khac");
VestingSchedule memory s = schedules[oldBeneficiary];
require(s.totalAmount > 0, "Lich vesting cu khong con ton tai");
(uint256 idx, bool found) = _findBeneficiaryIndex(oldBeneficiary);
require(found, "Khong tim thay dia chi cu trong danh sach");
delete schedules[oldBeneficiary];
delete pendingBeneficiaryTransfer[oldBeneficiary];
s.beneficiary = msg.sender;
schedules[msg.sender] = s;
beneficiaries[idx] = msg.sender;
emit BeneficiaryTransferAccepted(oldBeneficiary, msg.sender, s.totalAmount, s.released);
}
function beneficiariesCount() external view returns (uint256) {
return beneficiaries.length;
}
/// @notice V1.1 — Kiểm tra nhanh một địa chỉ có phải beneficiary đã được add hay không.
function isBeneficiary(address b) external view returns (bool) {
return schedules[b].totalAmount > 0;
}
/// @notice Trả về toàn bộ danh sách địa chỉ beneficiary đã add cho tới hiện tại.
/// An toàn để gọi qua eth_call (view, không ghi state) kể cả khi danh sách đầy
/// (MAX_BENEFICIARIES = 200) — dùng để audit off-chain trước khi finalize().
function getAllBeneficiaries() external view returns (address[] memory) {
return beneficiaries;
}
/// @notice Trả về schedule đầy đủ của một beneficiary, kèm vested/releasable
/// hiện tại — gộp 3 lần gọi (schedules, vestedAmount, releasableAmount) thành 1,
/// tiện cho dashboard/tool off-chain.
function getSchedule(address beneficiary) external view returns (ScheduleView memory) {
VestingSchedule memory s = schedules[beneficiary];
uint256 vested = vestedAmount(beneficiary);
uint256 releasable = s.totalAmount == 0 ? 0 : vested - s.released;
return ScheduleView({
beneficiary: s.beneficiary,
totalAmount: s.totalAmount,
released: s.released,
start: s.start,
cliff: s.cliff,
duration: s.duration,
vested: vested,
releasable: releasable
});
}
/// @notice Trả về schedule đầy đủ (kèm vested/releasable) của TẤT CẢ beneficiary
/// đã add cho tới hiện tại, trong một lần gọi. Dùng để deployer tự kiểm tra toàn
/// bộ danh sách off-chain trước khi gọi finalize() — giảm rủi ro finalize nhầm.
/// An toàn về gas vì đây là hàm view (chỉ chạy qua eth_call, không tốn gas thật,
/// không bị giới hạn gas block) và MAX_BENEFICIARIES chặn trần ở 200 phần tử.
function getAllSchedules() external view returns (ScheduleView[] memory) {
uint256 n = beneficiaries.length;
ScheduleView[] memory result = new ScheduleView[](n);
for (uint256 i = 0; i < n; i++) {
address b = beneficiaries[i];
VestingSchedule memory s = schedules[b];
uint256 vested = vestedAmount(b);
result[i] = ScheduleView({
beneficiary: s.beneficiary,
totalAmount: s.totalAmount,
released: s.released,
start: s.start,
cliff: s.cliff,
duration: s.duration,
vested: vested,
releasable: vested - s.released
});
}
return result;
}
/// @notice Tổng hợp nhanh trạng thái chuẩn bị finalize: đã add bao nhiêu beneficiary,
/// còn thiếu bao nhiêu so với expectedBeneficiaryCount, đã sẵn sàng finalize chưa,
/// và allowance hiện tại của deployer cho contract này đã đủ totalAllocated chưa.
/// Gọi hàm này TRƯỚC finalize() để tự kiểm tra, vì finalize là hành động một chiều.
function readyToFinalize()
external
view
returns (
bool countMatches,
uint256 addedCount,
uint256 remaining,
uint256 allocated,
uint256 deployerAllowance,
bool allowanceSufficient
)
{
addedCount = beneficiaries.length;
remaining = expectedBeneficiaryCount > addedCount ? expectedBeneficiaryCount - addedCount : 0;
countMatches = expectedCountSet && addedCount == expectedBeneficiaryCount;
allocated = totalAllocated;
deployerAllowance = token.allowance(deployer, address(this));
allowanceSufficient = deployerAllowance >= totalAllocated;
}
function excessToken() public view returns (uint256) {
uint256 committed = totalAllocated - totalReleased;
uint256 balance = token.balanceOf(address(this));
if (balance <= committed) return 0;
return balance - committed;
}
function sweepExcessToken(address to) external onlyDeployer nonReentrant {
require(finalized, "Chua finalize");
require(to != address(0), "Dia chi nhan khong duoc la zero");
require(to != address(this), "Khong duoc gui ve chinh contract");
uint256 amount = excessToken();
require(amount > 0, "Khong co token du de quet");
token.safeTransfer(to, amount);
emit ExcessSwept(to, amount);
}
function rescueToken(address otherToken, address to, uint256 amount) external onlyDeployer nonReentrant {
require(otherToken != address(token), "Khong duoc rut token vesting chinh, dung sweepExcessToken");
require(to != address(0), "Dia chi nhan khong duoc la zero");
require(to != address(this), "Khong duoc gui ve chinh contract");
IERC20(otherToken).safeTransfer(to, amount);
emit TokenRescued(otherToken, to, amount);
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
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);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also applies here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 _safeTransfer(token, to, value, false);
}
/**
* @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 _safeTransferFrom(token, from, to, value, false);
}
/**
* @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 {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 relies 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 relies 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}.
* Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// 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
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": false
},
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.