Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"rainlink-contract-main/token/Pool.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "@openzeppelin/contracts@5.0.0/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts@5.0.0/utils/Address.sol";
import "@openzeppelin/contracts@5.0.0/utils/math/Math.sol";
import {Types} from "../comn/Types.sol";
import {IToken} from "../comn/IToken.sol";
import {ComFunUtil} from "../comn/ComFunUtil.sol";
import {SafeERC20} from "../comn/SafeERC20.sol";
import {Comn} from "./Comn.sol";
/**
* @title Pool
* @dev This contract manages a pool of tokens. It allows users to stake tokens, withdraw tokens,
* earn bonuses, and provides functions for pool management and fee handling.
*/
contract Pool is Comn {
// Constant representing the pool fee rate. The value is divided by 1000000 to get the actual rate.
uint constant POOL_FEE = 3000;
using EnumerableSet for EnumerableSet.AddressSet;
// Mapping from user address to the prepaid amount of native tokens (ticket).
// It won't record how many tokens the user has; other places will handle that.
mapping(address => uint) private _userPayTicket; // native token prepay amount ticket
// Mapping from token address to the total remaining amount of the token in the pool.
// The remaining token is the locked amount, and users can withdraw it.
mapping(address => uint) private _tokenTotalRemainAmount;
// Mapping from user address to a set of token addresses that the user has staked.
mapping(address => EnumerableSet.AddressSet) private userStakeTokenSet;
// Total prepaid amount of native tokens (all tickets).
uint private allPayTicket;
// Mapping from token address to the pool information of that token.
mapping(address => Types.PoolInfo) public poolMap;
// Array of token addresses representing all the pools.
address[] public poolArr;
// Mapping from user address to another mapping from token address to the user's staked amount information.
mapping(address => mapping(address => Types.UserAmountInfo))
public userStakeAmountMap;
// Mapping from user address to another mapping from token address to the user's locked amount information.
mapping(address => mapping(address => Types.UserAmountInfo))
public userLockAmountMap;
// Mapping from token address to the platform fee amount for that token.
mapping(address => uint) public feeAmountMap;
// Mapping from token address to the pool fee rate. The value is divided by 1000000 to get the actual rate.
mapping(address => uint) public poolFeeMap;
/**
* @dev Modifier that restricts a function to be called only by the executor.
* Throws an error if the caller is not the executor.
*/
modifier onlyExecutor() {
require(ExecutorAddr == msg.sender, "Must executor");
_;
}
/**
* @dev Creates a new pool for a given token.
* Only the administrator can call this function.
* @param token The address of the token for which the pool is to be created.
*/
function createPool(address token) public onlyAdmin {
// Create an instance of the IToken interface for the given token.
IToken tokenOp = IToken(token);
// Try to get the decimals of the token to check if it is a valid token.
tokenOp.decimals();
// Check if the pool for the given token already exists.
if (poolMap[token].token != address(0)) {
revert("already created");
}
// Create a new PoolInfo struct for the token.
Types.PoolInfo memory p;
p.token = token;
// Add the pool information to the poolMap.
poolMap[token] = p;
// Add the token address to the poolArr.
poolArr.push(token);
}
/**
* @dev Removes a pool for a given token.
* Only the administrator can call this function.
* @param token The address of the token for which the pool is to be removed.
*/
function removePool(address token) public onlyAdmin {
// Check if the pool for the given token exists.
if (poolMap[token].token == address(0)) {
revert("Pool does not exist");
}
// Check if the pool has any staked tokens or locked tokens.
if (poolMap[token].inAmount != 0 || poolMap[token].acc != 0) {
revert("Cannot remove pool: inAmount or acc is not zero");
}
// Remove the token from the poolArr.
for (uint256 i = 0; i < poolArr.length; i++) {
if (poolArr[i] == token) {
// Copy the last element to the current index.
poolArr[i] = poolArr[poolArr.length - 1];
// Remove the last element from the array.
poolArr.pop();
break;
}
}
// Delete the pool information from the poolMap.
delete poolMap[token];
}
/**
* @dev Sets the pool fee for a given token.
* Only the administrator can call this function.
* @param token The address of the token for which the pool fee is to be set.
* @param feeRate The pool fee rate. this value is divided by 1000000 to get the actual rate.
*/
function setPoolFeeRate(address token, uint feeRate) public onlyAdmin {
require(feeRate <= 1000000, "fee rate too high");
poolFeeMap[token] = feeRate;
}
/**
* @dev Allows a user to stake tokens into a pool.
* @param stakeToken The address of the token to be staked.
* @param amount The amount of tokens to be staked.
*/
function stakeIntoPool(address stakeToken, uint amount) public payable {
// Check if the pool for the given token exists.
if (poolMap[stakeToken].token == address(0)) {
revert("pool not found");
}
// Ensure the staked amount is greater than zero.
require(amount > 0, "amount is zero");
// If the token is a wrapped token (WTOKEN_ADDRESS), check if the user sent enough Ether.
if (isWToken(stakeToken)) {
require(
msg.value >= amount,
"please send enough gas, or adjust amount"
);
} else {
// Transfer the tokens from the user to the contract.
SafeERC20.safeTransferFrom(
IToken(stakeToken),
msg.sender,
address(this),
amount
);
}
// Add the token to the user's staked token set.
userStakeTokenSet[msg.sender].add(stakeToken);
// Add the staked amount to the pool.
_addStakeAmount(stakeToken, amount);
}
/**
* @dev Allows a user to withdraw tokens from a pool.
* @param stakeToken The address of the token to be withdrawn.
* @param amount The amount of tokens to be withdrawn.
*/
function withdrawFromPool(address stakeToken, uint amount) public payable {
// Check if the pool for the given token exists.
if (poolMap[stakeToken].token == address(0)) {
revert("pool not found");
}
// Ensure the withdrawn amount is greater than zero.
require(amount > 0, "amount is zero");
// Remove the staked amount from the pool.
_removeStakeAmount(stakeToken, amount);
// If the token is a wrapped token (WTOKEN_ADDRESS), send Ether to the user.
if (isWToken(stakeToken)) {
Address.sendValue(payable(msg.sender), amount);
} else {
// Transfer the tokens from the contract to the user.
SafeERC20.safeTransfer(IToken(stakeToken), msg.sender, amount);
}
}
/**
* @dev Allows a user to withdraw the bonus from a pool.
* @param stakeToken The address of the token from which the bonus is to be withdrawn.
* @param amount The amount of bonus to be withdrawn.
*/
function withdrawBonusFromPool(address stakeToken, uint amount) public {
// Check if the pool for the given token exists.
if (poolMap[stakeToken].token == address(0)) {
revert("pool not found");
}
require(amount > 0, "amount is zero");
address user = msg.sender;
// Calculate the bonus amount.
uint bonus = calBonusFromPool(user, stakeToken);
require(bonus > 0, "bonus is zero");
// If there is a bonus, proceed with the withdrawal.
emit Types.Log("wd bonus", bonus);
// Reset the bonus information.
_resetBonus(stakeToken, amount);
// Decrease the total amount in the pool.
poolMap[stakeToken].inAmount -= amount;
// If the token is a wrapped token (WTOKEN_ADDRESS), send Ether to the user.
if (isWToken(stakeToken)) {
Address.sendValue(payable(user), amount);
} else {
// Transfer the tokens from the contract to the user.
SafeERC20.safeTransfer(IToken(stakeToken), user, amount);
}
}
/**
* @dev Allows the executor to transfer tokens from the pool to a destination address.
* @param destToken The address of the token to be transferred.
* @param toWho The address of the recipient.
* @param allAmount The total amount of tokens to be transferred.
*/
function transferFromPool(
address destToken,
address toWho,
uint allAmount
) public payable onlyExecutor {
// Calculate the LP fee.
uint lp_fee = getLpFee(destToken, allAmount);
// Calculate the actual amount to be transferred after deducting the fee.
uint amount = allAmount - lp_fee;
if (isWToken(destToken)) {
Address.sendValue(payable(toWho), amount);
} else {
SafeERC20.safeTransfer(IToken(destToken), toWho, amount);
}
// Calculate the pool fee.
uint pool_fee = Math.mulDiv(
lp_fee,
poolMap[destToken].amount,
poolMap[destToken].inAmount
);
// Calculate the decrease in the staked amount.
uint stakedDecrease = (allAmount * poolMap[destToken].amount) /
poolMap[destToken].inAmount;
require(
stakedDecrease <= poolMap[destToken].amount,
"pool amount insufficient for transfer"
);
// Decrease the staked amount in the pool.
poolMap[destToken].amount -= stakedDecrease;
// Decrease the total amount in the pool.
poolMap[destToken].inAmount -= allAmount;
// Return the remaining pool fee
poolMap[destToken].inAmount += (lp_fee - pool_fee);
// Get a reference to the pool information.
Types.PoolInfo storage poolInfo = poolMap[destToken];
// If there is a staked amount in the pool, update the reward amount and APY.
if (poolInfo.stakeAmount > 0) {
poolInfo.rewardAmount += pool_fee;
if (pool_fee > 0 && poolInfo.stakeAmount > 0) {
uint acc_percentage = (pool_fee * (1 << 64)) /
poolInfo.stakeAmount;
emit Types.Log("acc_percentage", acc_percentage);
poolInfo.acc += acc_percentage;
// cal the apy
if (poolInfo.last_receive_rewards_time == 0) {
poolInfo.last_apy = acc_percentage;
poolInfo.last_receive_rewards_time = ComFunUtil
.currentTimestamp();
} else {
uint now_secs = ComFunUtil.currentTimestamp();
uint delta = now_secs - poolInfo.last_receive_rewards_time;
if (delta > 0) {
poolInfo.last_apy =
(acc_percentage * 365 * 24 * 60 * 60) /
delta;
poolInfo.last_receive_rewards_time = now_secs;
}
}
}
}
}
/**
* @dev Calculates the bonus amount for a user in a given pool.
* @param user The address of the user.
* @param stakeToken The address of the token in the pool.
* @return The calculated bonus amount.
*/
function calBonusFromPool(
address user,
address stakeToken
) public view returns (uint) {
// Get the user's staked amount information.
Types.UserAmountInfo memory uInfo = userStakeAmountMap[user][
stakeToken
];
// Calculate the new reward.
uint newReward = (uInfo.amount * poolMap[stakeToken].acc) >> 64;
// Calculate the total bonus.
return newReward + uInfo.remainReward - uInfo.debt;
}
/**
* @dev Calculates the LP fee for a given token and amount.
* @param token The address of the token.
* @param amount The amount of tokens.
* @return The calculated LP fee.
*/
function getLpFee(address token, uint amount) public view returns (uint) {
uint feeRate = poolFeeMap[token];
uint pool_fee_all = Math.mulDiv(amount, feeRate, 1000000);
return pool_fee_all;
}
/**
* @dev Retrieves the pool information for a given token.
* @param stakeToken The address of the token.
* @return The pool information struct.
*/
function getPoolInfo(
address stakeToken
) public view returns (Types.PoolInfo memory) {
return poolMap[stakeToken];
}
/**
* @dev Retrieves the information of all pools.
* @return rs An array of pool information structs.
*/
function getAllPoolsInfo()
public
view
returns (Types.PoolInfo[] memory rs)
{
rs = new Types.PoolInfo[](poolArr.length);
for (uint i = 0; i < poolArr.length; i++) {
rs[i] = poolMap[poolArr[i]];
}
}
/**
* @dev Retrieves the staked information of all tokens for a given user.
* @param user The address of the user.
* @return An array of user staked amount information structs for view.
*/
function getAllUserStakeInfo(
address user
) public view returns (Types.UserAmountInfoForViewV2[] memory) {
// Get the user's staked token set.
EnumerableSet.AddressSet storage stakeSet = userStakeTokenSet[user];
// Get the number of staked tokens.
uint len = stakeSet.length();
// Create an array to store the user staked amount information for view.
Types.UserAmountInfoForViewV2[]
memory uai = new Types.UserAmountInfoForViewV2[](len);
// Get the array of staked token addresses.
address[] memory values = stakeSet.values();
for (uint i = 0; i < len; i++) {
// Get the address of the staked token.
address stakeToken = values[i];
// Calculate the bonus amount.
uint bonus = calBonusFromPool(user, stakeToken);
// Get the user's staked amount information.
Types.UserAmountInfo memory userStakeInfo = userStakeAmountMap[
user
][stakeToken];
// Populate the array with the user staked amount information for view.
uai[i] = Types.UserAmountInfoForViewV2({
token: userStakeInfo.token,
amountType: userStakeInfo.amountType,
amount: userStakeInfo.amount,
debt: userStakeInfo.debt,
remainReward: userStakeInfo.remainReward,
acc: poolMap[stakeToken].acc,
bonus: bonus,
earns: bonus
});
}
return uai;
}
/**
* @dev Checks if a given token is a wrapped token (WTOKEN_ADDRESS).
* @param token The address of the token.
* @return A boolean indicating whether the token is a wrapped token.
*/
function isWToken(address token) public pure returns (bool) {
return token == WTOKEN_ADDRESS;
}
/**
* @dev Allows a user to send Ether as a fee for a given token.
* @param stakeToken The address of the token.
*/
function sendEthFee(address stakeToken) public payable {
// Get the amount of Ether sent.
uint amount = msg.value;
// Add the locked amount to the pool.
_addLockAmount(stakeToken, amount);
}
/**
* @dev Allows a user to send tokens as a fee.
* @param token The address of the token.
* @param amount The amount of tokens to be sent.
*/
function sendTokenFee(address token, uint amount) public {
// Check if the pool for the given token exists.
require(poolMap[token].token != address(0), "pool not found");
// Transfer the tokens from the user to the contract.
SafeERC20.safeTransferFrom(
IToken(token),
msg.sender,
address(this),
amount
);
// Add the locked amount to the pool.
_addLockAmount(token, amount);
}
/**
* @dev Allows the executor to transfer the fee to a relay address.
* @param token The address of the token.
* @param relay The address of the relay.
* @param amount The amount of tokens to be transferred.
*/
function transferFeeToRelay(
address token,
address relay,
uint amount
) public onlyExecutor {
// Decrease the total amount in the pool.
poolMap[token].inAmount -= amount;
// Decrease the locked amount in the pool.
poolMap[token].lockAmount -= amount;
// Transfer the tokens from the contract to the relay.
SafeERC20.safeTransfer(IToken(token), relay, amount);
}
/**
* @dev Adds the staked amount to the pool and updates the user's staked amount information.
* @param token The address of the token.
* @param amount The amount of tokens to be staked.
*/
function _addStakeAmount(address token, uint amount) private {
poolMap[token].amount += amount;
poolMap[token].inAmount += amount;
poolMap[token].stakeAmount += amount;
address user = msg.sender;
// Check if this is the first time the user stakes this token.
if (userStakeAmountMap[user][token].token == address(0)) {
// If it's the first time, initialize the token and set the amount type to 1 (stake value).
userStakeAmountMap[user][token].token = token;
userStakeAmountMap[user][token].amountType = 1;
}
// Increase the user's staked amount.
userStakeAmountMap[user][token].amount += amount;
// Calculate the new debt based on the staked amount and the current accumulated value.
uint newDebt = (amount * poolMap[token].acc) >> 64;
// Increase the user's debt.
userStakeAmountMap[user][token].debt += newDebt;
}
/**
* @dev Removes the staked amount from the pool and updates the user's staked amount information.
* Also calculates and updates the user's remaining reward.
* @param token The address of the token.
* @param amount The amount of tokens to be removed from the stake.
*/
function _removeStakeAmount(address token, uint amount) private {
address user = msg.sender;
uint userAllAmount = userStakeAmountMap[user][token].amount;
require(amount <= userAllAmount, "not enough user assets");
userStakeAmountMap[user][token].amount -= amount;
require(amount <= poolMap[token].inAmount, "not enough pool assets");
require(
amount <= poolMap[token].stakeAmount,
"not enough pool stakeAmount assets"
);
uint userStakeRatio = (userAllAmount * 1e18) /
poolMap[token].stakeAmount;
uint withdrawRatio = (amount * 1e18) / userAllAmount;
uint stakedDecrease = (poolMap[token].amount * userStakeRatio) / 1e18;
stakedDecrease = (stakedDecrease * withdrawRatio) / 1e18;
require(
stakedDecrease <= poolMap[token].amount,
"pool amount insufficient for withdrawal"
);
poolMap[token].amount -= stakedDecrease;
poolMap[token].inAmount -= amount;
poolMap[token].stakeAmount -= amount;
// Calculate the new reward based on the withdrawn amount and the current accumulated value.
uint newReward = (amount * poolMap[token].acc) >> 64;
uint partDebt = (userStakeAmountMap[user][token].debt * amount) /
userAllAmount;
if (newReward > partDebt) {
userStakeAmountMap[user][token].remainReward +=
newReward -
partDebt;
}
// Decrease the user's debt.
userStakeAmountMap[user][token].debt -= partDebt;
}
/**
* @dev Adds the locked amount to the pool and updates the fee amount map.
* @param token The address of the token.
* @param amount The amount of tokens to be locked.
*/
function _addLockAmount(address token, uint amount) private {
// Increase the total amount in the pool.
poolMap[token].inAmount += amount;
// Increase the locked amount in the pool.
poolMap[token].lockAmount += amount;
// Increase the platform fee amount for the token.
feeAmountMap[token] += amount;
}
/**
* @dev Resets the user's bonus information after a bonus withdrawal.
* @param token The address of the token.
* @param amount_ The amount of bonus to be withdrawn.
*/
function _resetBonus(address token, uint amount_) private {
address user = msg.sender;
uint amount = userStakeAmountMap[user][token].amount;
uint newDebt = (amount * poolMap[token].acc) >> 64;
// Calculate the total reward the user has earned.
uint totalReward = newDebt -
userStakeAmountMap[user][token].debt +
userStakeAmountMap[user][token].remainReward;
// Check if the user has enough reward.
require(totalReward >= amount_, "not enough reward");
uint newReward = totalReward - amount_;
// Update the user's remaining reward and debt.
userStakeAmountMap[user][token].remainReward = newReward;
userStakeAmountMap[user][token].debt = newDebt;
}
}
"
},
"rainlink-contract-main/token/Comn.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "../BaseComn.sol";
/**
* @title all sol extends from this
* @dev Extends BaseComn with additional address constants
*/
abstract contract Comn is BaseComn {
// xone
address constant WTOKEN_ADDRESS = address(0x912A11C41d0D79c8466574d4C03cE68990dB713B);
address constant PoolAddr = address(0x52D4C1A6A69274afEe28C1A85e083357a9a1ffb2);
address constant ExecutorAddr = address(0x0D193a0B5f6Dc2f7c579219067DcD00df67241a1);
address constant MessagerAddr = address(0x46CE5d59b7aFfd84f97D4868814AF2cb7c9133d1);
// tbsc
// address constant WTOKEN_ADDRESS = address(0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd);
// address constant PoolAddr = address(0x38f9c465128F3139Ca70707eA7232568aC89C42B);
// address constant ExecutorAddr = address(0xc8C4087c56B47e4658F54b925aF607118D461798);
// address constant MessagerAddr = address(0xF2B99D50bdb83110aBf94cA7cD98057E95302D83);
// sepolia
// address constant WTOKEN_ADDRESS = address(0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14);
// address constant PoolAddr = address(0x5Dab805f174FA4e66aeE1947978e055C61e16AB2);
// address constant ExecutorAddr = address(0x3B43c5B5c83b683ecE682e4ed8a75ec81BB55248);
// address constant MessagerAddr = address(0xb2E08E9840Cd02dE0002189BBd2Bc24333a7c9D2);
// nile
// address constant WTOKEN_ADDRESS = address(0xfb3b3134F13CcD2C81F4012E53024e8135d58FeE); //TYsbWxNnyTgsZaTFaue9hqpxkU3Fkco94a
// address constant PoolAddr = address(0x273Ea2807918A51D7e4D0E47779365391105eFa4); //TDYiPUqKWvFSu3qpgTP4ctNXPQqaxPnJXp
// address constant ExecutorAddr = address(0x7b6229abeE4D531D7ae82b00f5b8F52D0a5764EB); //TMDbi88CTghZj88NbGKn4NPnzWptrH453B
// address constant MessagerAddr = address(0x181Ff0aEd1d4a5829936322363D992D570c8f0c3); //TCAmUuRamPsA5m862JQUpDaJkDTGznpV6y
}
"
},
"rainlink-contract-main/comn/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;
import "@openzeppelin/contracts@5.0.0/token/ERC20/IERC20.sol";
library SafeERC20 {
// mainnet:0xa614f803B6FD780986A42c78Ec9c7f77e6DeD13C
address constant USDTAddr = 0xa614f803B6FD780986A42c78Ec9c7f77e6DeD13C;
function safeIncreaseAllowance(IERC20 token, address to, uint value) internal {
uint newAllowance = token.allowance(address(this), to) + value;
safeApprove(token, to, newAllowance);
}
function safeApprove(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
if (address(token) == USDTAddr && success) {
return;
}
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
}
"
},
"rainlink-contract-main/comn/ComFunUtil.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {Types} from "./Types.sol";
library ComFunUtil {
function isNotEmpty(address ad, string memory msgs) private pure {
require(ad != address(0), msgs);
}
function isNotEmpty(uint ad, string memory msgs) private pure {
require(ad != 0, msgs);
}
function combainChain(
Types.Chain memory chain_
) internal pure returns (uint72) {
uint72 c = chain_.chain_id;
// must use uint72 to avoid u8 overflow
uint72 chain_type = chain_.chain_type;
c += chain_type << 64;
return c;
}
function splitChain(uint a1) internal pure returns (Types.Chain memory c) {
c.chain_id = uint64(a1);
c.chain_type = uint8(a1 >> 64);
}
function addressToBytes32(address a) internal pure returns (bytes32 b) {
return bytes32(uint(uint160(a)));
}
function bytes32ToAddress(bytes32 a) internal pure returns (address b) {
return address(uint160(uint(a)));
}
function hexStr2bytes32(string memory data) internal pure returns (bytes32) {
return bytes2bytes32(hexStr2bytes(data));
}
function bytes2bytes32(bytes memory data) internal pure returns (bytes32) {
uint len = data.length;
if (len > 32) {
revert("data len is overflow 32");
}
uint rs = 0;
for (uint i = 0; i < len; i++) {
rs = rs << 8;
rs += uint8(data[i]);
}
return bytes32(rs);
}
// convert hex string to bytes
function hexStr2bytes(
string memory data
) internal pure returns (bytes memory) {
bytes memory a = bytes(data);
if (a.length % 2 != 0) {
revert("hex string len is invalid");
}
uint8[] memory b = new uint8[](a.length);
for (uint i = 0; i < a.length; i++) {
uint8 _a = uint8(a[i]);
if (_a > 96) {
b[i] = _a - 97 + 10;
} else if (_a > 66) {
b[i] = _a - 65 + 10;
} else {
b[i] = _a - 48;
}
}
bytes memory c = new bytes(b.length / 2);
for (uint _i = 0; _i < b.length; _i += 2) {
c[_i / 2] = bytes1(b[_i] * 16 + b[_i + 1]);
}
return c;
}
function stringConcat(
string memory a,
string memory b,
bytes memory d
) internal pure returns (string memory) {
bytes memory a1 = bytes(a);
bytes memory a2 = bytes(b);
bytes memory a3;
a3 = new bytes(a1.length + a2.length + d.length);
uint k = 0;
for (uint i = 0; i < a1.length; i++) {
a3[k++] = a1[i];
}
for (uint i = 0; i < d.length; i++) {
a3[k++] = d[i];
}
for (uint i = 0; i < a2.length; i++) {
a3[k++] = a2[i];
}
return string(a3);
}
function currentTimestamp() internal view returns (uint256) {
return block.timestamp;
}
}
"
},
"rainlink-contract-main/comn/IToken.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "@openzeppelin/contracts@5.0.0/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts@5.0.0/token/ERC20/extensions/IERC20Metadata.sol";
interface IToken is IERC20, IERC20Metadata {
function isMinter(address addr) external pure returns (bool);
function mintFor(address account, uint256 amount) external;
function burnFor(address account, uint256 amount) external;
}"
},
"rainlink-contract-main/comn/Types.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
// all data in this file we should remain static.
// as this file may be used when create empty StoreHouse. to avoid any data not being initialized. we should keet it static.
library Types {
event Log(string);
event Log(string, bytes);
event Log(uint);
event Log(string, uint);
event Log(string, bytes32);
event Log(string, bytes32, uint);
event Log(string, address);
struct PoolInfo {
address token;
uint amount; // actual remain amount.
uint inAmount; // all in token = all in lock amount + all in stake amount.
uint lockAmount; // actual locked by contract
uint stakeAmount; // actual user stake into contract.
uint rewardAmount; // reward for staker, will used in future. now all reward will added to stake amount.
uint acc; // Q64.64
uint last_apy; // Q64.64
uint last_receive_rewards_time;
}
enum AmountType {
locked,
staked
}
enum TokenType {
pool,
mint
}
struct UserAmountInfo {
address token;
uint8 amountType; // 0 locked value. 1 staked value.
uint amount;
uint debt;
uint remainReward;
// for locked user. all amount = amount
// for stake user all amount = amount*acc - debt + amount + remainReward
}
// for front end.
struct UserAmountInfoForView {
address token;
uint8 amountType; // 0 locked value. 1 staked value.
uint amount;
uint debt;
uint remainReward;
uint acc;
uint bonus;
// for locked user. all amount = amount
// for stake user all amount = amount*acc - debt + amount + remainReward
}
// for front end.
struct UserAmountInfoForViewV2 {
address token;
uint8 amountType; // 0 locked value. 1 staked value.
uint amount;
uint debt;
uint remainReward;
uint acc;
uint bonus;
// for locked user. all amount = amount
// for stake user all amount = amount*acc - debt + amount + remainReward
uint earns;
}
struct FromSource {
uint source_chain_id;
bytes32 source_token;
}
struct RelationShipInfo {
address dest_token;
uint8 dest_token_type; // 0 for pool, 1 for new mint
}
struct SourceTokenInfo {
uint8 initialized;
uint8 decimals; // record the decimals for source token
}
struct CrossRelation {
uint source_chain_id;
bytes32 source_token;
uint8 source_token_decimals;
address dest_token;
uint8 dest_token_type;
}
struct MessageMeta {
// BridgeMessage bridgeMsg;
// // other fields
uint8 status; //
uint[4] reserves;
}
struct Chain {
uint8 chain_type;
uint64 chain_id;
}
enum ChainType {
ETH,
TRX,
SOL
}
struct Message {
MessageHeader msg_header;
bytes msg_body;
}
struct MessageHeader {
uint8 msg_type; // 0 means bridge message
uint64 nonce;
Chain from_chain; //
bytes32 sender;
// address messager;
Chain to_chain; //
bytes32 receiver;
uint128 upload_gas_fee;
}
struct BridgeMessageBody {
// body
bytes32 source_token;
uint128 all_amount;
// uint amount;
// uint platform_fee;
// uint upload_fee_price; // all amount = amount + platform_fee + upload_gas_fee * upload_fee_price
bytes32 from_who;
bytes32 to_who;
bytes biz_data;
// uint slipage;
}
struct ERC20Permit {
address owner;
address spender;
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct UserWithdrawData {
address token;
uint amount; // uni decimal.
// string symbol;
}
struct UserWithdrawDataDetail {
address token;
string symbol;
string name;
uint8 decimal;
uint amount;
}
struct ErrorObj {
uint key;
uint error_type;
string sMsg;
uint cMsg;
bytes bMsg;
string desc; // description
}
}
"
},
"@openzeppelin/contracts@5.0.0/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
"
},
"@openzeppelin/contracts@5.0.0/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
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();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
"
},
"@openzeppelin/contracts@5.0.0/utils/structs/EnumerableSet.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32S
Submitted on: 2025-09-19 13:09:04
Comments
Log in to comment.
No comments yet.