Verified contractPartialBUSL-1.1
Executor
Address0x7bc276a77c4b2aa577d5ddf9a39d64465ae7464a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,295,903
- Creation transaction
- 0x3be6ffb712…0f0d32a689
19 files
- token/Executor.solmain20.58 KB
- @openzeppelin/[email protected]/interfaces/draft-IERC6093.sol6.53 KB
- @openzeppelin/[email protected]/token/ERC20/ERC20.sol11.14 KB
- @openzeppelin/[email protected]/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/[email protected]/utils/Address.sol6.26 KB
- @openzeppelin/[email protected]/utils/Context.sol860 B
- @openzeppelin/[email protected]/utils/StorageSlot.sol3.93 KB
- @openzeppelin/[email protected]/utils/math/Math.sol15.12 KB
- BaseComn.sol884 B
- comn/ComFunUtil.sol3.07 KB
- comn/IAdmin.sol355 B
- comn/IMessager.sol1.06 KB
- comn/IPool.sol1.64 KB
- comn/IToken.sol449 B
- comn/SafeERC20.sol1.73 KB
- comn/Types.sol4.35 KB
- token/Comn.sol1.88 KB
- token/Token.sol1.36 KB
token/Executor.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "@openzeppelin/[email protected]/utils/math/Math.sol";
import "@openzeppelin/[email protected]/utils/Address.sol";
import {Types} from "../comn/Types.sol";
import {IPool} from "../comn/IPool.sol";
import {IMessager} from "../comn/IMessager.sol";
import {IToken} from "../comn/IToken.sol";
import {ComFunUtil} from "../comn/ComFunUtil.sol";
import {SafeERC20} from "../comn/SafeERC20.sol";
import {BridgeToken} from "./Token.sol";
import {Comn} from "./Comn.sol";
/**
* @title Executor
* @dev This contract inherits from the Comn contract and is mainly used to manage cross - chain token relationships,
* create new tokens, handle cross - chain token bridging, and process messages.
*/
contract Executor is Comn {
// Mapping from source chain ID to source token to relationship information.
// It stores the relationship information between tokens on different source chains and tokens on the destination chain.
mapping(uint => mapping(bytes32 => Types.RelationShipInfo))
public tokenRelationshipMap;
// Mapping from source chain ID to source token to source token information.
// It stores relevant information about tokens on different source chains.
mapping(uint => mapping(bytes32 => Types.SourceTokenInfo))
public sourceTokenInfoMap;
// Array that stores cross - chain relationship information.
// It contains all the relevant information about cross - chain tokens.
Types.CrossRelation[] public crossArr;
// Mapping from the address of a new ERC20 token to its status.
// It records newly created tokens and their status.
mapping(address => uint) public newMintMap;
// Mapping from chain ID to contract address.
// It stores the contract addresses corresponding to different chains.
mapping(uint => bytes32) public chainContractMap;
// Mapping from chain ID to fee token address.
// It stores the fee token addresses corresponding to different chains.
mapping(uint => bytes32) public chainFeeTokenMap;
event TokenRelationshipSet(
uint indexed source_chain_id,
bytes32 indexed source_token,
uint8 source_token_decimals,
address dest_token,
uint8 dest_token_type
);
event TokenRelationshipRemoved(
uint indexed source_chain_id,
bytes32 indexed source_token
);
/**
* @dev Sets the contract address for a specified chain. This function can only be called by the administrator.
* @param source_chain_id The ID of the source chain.
* @param contract_addr The address of the contract.
*/
function setChainContract(
uint source_chain_id,
bytes32 contract_addr
) public onlyAdmin {
chainContractMap[source_chain_id] = contract_addr;
}
/**
* @dev Sets the fee token address for a specified chain. This function can only be called by the administrator.
* @param source_chain_id The ID of the source chain.
* @param fee_token_addr The address of the fee token.
*/
function setChainFeeToken(
uint source_chain_id,
bytes32 fee_token_addr
) public onlyAdmin {
chainFeeTokenMap[source_chain_id] = fee_token_addr;
}
/**
* @dev Sets the token relationship. Before setting the relationship, the pool or minted token must exist.
* This function can only be called by the administrator.
* @param source_chain_id The combined chain type and chain ID of the source chain.
* @param source_token The source token in bytes32 format.
* @param source_token_decimals The number of decimals of the source token.
* @param _dest_token The destination token in bytes32 format.
* @param dest_token_type The type of the destination token.
*/
function setTokenRelationship(
uint source_chain_id, // combain chain_type&chain_id
bytes32 source_token,
uint8 source_token_decimals,
bytes32 _dest_token,
uint8 dest_token_type
) public onlyAdmin {
address dest_token = ComFunUtil.bytes32ToAddress(_dest_token);
if (dest_token_type == uint8(Types.TokenType.pool)) {
// 0 means pool map
require(
IPool(PoolAddr).getPoolInfo(dest_token).token != address(0),
"no token for type 0"
);
} else {
// 1 means mint token.
require(newMintMap[dest_token] > 0, "no token for type 1");
}
require(
tokenRelationshipMap[source_chain_id][source_token].dest_token ==
address(0),
"has been set"
);
tokenRelationshipMap[source_chain_id][source_token] = Types
.RelationShipInfo(dest_token, dest_token_type);
sourceTokenInfoMap[source_chain_id][source_token] = Types
.SourceTokenInfo(1, source_token_decimals);
crossArr.push(
Types.CrossRelation(
source_chain_id,
source_token,
source_token_decimals,
dest_token,
dest_token_type
)
);
emit TokenRelationshipSet(
source_chain_id,
source_token,
source_token_decimals,
dest_token,
dest_token_type
);
}
/**
* @dev Removes the token relationship. This function can only be called by the administrator.
* @param source_chain_id The ID of the source chain.
* @param source_token The source token in bytes32 format.
*/
function removeTokenRelationship(
uint source_chain_id,
bytes32 source_token
) public onlyAdmin {
// Types.RelationShipInfo memory data;
delete tokenRelationshipMap[source_chain_id][source_token];
delete sourceTokenInfoMap[source_chain_id][source_token];
for (uint i = 0; i < crossArr.length; i++) {
Types.CrossRelation memory data = crossArr[i];
if (
data.source_chain_id == source_chain_id &&
data.source_token == source_token
) {
crossArr[i] = crossArr[crossArr.length - 1];
crossArr.pop();
emit TokenRelationshipRemoved(source_chain_id, source_token);
break;
}
}
}
/**
* @dev Creates a new token for minting on the local chain. This function can only be called by the administrator.
* @param name The name of the token.
* @param symbol The symbol of the token.
* @param decimals The number of decimals of the token.
* @return The address of the newly created token.
*/
function createNewToken(
string memory name,
string memory symbol,
uint8 decimals
) public onlyAdmin returns (address) {
BridgeToken newToken = new BridgeToken{salt: bytes32(0)}(
name,
symbol,
decimals,
address(this)
);
emit Types.Log("newToken", address(newToken));
if (newMintMap[address(newToken)] != 0) {
revert("token already in use");
}
newMintMap[address(newToken)] = 1;
return address(newToken);
}
/**
* @dev Bridges a token across chains.
* @param source_token The source token in bytes32 format.
* @param to_chain The destination chain information.
* @param to_who The recipient in bytes32 format on the destination chain.
* @param receiver The destination bridger in bytes32 format.
* @param all_amount The total amount of tokens to be bridged.
* @param upload_gas_fee The gas fee for uploading, converted from the target platform token to the source platform token.
*/
function bridgeToken(
bytes32 source_token,
Types.Chain memory to_chain,
bytes32 to_who,
bytes32 receiver, // destination bridger
uint128 all_amount,
uint128 upload_gas_fee // convert target platform token to source platform token
) public payable {
uint all_value = msg.value;
uint msger_value;
// transfer gas fee to pool
require(all_value >= upload_gas_fee, "please send enough gas");
msger_value = all_value - upload_gas_fee;
IPool(PoolAddr).sendEthFee{value: upload_gas_fee}(WTOKEN_ADDRESS);
address source_address = ComFunUtil.bytes32ToAddress(source_token);
// exist in poolMap
if (IPool(PoolAddr).getPoolInfo(source_address).token != address(0)) {
if (isWToken(source_address)) {
require(
all_value >= all_amount + upload_gas_fee,
"please send enough value, or adjust amount"
);
msger_value = all_value - all_amount - upload_gas_fee;
IPool(PoolAddr).sendEthFee{value: all_amount}(WTOKEN_ADDRESS);
} else {
SafeERC20.safeTransferFrom(
IToken(source_address),
msg.sender,
address(this),
all_amount
);
uint256 allowance = IToken(source_address).allowance(
address(this),
PoolAddr
);
if (allowance < all_amount) {
SafeERC20.safeIncreaseAllowance(
IToken(source_address),
PoolAddr,
type(uint256).max
);
}
IPool(PoolAddr).sendTokenFee(source_address, all_amount);
}
} else if (newMintMap[source_address] > 0) {
// burn token.
IToken tokenOp = IToken(source_address);
tokenOp.burnFor(msg.sender, all_amount);
} else {
revert("source token not supported");
}
// all amount = amount + platform_fee + upload_gas_fee * upload_fee_price
bytes memory messageBody = abi.encodePacked(
source_token, // source_token
uint128(all_amount), // all_amount
// upload_gas_fee, // upload_gas_fee
ComFunUtil.addressToBytes32(address(msg.sender)), // from_who
to_who // to who
// slipage
);
IMessager(MessagerAddr).emit_msg{value: msger_value}(
0,
to_chain,
receiver,
messageBody,
upload_gas_fee
);
}
/**
* @dev Processes a received message.
* @param message The received message.
* @param signature The array of signatures for the message. Each signature is 65 bytes.
* @return A boolean indicating whether the message was processed successfully.
*/
function processMsg(
Types.Message memory message,
bytes[] memory signature // 65bytes for one signature
) public returns (bool) {
(
Types.MessageHeader memory msg_header,
Types.BridgeMessageBody memory msg_body
) = decode_bridge_msg(message);
uint from_chain = ComFunUtil.combainChain(msg_header.from_chain);
require(
address(this) == ComFunUtil.bytes32ToAddress(msg_header.receiver),
"processMsg receiver error"
);
require(
chainContractMap[from_chain] == msg_header.sender,
"processMsg sender error"
);
bytes32 source_token = msg_body.source_token;
(
bool exist,
Types.RelationShipInfo memory tokenRInfo
) = getStrictTokenRelationship(from_chain, source_token);
if (!exist) {
revert("no token relation ship");
}
bool consume_success = IMessager(MessagerAddr).consume_bridge_msg(
message,
signature
);
if (
!consume_success &&
msg.sender != address(0x0000000000000000000000000000000000000001)
) {
revert("nonce has been uploaded");
}
// amount decimal process
bytes32 to_who = msg_body.to_who;
uint all_amount = msg_body.all_amount;
Types.SourceTokenInfo
memory source_token_info = getStrictSourceTokenInfo(
from_chain,
source_token
);
IToken tokenOp = IToken(tokenRInfo.dest_token);
uint8 dest_decimals = tokenOp.decimals();
if (dest_decimals > source_token_info.decimals) {
all_amount =
all_amount *
10 ** (dest_decimals - source_token_info.decimals);
} else if (dest_decimals < source_token_info.decimals) {
all_amount =
all_amount /
10 ** (source_token_info.decimals - dest_decimals);
}
if (tokenRInfo.dest_token_type == uint8(Types.TokenType.pool)) {
IPool(PoolAddr).transferFromPool(
tokenRInfo.dest_token,
ComFunUtil.bytes32ToAddress(to_who),
all_amount
);
} else {
// only mint token
BridgeToken destTokenOp = BridgeToken(tokenRInfo.dest_token);
destTokenOp.mintFor(
ComFunUtil.bytes32ToAddress(to_who),
all_amount
);
}
{
// mint gas_fee to sender
uint128 gas_fee = msg_header.upload_gas_fee;
if (gas_fee > 0) {
emit Types.Log("send gas fee to sender", gas_fee);
bytes32 fee_token = chainFeeTokenMap[from_chain];
(exist, tokenRInfo) = getStrictTokenRelationship(
from_chain,
fee_token
);
if (!exist) {
revert("no token relation ship for fee token");
}
Types.SourceTokenInfo
memory fee_token_info = getStrictSourceTokenInfo(
from_chain,
fee_token
);
tokenOp = IToken(tokenRInfo.dest_token);
uint8 fee_dest_decimals = tokenOp.decimals();
if (fee_dest_decimals > fee_token_info.decimals) {
gas_fee = uint128(
uint(gas_fee) *
10 ** (fee_dest_decimals - fee_token_info.decimals)
);
} else if (fee_dest_decimals < source_token_info.decimals) {
gas_fee = uint128(
uint(gas_fee) /
10 ** (fee_token_info.decimals - fee_dest_decimals)
);
}
if (tokenRInfo.dest_token_type == uint8(Types.TokenType.pool)) {
IPool(PoolAddr).transferFeeToRelay(
tokenRInfo.dest_token,
msg.sender,
gas_fee
);
} else {
BridgeToken destTokenOp = BridgeToken(
tokenRInfo.dest_token
);
destTokenOp.mintFor(msg.sender, gas_fee);
}
}
}
return true;
}
/**
* @dev Calculates the LP fee and the final amount after fee deduction.
* @param source_chain_id The ID of the source chain.
* @param source_token The source token in bytes32 format.
* @param all_amount The total amount of tokens.
* @return lp_fee The LP fee and the final amount after fee deduction.
*/
function getLpFeeAndFinalAmount(
uint source_chain_id,
bytes32 source_token,
uint all_amount
) public view returns (uint lp_fee, uint final_amount) {
(
bool exist,
Types.RelationShipInfo memory tokenRInfo
) = getStrictTokenRelationship(source_chain_id, source_token);
if (!exist) {
return (0, 0);
}
if (tokenRInfo.dest_token_type == uint8(Types.TokenType.pool)) {
uint pool_fee = IPool(PoolAddr).getLpFee(
tokenRInfo.dest_token,
all_amount
);
uint amount = all_amount - pool_fee;
return (pool_fee, amount);
} else {
return (0, all_amount);
}
}
/**
* @dev Decodes a bridge message.
* @param decMsg The message to be decoded.
* @return The message header and the bridge message body.
*/
function decode_bridge_msg(
Types.Message memory decMsg
)
public
pure
returns (Types.MessageHeader memory, Types.BridgeMessageBody memory)
{
Types.BridgeMessageBody memory bridgeMsgBody = IMessager(MessagerAddr)
.decode_bridge_msg_body(decMsg.msg_body);
return (decMsg.msg_header, bridgeMsgBody);
}
/**
* @dev Retrieves all cross - chain relationship information.
* @return An array containing all cross - chain relationship information.
*/
function getAllCrossRelation()
public
view
returns (Types.CrossRelation[] memory)
{
return crossArr;
}
/**
* @dev Retrieves the token relationship information.
* @param source_chain_id The ID of the source chain.
* @param source_token The source token in bytes32 format.
* @return A boolean indicating whether the relationship exists and the relationship information.
*/
function getTokenRelationship(
uint source_chain_id,
bytes32 source_token
) public view returns (bool, Types.RelationShipInfo memory) {
Types.RelationShipInfo memory data = tokenRelationshipMap[
source_chain_id
][source_token];
if (data.dest_token == address(0)) {
return (false, data);
}
return (true, data);
}
/**
* @dev Retrieves the strict token relationship information. Checks if the destination token exists in the pool or mint map.
* @param source_chain_id The ID of the source chain.
* @param source_token The source token in bytes32 format.
* @return A boolean indicating whether the relationship exists and the relationship information.
*/
function getStrictTokenRelationship(
uint source_chain_id,
bytes32 source_token
) public view returns (bool, Types.RelationShipInfo memory) {
Types.RelationShipInfo memory data = tokenRelationshipMap[
source_chain_id
][source_token];
if (data.dest_token == address(0)) {
return (false, data);
}
if (data.dest_token_type == uint8(Types.TokenType.pool)) {
if (
IPool(PoolAddr).getPoolInfo(data.dest_token).token == address(0)
) {
return (false, data);
}
} else {
if (newMintMap[data.dest_token] == 0) {
return (false, data);
}
}
return (true, data);
}
/**
* @dev Retrieves the source token information.
* @param source_chain_id The ID of the source chain.
* @param source_token The source token in bytes32 format.
* @return The source token information.
*/
function getSourceTokenInfo(
uint source_chain_id,
bytes32 source_token
) public view returns (Types.SourceTokenInfo memory) {
return sourceTokenInfoMap[source_chain_id][source_token];
}
/**
* @dev Retrieves the strict source token information. Ensures the source token information is initialized.
* @param source_chain_id The ID of the source chain.
* @param source_token The source token in bytes32 format.
* @return rs The source token information. Reverts if the information is not initialized.
*/
function getStrictSourceTokenInfo(
uint source_chain_id,
bytes32 source_token
) public view returns (Types.SourceTokenInfo memory rs) {
rs = sourceTokenInfoMap[source_chain_id][source_token];
if (rs.initialized == 0) {
revert("source token info is empty");
}
}
/**
* @dev Checks if a given token is the wrapped token.
* @param token The address of the token to check.
* @return A boolean indicating whether the token is the wrapped token.
*/
function isWToken(address token) public pure returns (bool) {
return token == WTOKEN_ADDRESS;
}
}@openzeppelin/[email protected]/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
@openzeppelin/[email protected]/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
@openzeppelin/[email protected]/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/[email protected]/utils/Address.sol
// 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/[email protected]/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/[email protected]/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/[email protected]/utils/math/Math.sol
// 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;
}
}
BaseComn.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "./comn/IAdmin.sol";
import {StorageSlot} from "@openzeppelin/[email protected]/utils/StorageSlot.sol";
/**
* @title BaseComn
* @dev Contains the core constants and base functionality
*/
abstract contract BaseComn {
bytes32 constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier onlyMaster() {
IAdmin(getAdminAddr()).mustMaster(msg.sender);
_;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
IAdmin(getAdminAddr()).mustAdmin(msg.sender);
_;
}
/**
* @dev Returns the admin address from storage slot
*/
function getAdminAddr() public view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
}
comn/ComFunUtil.sol
// 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;
}
}
comn/IAdmin.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/**
* @dev Interface for Admin
*/
interface IAdmin {
function mustMaster(address addr) external view;
function mustAdmin(address addr) external view;
function isMaster(address addr) external view returns (bool);
function isAdmin(address addr) external view returns (bool);
}
comn/IMessager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "./Types.sol";
interface IMessager {
event Msg(Types.Message);
event UploadFee(uint);
function set_bridge_fee(uint v) external;
function verify_msg(
Types.Message memory messageDec,
// uint16[] memory signer_index,
bytes[] memory signature
) external returns (bool);
function decode_msg(
bytes memory message
) external pure returns (Types.Message memory);
function decode_bridge_msg_body(
bytes memory msg_body
) external pure returns (Types.BridgeMessageBody memory);
// verify and consume it.
function consume_bridge_msg(
Types.Message memory messageDec,
bytes[] memory signature
) external returns (bool);
function emit_msg(
uint8 msg_type,
Types.Chain memory to_chain,
bytes32 receiver,
bytes memory message,
uint128 upload_gas_fee // source p token.
) external payable;
function withdrawFee(uint amount) external;
}
comn/IPool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "./Types.sol";
interface IPool {
function createPool(
address token // already exist in chain.
) external;
// stake into pool and record some information. no lp will be created.
// use msg.sender as staker
function stakeIntoPool(address stakeToken, uint amount) external payable;
// we use msg.sender and get the amount
function withdrawFromPool(address stakeToken, uint amount) external;
// only withdraw the bonus.
function withdrawBonusFromPool(address stakeToken, uint amount) external;
function getPoolInfo(
address stakeToken
) external view returns (Types.PoolInfo memory);
function getAllPoolsInfo()
external
view
returns (Types.PoolInfo[] memory rs);
function getAllUserStakeInfo(
address user
) external view returns (Types.UserAmountInfoForViewV2[] memory);
function transferFromPool(
address destToken,
address toWho,
uint allAmount
) external;
function calBonusFromPool(
address user,
address stakeToken
) external view returns (uint bonus);
function getLpFee(address token, uint amount) external view returns (uint);
function sendEthFee(address token) external payable;
function sendTokenFee(address token, uint amount) external;
function withdrawFee(address token, uint amount) external;
function transferFeeToRelay(
address token,
address relay,
uint amount
) external;
}
comn/IToken.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import "@openzeppelin/[email protected]/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;
}comn/SafeERC20.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;
import "@openzeppelin/[email protected]/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');
}
}
comn/Types.sol
// 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;
// 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
}
}
token/Comn.sol
// 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 {
address constant WTOKEN_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant PoolAddr = address(0x4aeDc117527fD270D4d56aA32f2E4e532547c8Dc);
address constant ExecutorAddr = address(0x5B6C580F2Af1eDD51349716f40A9104Bd918aef7);
address constant MessagerAddr = address(0xda6869A6435c3bef2Ece47cD1B0B020ffc62E1A3);
// 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
}
token/Token.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {ERC20} from "@openzeppelin/[email protected]/token/ERC20/ERC20.sol";
contract BridgeToken is ERC20 {
// the minter address
address private _minter;
// decimals
uint8 private _decimals;
/**
* @dev Throws if called by any account other than the master.
*/
modifier onlyMinter() {
require(msg.sender == _minter, "Must minter");
_;
}
/**
* @dev construct
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
address minter_
) ERC20(name_, symbol_) {
_decimals = decimals_;
_minter = minter_;
}
/**
* @dev set decimals 6, same as usdt
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
/**
* @dev Get the address is the minter
*/
function isMinter(address addr) public view returns (bool) {
return _minter == addr;
}
/**
* @dev bridge mint token
*/
function mintFor(address account, uint256 amount) public onlyMinter {
_mint(account, amount);
}
/**
* @dev bridge burn token
*/
function burnFor(address account, uint256 amount) public onlyMinter {
_burn(account, amount);
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.