Verified contractPartialMIT
Presale
Address0x799485465d1108035e72d4febdcd6ebf1bf8bdef
- Balance
0.208883 ETH
- Transactions
160
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- No
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,003,210
- Creation transaction
- 0x12e26c5346…b338d0b72f
2 files
- Presale_krm.solmain14.49 KB
- Helper.sol10.77 KB
Presale_krm.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {Ownable, Pausable, Aggregator, IERC20, SafeERC20, MathUtils} from "./Helper.sol";
/// NOTE : Instead of require use revert for less gas cost
/// NOTE : Use unchecked for adding or subtracting(check overflow when user give higher input value to overflow the value)
/// NOTE : Instead of withdrawing total amounts use desired amounts for user purpose(for that use max like ico_user)
contract Presale is Ownable, Pausable {
using SafeERC20 for IERC20;
IERC20 public immutable token;
IERC20 public immutable usdt;
uint256 public totalTokensSold;
uint256 public startTime;
uint256 public endTime;
uint256 public nativeRaised;
uint256 public usdtRaised;
uint256 public valueRaised; //represents total value of tokens sold by taking price of native currency at sale time
uint256 public price = 700000; //price in usdt 0.007$
uint256 public unWithdrawnAffProfitNative = 0;
uint256 public unWithdrawnAffProfitUSDT = 0;
Aggregator public immutable aggregatorInterface;
//referral system
struct Affiliate {
address user;
bool revoked; //revoked codes don't incur profit
uint8 profitPercent; // absolute numbers between 0 - 100
uint256 tokensSold;
uint256 usdtProfit;
uint256 nativeProfit;
uint256 usdtWithdrawn;
uint256 nativeWithdrawn;
string code;
}
struct AffiliateSale {
address user;
uint256 profit; // represent usdt amount or eth amount
bool isUsdtPurchase;
uint256 investment; // represent usdt amount or eth amount
uint256 tokensTransferred; // represent KMR token
uint256 purchaseTime;
}
/// NOTE : Instead of mapping(address => string) codeMap; use mapping(string => address) codeMap; for increase the better formormance and accessability
mapping(string => Affiliate) public affiliateMap;
mapping(address => string) public codeMap;
mapping(string => AffiliateSale[]) public affiliateSales;
string[] public codes;
/// NOTE : If the tokens are fixed the use contants or immutables instead of storage variables
constructor() {
token = IERC20(0x51539ED14Bd63A77bF319061A336f14b77AdC895);
usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
aggregatorInterface = Aggregator(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
startTime = block.timestamp;
}
function changeSaleStartTime(uint256 _startTime) external onlyOwner {
require(block.timestamp <= _startTime, "Sale time in past");
startTime = _startTime;
}
function changeSaleEndTime(uint256 _endTime) external onlyOwner {
require(startTime <= _endTime, "Sale time in past than startTime");
endTime = _endTime;
}
/// NOTE : Not useful to returning the bool value (gas cost)
function pause() external onlyOwner {
_pause();
}
/// NOTE : Not useful to returning the bool value (gas cost)
function unpause() external onlyOwner {
_unpause();
}
function updatePrice(uint256 newPrice) external onlyOwner {
price = newPrice;
}
modifier onlyAlphanumeric(string memory input) {
bytes memory strBytes = bytes(input);
for (uint256 i = 0; i < strBytes.length; i++) {
bytes1 char = strBytes[i];
if (
!(// Check if it's a valid character (0-9, A-Z, a-z)
(char >= 0x30 && char <= 0x39) || // '0' - '9'
(char >= 0x41 && char <= 0x5A) || // 'A' - 'Z'
(char >= 0x61 && char <= 0x7A)) // 'a' - 'z'
) {
revert("Invalid character: Only A-Z, a-z, 0-9 allowed");
}
}
_;
}
/// NOTE : Fixed size variables should be first and dynamic size should be at last
/// NOTE : Use profit percentage to 2 deciamls for more precision values
function registerAffiliate(
string calldata code,
address user,
uint8 profitPercent
) external onlyOwner onlyAlphanumeric(code) {
require(user != address(0), "Can't regiser for 0 address");
require(
profitPercent >= 0 && profitPercent <= 100,
"Invalid Profit Percent"
);
/// NOTE : No need to check for both times
require(affiliateMap[code].user == address(0), "Code already in use");
require(
keccak256(abi.encodePacked(codeMap[user])) ==
keccak256(abi.encodePacked("")),
"User already registered"
);
Affiliate memory affiliate = Affiliate({
user: user,
revoked: false,
profitPercent: profitPercent, /// NOTE : U8 is more gas be like
tokensSold: 0,
usdtProfit: 0,
nativeProfit: 0,
usdtWithdrawn: 0,
nativeWithdrawn: 0,
code: code /// NOTE : Use fixed length of bytes16 like that and generate fixed size code
});
affiliateMap[code] = affiliate;
codeMap[user] = code;
codes.push(code);
}
function updateAffiliateProfit(
string calldata code,
uint8 profitPercent
) external onlyOwner {
require(affiliateMap[code].user != address(0), "Invalid Code");
require(
affiliateMap[code].revoked == false,
"Can't update revoked user"
);
require(
profitPercent >= 0 && profitPercent <= 100, /// NOTE : use static variables
"Invalid Profit Percent"
);
affiliateMap[code].profitPercent = profitPercent;
}
function updateRevokeStatus(
string calldata code,
bool revoked
) external onlyOwner {
require(affiliateMap[code].user != address(0), "Invalid Code");
affiliateMap[code].revoked = revoked;
}
/// NOTE : if all the amount is taken, then what about the distributers amounts
function withdrawNative() public onlyOwner {
uint256 available = address(this).balance - unWithdrawnAffProfitNative;
require(available > 0, "Amount not available for admin withdrawl");
payable(owner()).transfer(available);
}
function withdrawTokens(address _token, uint256 amount) external onlyOwner {
uint256 available = IERC20(_token).balanceOf(address(this));
if (_token == address(usdt)) {
available -= unWithdrawnAffProfitUSDT;
}
require(
available >= amount,
"Insufficient tokens" /// NOTE : use a tracking variable, because distributers amount is also contains
);
IERC20(_token).safeTransfer(_msgSender(), amount);
}
modifier checkSaleState(uint256 amount) {
require(startTime <= block.timestamp, "ICO hasn't started yet");
require(block.timestamp < endTime, "ICO has ended");
require(amount > 0, "Invalid amount");
_;
}
function withdrawAffiliateProfitUsdt() external {
address user = msg.sender;
require(
keccak256(abi.encodePacked(codeMap[user])) !=
keccak256(abi.encodePacked("")),
"User is not an affiliate"
);
Affiliate storage affiliate = affiliateMap[codeMap[user]];
uint256 availableForWithdrawl = affiliate.usdtProfit -
affiliate.usdtWithdrawn;
affiliate.usdtWithdrawn += availableForWithdrawl;
unWithdrawnAffProfitUSDT -= availableForWithdrawl;
usdt.safeTransfer(_msgSender(), availableForWithdrawl);
}
function withdrawAffiliateProfitNative() external {
address user = msg.sender; /// NOTE : Comparing addresses are cheaper than strings
require(
keccak256(abi.encodePacked(codeMap[user])) !=
keccak256(abi.encodePacked("")),
"User is not an affiliate"
);
Affiliate storage affiliate = affiliateMap[codeMap[user]];
uint256 availableForWithdrawl = affiliate.nativeProfit -
affiliate.nativeWithdrawn;
affiliate.nativeWithdrawn += availableForWithdrawl;
unWithdrawnAffProfitNative -= availableForWithdrawl;
payable(msg.sender).transfer(availableForWithdrawl);
}
function buyWithUSDT(
uint256 amount,
string calldata code
) external checkSaleState(amount) whenNotPaused {
// NOTE : USDT is eth is 6 decimals
// token is 2 decimals divide by 4 to make it standard for calculation
uint256 tokensReceivable = calculateToken(amount) / 1e4; //2 decimals
usdt.safeTransferFrom(_msgSender(), address(this), amount);
token.safeTransfer(_msgSender(), tokensReceivable);
totalTokensSold += tokensReceivable;
usdtRaised += amount;
valueRaised += amount; // 6 decimals
//check for referral code validity
if (affiliateMap[code].user != address(0)) {
//check if affiliate user is revoked
if (affiliateMap[code].revoked) return;
Affiliate storage affiliate = affiliateMap[code];
uint256 commission = (amount * affiliate.profitPercent) / 100;
affiliate.usdtProfit += commission;
affiliate.tokensSold += tokensReceivable;
AffiliateSale memory sale = AffiliateSale({
user: msg.sender,
profit: commission,
isUsdtPurchase: true,
investment: amount,
tokensTransferred: tokensReceivable,
purchaseTime: block.timestamp
});
affiliateSales[code].push(sale);
unWithdrawnAffProfitUSDT += commission;
}
}
function buyWithNative(
string calldata code
) external payable checkSaleState(msg.value) whenNotPaused {
//eth in wei is 18 decimals, token is 2 decimals divide by 16 to make it standard for calculation
uint256 nativeToUsdt = (getLatestPrice() * msg.value) / (1e8); // 18 decimals
uint256 tokensReceivable = calculateToken(nativeToUsdt) / (1e16); // 2 decimals
token.safeTransfer(_msgSender(), tokensReceivable);
totalTokensSold += tokensReceivable;
nativeRaised += msg.value;
valueRaised += nativeToUsdt / 1e12; // 6 decimals
//check for referral code validity
if (affiliateMap[code].user != address(0)) {
//check if affiliate user is revoked
if (affiliateMap[code].revoked) return;
Affiliate storage affiliate = affiliateMap[code];
uint256 commission = (msg.value * affiliate.profitPercent) / 100;
affiliate.nativeProfit += commission;
affiliate.tokensSold += tokensReceivable;
AffiliateSale memory sale = AffiliateSale({
user: msg.sender,
profit: commission,
isUsdtPurchase: false,
investment: msg.value, /// NOTE : msg.value is used no.of time
tokensTransferred: tokensReceivable,
purchaseTime: block.timestamp
});
affiliateSales[code].push(sale);
unWithdrawnAffProfitNative += commission;
}
}
function calculateToken(uint256 _usdtAmount) public view returns (uint256) {
return (_usdtAmount * 1e8) / price;
}
function nativeBuyHelper(
/// NOTE : Nothing use of function, no where it is used
uint256 amount
) external view returns (uint256 numOfTokens) {
uint256 nativeToUsdt = (getLatestPrice() * amount) / 1e8;
numOfTokens = calculateToken(nativeToUsdt);
}
function totalTokenInPresale() public view returns (uint256) {
uint256 unsoldTokens = IERC20(token).balanceOf(address(this));
uint256 totaltokenInPresale = totalTokensSold + unsoldTokens;
return totaltokenInPresale;
}
function getLatestPrice() public view returns (uint256) {
(, int256 _price, , , ) = aggregatorInterface.latestRoundData();
return uint256(_price);
}
///NOTE : For these two use same function
function getTokenBalance() public view returns (uint256 tokenBalance) {
tokenBalance = token.balanceOf(address(this));
} /// NOTE : No need to keep here, if required we can get the data from erc20 abi contract
function getUsdtBalance() public view returns (uint256 usdtBalance) {
usdtBalance = usdt.balanceOf(address(this));
} /// NOTE : Same like above
function getNativeBalance() public view returns (uint256 NATIVE) {
NATIVE = address(this).balance;
} /// NOTE : Same like above
function getTotalAffiliates() public view returns (uint256) {
return codes.length;
} /// NOTE : If we not used in frontend then just remove it
function getTotalSalesAffiliate(
string calldata code
) public view returns (uint256) {
return affiliateSales[code].length;
} /// NOTE : Same like above
function getAffiliates(
uint256 length,
uint256 offset
) public view returns (Affiliate[] memory) {
uint256 offsetCount = offset * length; /// Bug: Getting wrong offset value
if (codes.length <= offsetCount) return new Affiliate[](0);
uint256 count = MathUtils.min(codes.length - offsetCount, length);
Affiliate[] memory affiliates = new Affiliate[](count);
for (uint256 i = 0; i < count; i++) {
/// NOTE : Instead of i=0 use i = offset*length
affiliates[i] = affiliateMap[codes[i + offsetCount]];
}
return affiliates;
}
function getAffiliateSales(
string calldata code,
uint256 length,
uint256 pageOffset
) public view returns (AffiliateSale[] memory) {
uint256 offsetCount = pageOffset * length;
if (affiliateSales[code].length <= offsetCount)
return new AffiliateSale[](0);
uint256 count = MathUtils.min(
affiliateSales[code].length - offsetCount,
length
);
AffiliateSale[] memory sales = new AffiliateSale[](count);
for (uint256 i = 0; i < count; i++) {
sales[i] = affiliateSales[code][i + offsetCount];
}
return sales;
}
receive() external payable {
/// NOTE : Inside here if any user send , add to tracking variable
}
}
Helper.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(
address owner,
address spender
) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_setOwner(msg.sender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) internal {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
interface Aggregator {
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
library Address {
error AddressInsufficientBalance(address account);
error AddressEmptyCode(address target);
error FailedInnerCall();
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
function functionCall(
address target,
bytes memory data
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResultFromTarget(target, success, returndata);
}
function functionStaticCall(
address target,
bytes memory data
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
function functionDelegateCall(
address target,
bytes memory data
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
function verifyCallResult(
bool success,
bytes memory returndata
) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
function _revert(bytes memory returndata) private pure {
if (returndata.length > 0) {
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC1363 is IERC20, IERC165 {
function transferAndCall(address to, uint256 value) external returns (bool);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function transferFromAndCall(
address from,
address to,
uint256 value
) external returns (bool);
function transferFromAndCall(
address from,
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function approveAndCall(
address spender,
uint256 value
) external returns (bool);
function approveAndCall(
address spender,
uint256 value,
bytes calldata data
) external returns (bool);
}
library MathUtils {
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
}
library SafeERC20 {
using Address for address;
error SafeERC20FailedOperation(address token);
error SafeERC20FailedDecreaseAllowance(
address spender,
uint256 currentAllowance,
uint256 requestedDecrease
);
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeCall(token.transferFrom, (from, to, value))
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
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);
}
}
function forceApprove(
IERC20 token,
address spender,
uint256 value
) internal {
bytes memory approvalCall = abi.encodeCall(
token.approve,
(spender, value)
);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(
token,
abi.encodeCall(token.approve, (spender, 0))
);
_callOptionalReturn(token, approvalCall);
}
}
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));
}
}
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));
}
}
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));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
function _callOptionalReturnBool(
IERC20 token,
bytes memory data
) private returns (bool) {
(bool success, bytes memory returndata) = address(token).call(data);
return
success &&
(returndata.length == 0 || abi.decode(returndata, (bool))) &&
address(token).code.length > 0;
}
}
abstract contract Pausable is Context {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() {
_paused = false;
}
modifier whenNotPaused() {
_requireNotPaused();
_;
}
modifier whenPaused() {
_requirePaused();
_;
}
function paused() public view virtual returns (bool) {
return _paused;
}
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": false
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.