// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 4 of 11: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @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[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 5 of 11: IERC20.sol
// This is a file copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
functiondecimals() externalviewreturns (uint8);
functionname() externalviewreturns (stringmemory);
functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address recipient, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` 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.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(address sender, address recipient, uint256 amount) externalreturns (bool);
functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
Contract Source Code
File 6 of 11: IStarBaseDCA.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;interfaceIStarBaseDCA{
// Order 结构体structOrder {
uint160 cycleSecondsApart; // executed per seconduint160 numberOfTrade; // executed 5 timesaddress inputToken; // selladdress outputToken; // buyaddress maker;
uint160 inAmount; // One of the total (numberOfTrade)uint256 minOutAmountPerCycle; // min out amountuint256 maxOutAmountPerCycle; // max out amountuint256 expiration;
uint256 salt;
}
// ============ DCA ===============functionfillDCA(
Order memory order,
bytesmemory signature,
bytesmemory takerInteraction
) externalreturns (uint256 curTakerFillAmount);
functioncancelOrder(Order memory order, bytesmemory signature) external;
}
/*
Copyright 2020 StarBase .
SPDX-License-Identifier: Apache-2.0
This is a simplified version of OpenZepplin's SafeERC20 library
*/pragmasolidity ^0.8.4;import"@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from"../intf/IERC20.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
functionsafeApprove(IERC20 token, address spender, uint256 value) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'// solhint-disable-next-line max-line-lengthrequire(
(value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
require(Address.isContract(address(token)), "SafeERC20: call to non-contract");
(bool success, bytesmemory returndata) =address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length>0) {
// Return data is optional// solhint-disable-next-line max-line-lengthrequire(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
Contract Source Code
File 11 of 11: StarBaseDCABot.sol
/*
Copyright 2024 StarBase .
SPDX-License-Identifier: Apache-2.0
*/pragmasolidity ^0.8.4;import { InitializableOwnable } from"./lib/InitializableOwnable.sol";
import { IERC20 } from"./intf/IERC20.sol";
import { SafeERC20 } from"./lib/SafeERC20.sol";
import { IStarBaseRouter } from"./intf/IStarBaseRouter.sol";
import { ERC165 } from"@openzeppelin/contracts/utils/introspection/ERC165.sol";
import { Common } from"./lib/Common.sol";
import { IStarBaseDCA } from"./intf/IStarBaseDCA.sol";
import { IStarBaseDCABot } from"./intf/IStarBaseDCABot.sol";
/**
* @title StarBaseDCABot
* @dev This contract is a DCA (Dollar Cost Averaging) bot for StarBase, enabling users to automate trades and interact with StarBase's DCA mechanism.
* @notice The bot allows admin users to initiate DCA trades and perform token swaps through a connected router.
* @author StarBase
*/contractStarBaseDCABotisInitializableOwnable, ERC165{
usingSafeERC20forIERC20;
// ================ Storage ================addresspublic _StarBase_DCA_;
addresspublic _TOKEN_RECEIVER_;
mapping(address=>bool) public isAdminListed;
addresspublic _Setup_Tool_;
// ================ Events ================eventAddAdmin(addressindexed admin);
eventRemoveAdmin(addressindexed admin);
eventChangeReceiver(addressindexed newReceiver);
eventFill(bytes, address, uint256);
structSwapData {
address callSwapAddr;
bytes datas;
}
/**
* @dev Initializes the contract with the given parameters.
* @param owner The address of the owner.
* @param tokenReceiver The address of the token receiver for the filled DCA trades.
* @param userAddr List of admin addresses that are allowed to execute certain functions.
*/constructor(address owner, address tokenReceiver, address[] memory userAddr) {
Common._validateAddress(owner);
Common._validateAddress(tokenReceiver);
initOwner(owner);
_TOKEN_RECEIVER_ = tokenReceiver;
emit ChangeReceiver(_TOKEN_RECEIVER_);
for (uint i =0; i < userAddr.length; i++) {
isAdminListed[userAddr[i]] =true;
emit AddAdmin(userAddr[i]);
}
}
/**
* @dev Executes the DCA trade by interacting with the StarBase DCA contract and transferring the resulting tokens.
* @param callExternalData Data to call the external DCA contract with.
* @param outputToken The address of the token that is received after the DCA trade.
* @param minOutputTokenAmount The minimum amount of the output token that should be received.
*/functionfillStarBaseDCA(bytesmemory callExternalData,
address outputToken,
uint256 minOutputTokenAmount
) external{
require(isAdminListed[msg.sender], "SDCAB: ACCESS_DENIED");
Common._validateAddress(outputToken);
uint256 originTakerBalance = IERC20(outputToken).balanceOf(address(this));
(bool success, bytesmemory data) = _StarBase_DCA_.call(callExternalData);
if (!success) {
assembly {
revert(add(data, 32), mload(data))
}
}
uint256 leftTakerAmount = IERC20(outputToken).balanceOf(address(this)) - originTakerBalance;
require(leftTakerAmount >= minOutputTokenAmount, "SDCAB: TAKER_AMOUNT_NOT_ENOUGH");
IERC20(outputToken).safeTransfer(_TOKEN_RECEIVER_, leftTakerAmount);
emit Fill(callExternalData, outputToken, minOutputTokenAmount);
}
/**
* @dev Executes a swap on the DCA contract using the provided parameters.
* @param inAmount The amount of the input token to swap.
* @param minOutAmount The minimum amount of output token to receive.
* @param maxOutAmount The maximum amount of output token to allow.
* @param inputToken The address of the input token.
* @param outputToken The address of the output token.
* @param StarBaseRouteProxy The address of the StarBase route proxy for swapping.
* @param datas Data for the swap call.
* @return returnTakerAmount The amount of output token received from the swap.
*/functiondoDCASwap(uint256 inAmount,
uint256 minOutAmount,
uint256 maxOutAmount,
address inputToken,
address outputToken,
address StarBaseRouteProxy,
SwapData calldata datas
) externalreturns (uint256 returnTakerAmount) {
Common._validateAddress(inputToken);
Common._validateAddress(outputToken);
Common._validateAddress(StarBaseRouteProxy);
require(msg.sender== _StarBase_DCA_, "SDCAB: ACCESS_DENIED");
uint256 originTakerBalance = IERC20(outputToken).balanceOf(address(this));
_approve(IERC20(inputToken), StarBaseRouteProxy, inAmount);
IStarBaseRouter(StarBaseRouteProxy).defiSwap(
inAmount,
minOutAmount,
inputToken,
outputToken,
address(this),
datas.callSwapAddr,
datas.datas
);
returnTakerAmount = IERC20(outputToken).balanceOf(address(this)) - originTakerBalance;
require(returnTakerAmount >= minOutAmount, "SDCAB: SWAP_TAKER_AMOUNT_NOT_ENOUGH");
if (returnTakerAmount > maxOutAmount) {
returnTakerAmount = maxOutAmount;
}
_approve(IERC20(outputToken), _StarBase_DCA_, returnTakerAmount);
}
function_checkIfContractSupportsInterface(address _contract, bytes4 interfaceId) internalviewreturns (bool) {
(bool success, bytesmemory result) = _contract.staticcall(
abi.encodeWithSelector(ERC165.supportsInterface.selector, interfaceId)
);
if (success && result.length==32) {
returnabi.decode(result, (bool));
}
returnfalse;
}
functionsupportsInterface(bytes4 interfaceId) publicpureoverride(ERC165) returns (bool) {
return interfaceId ==type(IStarBaseDCABot).interfaceId;
}
// ============= Ownable Functions =============functionsetDcaContract(address StarBaseDCA) externalonlyOwner{
require(
_checkIfContractSupportsInterface(StarBaseDCA, type(IStarBaseDCA).interfaceId),
"SLOP: ADDRESS_DOES_NOT_IMPLEMENT_REQUIRED_METHODS"
);
_StarBase_DCA_ = StarBaseDCA;
}
/**
* @dev Adds an address to the list of admin addresses.
* @param userAddr The address of the user to add as an admin.
*/functionaddAdminList(address userAddr) externalonlyOwner{
Common._validateAddress(userAddr);
isAdminListed[userAddr] =true;
emit AddAdmin(userAddr);
}
/**
* @dev Removes an address from the list of admin addresses.
* @param userAddr The address of the user to remove from the admin list.
*/functionremoveAdminList(address userAddr) externalonlyOwner{
Common._validateAddress(userAddr);
isAdminListed[userAddr] =false;
emit RemoveAdmin(userAddr);
}
/**
* @dev Changes the address where the tokens are sent after a DCA fill.
* @param newTokenReceiver The address of the new token receiver.
*/functionchangeTokenReceiver(address newTokenReceiver) externalonlyOwner{
Common._validateAddress(newTokenReceiver);
_TOKEN_RECEIVER_ = newTokenReceiver;
emit ChangeReceiver(newTokenReceiver);
}
// ============= Internal Functions =============/**
* @dev Approves the specified amount of a token for a given spender.
* @param token The token to approve.
* @param to The address to approve.
* @param amount The amount to approve.
*/function_approve(IERC20 token, address to, uint256 amount) internal{
uint256 allowance = token.allowance(address(this), to);
// Only approve if the current allowance is less than the required amountif (allowance < amount) {
// Reset allowance to zero first to avoid race conditionif (allowance >0) {
token.safeApprove(to, 0);
}
// Approve exactly the required amount
token.safeApprove(to, amount);
}
}
// ============= View Functions =============/**
* @dev Returns the current version of the contract.
* @return The current version number.
*/functionversion() externalpurereturns (uint256) {
return101;
}
}