Presale Contract Details

Presale Contract

Table of Contents

Introduction

Presale contracts facilitate the sale of a new cryptocurrency (presale token) before it launches on a public exchange. This contract offers a specific functionality that combines a presale mechanism with an affiliate marketing system. Here's a brief overview of what the contract enables:

Users can purchase presale tokens using either BNB or another ERC20 token. The contract employs Oracles to obtain the latest token prices, ensuring dynamic presale token pricing based on defined tiers. An interesting aspect is the dynamic price tier which will be changed after some amount of presale tokens has been bought. The contract integrates an affiliate marketing system, where affiliates can earn bonuses based on their own sales and the sales generated by the affiliates they refer (their children) up to a certain level within the referral hierarchy. To qualify for bonuses, there are minimum purchase requirements in place for both affiliates and their referred affiliates (children). Founders, potentially those at the top of the affiliate hierarchy, have a distinct bonus calculation mechanism compared to regular affiliates.

Contract Overview

Presale Mechanics:

  • The contract allows users to purchase presale tokens using either BNB (Binance Coin) or another ERC20 token (USDT). It leverages Oracles(Chainlink), external data providers, to fetch the latest BNB and paid-with token (ERC20 token used for purchase) prices. Based on these dynamic prices and pre-defined tiers(PriceTier), the contract calculates the presale token price for each purchase.

Affiliate Marketing System:

  • The contract facilitates the creation of an affiliate marketing system, where affiliates can be added to a hierarchical structure. This structure allows affiliates to earn bonuses based not only on their own sales but also on the sales generated by the affiliates they refer (their children) up to a certain level within the hierarchy. To prevent abuse and ensure active participation, the contract enforces minimum purchase requirements. Both affiliates and their referred affiliates (children) must meet these minimum purchase requirements to qualify for any bonus payouts. Founders, potentially those at the top of the affiliate hierarchy, have a separate bonus calculation mechanism compared to regular affiliates.

Presale Parameters

Oracle Interfaces

  • bnbPriceFeed: An interface to interact with the BNB price feed.

  • paidWithTokenPriceFeed: An interface to interact with the token used for payment price feed.

Numeric Constants

  • DECIMALS: The number of decimal places for token values.

  • DENOMINATOR: The denominator used for calculations.

  • PERCENTAGE_DENOMINATOR: The denominator for percentage calculations.

  • ORACLE_DENOMINATOR: The denominator for oracle values.

  • USD_DENOMINATOR: The denominator for USD calculations.

Role Constants

  • MANAGER_ROLE: The keccak256 hash representing the manager role.

Minimum Purchase Requirements

  • minPurchaseAmount: The minimum purchase amount in USD.

  • minChildPurchaseAmount: The minimum purchase amount for child affiliates.

Payment Ratio

  • paidWithRatioInPersent: The ratio of payment in percentage.

  • totalTokenSoldAmount: The total number of presale tokens sold.

  • paidWithPresaleDecimalsDiff: The difference in decimals between the paid token and the presale token.

Paused State

  • paused: Indicates whether the presale is paused or active.

Affiliate Levels

  • maxLevel: The maximum level of affiliates.

  • minChildsReachedDestinationValue: The minimum number of child affiliates required to reach the destination value.

Token Decimals

  • tokenDecimals: The number of decimals for the presale token.

Paid With Token Receiver Address

  • receiverOfEarnings: The address to receive presale earnings.

Token Contracts

  • paidWithToken: The contract address of the ERC20 token used for payment(e.g. USDT).

  • presaleToken: The contract address of the presale token.

Current Price Tier

  • priceTier: The current price tier of the presale.

Fee Distribution Array

  • feePercentageDistribution: An array representing the percentage distribution of fees.

Affiliate Mapping

  • affiliateIdChildsReachedDestinationValue: The number of child affiliates who have reached the destination value.

  • affiliateIdToAddress: The address associated with each affiliate ID.

  • affiliateIdToParentAffiliateId: The parent affiliate ID associated with each affiliate ID.

  • affiliateIdAffiliatedUSDAmount: The USD amount affiliated with each affiliate ID.

  • affiliateIdSoldTokenAmount: The number of presale tokens sold for each affiliate ID.

  • addressToAffiliateId: The affiliate ID associated with each address.

  • isFounder: Indicates whether an address is a founder.

Hot Wallet

  • hotwallet: The address of the hot wallet for the presale.

Fixed Funds

  • fixedFundsAmount: The fixed amount of funds (in BNB) reserved for fiat buyers.

Modifiers

Not Paused Modifier

  • notPaused: Throws if the presale is paused.

    • Description: Ensures that the presale is not paused before executing the function.

    • Usage: Apply this modifier to functions that should only be called when the presale is not paused.

    • Example:

      Copy

      modifier notPaused() {
          require(!paused, "Presale is paused");
          _;
      }

Is Paused Modifier

  • isPaused: Throws if the presale is not paused.

    • Description: Ensures that the presale is paused before executing the function.

    • Usage: Apply this modifier to functions that should only be called when the presale is paused.

    • Example:

      Copy

      modifier isPaused() {
          require(paused, "Presale is not paused");
          _;
      }

Events

Price Setter Change Event

  • PriceSetterChange: Emits when the price setter address is changed.

    • Parameters:

      • oldPriceSetter: The address of the old price setter.

      • newPriceSetter: The address of the new price setter.

Price Change Event

  • PriceChange: Emits when the presale token price changes.

    • Parameters:

      • oldPrice: The old price of the presale token.

      • newPrice: The new price of the presale token.

Bought With BNB Event

  • BoughtWithBNB: Emits when presale tokens are bought with BNB.

    • Parameters:

      • buyer: The address of the buyer.

      • affiliateId: The ID of the affiliate.

      • paid: The amount paid in BNB.

      • bought: The amount of presale tokens bought.

Bought With Token Event

  • BoughtWithToken: Emits when presale tokens are bought with another ERC20 token.

    • Parameters:

      • buyer: The address of the buyer.

      • affiliateId: The ID of the affiliate.

      • paid: The amount paid with the token.

      • bought: The amount of presale tokens bought.

Price Updated Event

  • PriceUpdated: Emits when the price tier is updated.

    • Parameters:

      • oldPriceTier: The old price tier.

      • newPriceTier: The new price tier.

Bought With BNB By Fiat Event

  • BoughtWithBNBByFiat: Emits when presale tokens are bought with BNB by fiat.

    • Parameters:

      • caller: The address of the caller.

      • buyer: The address of the buyer.

      • affiliateId: The ID of the affiliate.

      • paid: The amount paid in BNB.

      • bought: The amount of presale tokens bought.

      • sendPresaleTokens: Indicates whether presale tokens were sent to the buyer.

Bought With Token By Fiat Event

  • BoughtWithTokenByFiat: Emits when presale tokens are bought with another ERC20 token by fiat.

    • Parameters:

      • caller: The address of the caller.

      • buyer: The address of the buyer.

      • affiliateId: The ID of the affiliate.

      • paid: The amount paid with the token.

      • bought: The amount of presale tokens bought.

      • sendPresaleTokens: Indicates whether presale tokens were sent to the buyer.

Functions

initialize

Initializes the presale contract with necessary parameters.

Copy

function initialize(
    address _presaleToken,
    address _paidWithToken,
    address _admin,
    address _bnbOracle,
    address _paidWithTokenOracle,
    uint256 _beforePrice,
    uint256 _fromTokenAmount,
    uint256 _afterPrice,
    uint256[] memory _feePercentageDistribution
) public initializer 

Parameters

  • address _presaleToken: The address of the presale token.

  • address _paidWithToken: The address of the token used for payment.

  • address _admin: The address of the admin.

  • address _bnbOracle: The address of the BNB oracle.

  • address _paidWithTokenOracle: The address of the token oracle.

  • uint256 _beforePrice: The price before the presale.

  • uint256 _fromTokenAmount: The amount of tokens available for presale.

  • uint256 _afterPrice: The price after the presale.

  • uint256[] memory _feePercentageDistribution: An array of fee percentage distribution.

Modifiers

  • initializer: Ensures that the function is only called during contract initialization.

Returns

None


_authorizeUpgrade

Internal function for upgrading proxy contract to the newImplementation addrress.

Copy

function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • address newImplementation: The address of the new implementation.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the default admin role.

Returns

None


setHotWallet

Sets the address of the hot wallet.

Copy

function setHotWallet(address _newHotWallet) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • address _newHotWallet: The address of the hot wallet.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setFixedFundsAmount

Sets the fixed funds amount. Upon execution, the function updates the fixedFundsAmount variable with the specified _amount. This variable is subsequently utilized in transactions where tokens are purchased "byfiat" (buyTokensWithTokenByFiat and buyTokensWithBNBByFiat) ensuring that buyers receive the designated fixed funds along with their token allocations.

Copy

function setFixedFundsAmount(uint256 _amount) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint256 _amount: The fixed funds amount.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setPresaleToken

Sets the presale ERC20 token address.

Copy

function setPresaleToken(address _presaleToken) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • address _presaleToken: The address of the presale token.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setMaxLevel

Sets the maximum level.

Copy

function setMaxLevel(uint8 _maxLevel) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint8 _maxLevel: The maximum level.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setPaidWithToken

Sets the ERC20 token used for payment.

Copy

function setPaidWithToken(address _paidWithToken) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • address _paidWithToken: The address of the token used for payment.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


pause

Pauses the presale contract.

Copy

function pause() external onlyRole(DEFAULT_ADMIN_ROLE)

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


unpause

Unpauses the presale contract.

Copy

function unpause() external onlyRole(DEFAULT_ADMIN_ROLE)

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setPaidWithRatioInPersent

This function configures the allocation percentage for affiliate bonuses between the paidWith and presale tokens. When paidWithRatioInPersent is set to 0, affiliate bonuses will be exclusively provided in presale tokens. Conversely, if paidWithRatioInPersent is set to PERCENTAGE_DENOMINATOR (10^7), affiliate bonuses will be exclusively provided in paidWith tokens.

Copy

function setPaidWithRatioInPersent(uint256 _paidWithRatioInPersent) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint256 _paidWithRatioInPersent: The paid with ratio persentage between paidWith and presale tokens used for affiliate rewards (bonuses).

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setMinimumPurchasesForTheBonus

This function allows the administrator of the presale contract to set the minimum purchase amounts required to qualify for bonuses. By specifying _minPurchaseAmount, which represents the minimum purchase amount in USD (United States Dollars), and _minChildPurchaseAmount, indicating the minimum purchase amount for affiliates' children, the administrator can tailor the bonus criteria to align with the presale's objectives.

The flexibility provided by this function enables the presale contract to incentivize larger purchases while also ensuring that affiliates and their referred buyers meet specific minimum thresholds to qualify for bonuses. By adjusting these parameters, the presale contract can effectively manage bonus distributions and promote desirable purchasing behaviors among participants.

Access to this function is restricted to users with the DEFAULT_ADMIN_ROLE, ensuring that only authorized administrators can modify the minimum purchase requirements. This security measure safeguards the integrity of the presale process and maintains transparency in bonus eligibility criteria. Once the minimum purchase amounts are set, they are stored in the contract state variables minPurchaseAmount and minChildPurchaseAmount for reference during bonus calculations.

Copy

function setMinimumPurchasesForTheBonus(uint256 _minPurchaseAmount, uint256 _minChildPurchaseAmount) public onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint256 _minPurchaseAmount: The minimum number of purchases required to qualify for affiliate bonuses.

  • uint256 _minChildPurchaseAmount: The minimum number of purchases required to be purchased by child affiliates for qualify affiliate bonuses.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


setMinimumChildsReachedDestinationValue

This function enables the presale contract administrator to define the minimum number of children required to achieve a predetermined destination value. The _minChildsReachedDestinationValue parameter specifies the minimum count of children necessary to reach the specified destination value (affiliateIdChildsReachedDestinationValue).

This function is accessible only to users with the DEFAULT_ADMIN_ROLE, ensuring that only authorized administrators can configure the minimum child requirement.

Upon invocation, the contract's minChildsReachedDestinationValue variable is updated with the provided minimum child requirement.

Copy

function setMinimumChildsReachedDestinationValue(uint8 _minChildsReachedDestinationValue) public onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint8 _minChildsReachedDestinationValue: The minimum number of child nodes reached to qualify for the affiliate bonus.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None


updateFeeDistributionArray

This function updates the fee distribution array, which specifies the percentage distribution of fees from the purchased amount. Each affiliate level can have a unique percentage distribution, allowing for flexibility in fee allocation based on affiliate hierarchy.

Copy

function updateFeeDistributionArray(uint256[] memory _feePercentageDistribution) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint256[] memory _feePercentageDistribution: An array containing the updated fee percentage distribution.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None

Example

BSCscan

"updateFeeDistributionArray" tab

Fields
Value

_feePercentageDistribution

[1000000, 500000, 250000, 125000, 62500, 31250, 15625, 15625]

_feePercentageDistribution - this field represents an array of uint256 values, where each value represents the fee percentage (in basis points) allocated to the corresponding affiliate level. The fee percentages are based on a PERCENTAGE_DENOMINATOR constant, which is equal to 10^7.

For example:

  • 10% of the PERCENTAGE_DENOMINATOR (10,000,000) is 1,000,000

  • 5% of the PERCENTAGE_DENOMINATOR (10,000,000) is 500,000

Code

Copy

await presale.updateFeeDistributionArray([1000000, 500000, 250000, 125000, 62500, 31250, 15625, 15625])

updateFeeDistribution

This function updates exactly one position in the fee distribution array (updateFeeDistributionArray).

Copy

function updateFeeDistribution(uint256 _key, uint256 _value) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint256 _key: The key for which the fee distribution needs to be updated.

  • uint256 _value: The new fee percentage for the given address.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None

Example

BSCscan

"updateFeeDistribution" tab

Fields
Value

_key

0

_value

500000

_key- This field represents the key (index) in the fee distribution array for which the fee distribution needs to be updated.

_value - This field represents the new fee percentage for the given key (index). The fee percentage should be provided in basis points relative to the PERCENTAGE_DENOMINATOR, which is 10^7.

For example:

  • 5% of the PERCENTAGE_DENOMINATOR (10,000,000) is 500,000

Code

Copy

await presale.updateFeeDistribution(0, 500000);

updatePriceTier

The function enables users with the DEFAULT_ADMIN_ROLE role to update the price of the presale token. This includes setting the price before reaching a certain threshold of token sales and adjusting the price after surpassing that threshold.

Copy

function updatePriceTier(uint256 _beforePrice, uint256 _fromTokenAmount, uint256 _afterPrice) public onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • uint256 _beforePrice: Represents the price of the presale token before the total number of tokens sold (totalTokenSoldAmount) equals or exceeds the specified _fromTokenAmount.

  • uint256 _fromTokenAmount: Denotes the new target amount of presale tokens to be sold.

  • uint256 _afterPrice: Indicates the price of the presale token after the total number of tokens sold (totalTokenSoldAmount) equals or exceeds the specified _fromTokenAmount.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the admin role.

Returns

None

Example

BSCscan

"updatePriceTier" tab

Fields
Value

_beforePrice

10000000

_fromTokenAmount

20000000000000000000

_afterPrice

20000000

_beforePrice - this field represents the price of the presale token before the total number of tokens sold (totalTokenSoldAmount) equals or exceeds the specified _fromTokenAmount.(USD_DENOMINATOR is equal to 10^6, so 10$ = 10 * 10^6)

_fromTokenAmount - this field indicates the amount of presale tokens to be sold. Presale tokens use decimals of 10^18. Therefore, _fromTokenAmount is also indicated in 10^18 (if you would like to change the price after 20 tokens have been sold, you need to enter 20 * 10^18 as an input).

_afterPrice - this field represents the price of the token after the total number of tokens sold. (USD_DENOMINATOR is equal to 10^6, so 20$ = 20 * 10^6)

Code

Copy

// before price 10$, denominator 10^6
const beforePrice = ethers.utils.parseUnits("10", "mwei");
// after price 20$, denominator 10^6
const afterPrice = ethers.utils.parseUnits("20", "mwei");
const fromTokenAmount = 10;
await presale.updatePriceTier(beforePrice, fromTokenAmount, afterPrice);

addAffiliate

Adds a new affiliate to the contract.

Copy

function addAffiliate(uint256 _newAffiliateId, uint256 _parentAffiliateId, address _newAffiliateAddress) external onlyRole(MANAGER_ROLE)

Parameters

  • uint256 _newAffiliateId: ID of the new affiliate.

  • uint256 _parentAffiliateId: ID of the parent affiliate.

  • address _newAffiliateAddress: Address of the new affiliate.

Parameters

  • onlyRole(MANAGER_ROLE): Restricts the function to be called only by users with the MANAGER_ROLE role.

Returns

None

Example

BSCscan

"addAffiliate" tab

Fields
Value

_newAffiliateId

1

_parentAffiliateId

0

_newAffiliateAddress

0x83190245eca819ff186Da8296aa218f23F059A4c

_newAffiliateId - this field represents the unique identifier for the new affiliate. It should be a uint256 integer

_parentAffiliateId - this field indicates the unique identifier of the parent affiliate under which the new affiliate will be added. It should be a uint256 integer.

_newAffiliateAddress - this field specifies the address of the new affiliate.

Code

Copy

const newAffiliateId = 1;
const parentAffiliateId = 0;
const newAffiliateAddress = "0x00...abc"; // add valid address
await presale.addAffiliate(newAffiliateId, parentAffiliateId, newAffiliateAddress);

updateAffiliate

Updates the address of an existing affiliate.

Copy

function updateAffiliate(uint256 _affiliateId, address _newAffiliateAddress) external onlyRole(MANAGER_ROLE)

Parameters

  • uint256 _affiliateId: ID of the existing affiliate.

  • address _newAffiliateAddress: New address of the affiliate.

Parameters

  • onlyRole(MANAGER_ROLE): Restricts the function to be called only by users with the MANAGER_ROLE role.

Returns

None

Example

BSCscan

"addAffiliate" tab

Fields
Value

_affiliateId

1

_newAffiliateAddress

0x83190245eca819ff186Da8296aa218f23F059A4c

_affiliateId - this field represents the unique identifier for an existing affiliate. It should be a uint256 integer

_newAffiliateAddress - this field specifies the new address of the already exist affiliate.

Code

Copy

const affiliateId = 1;
const newAffiliateAddress = "0x00...bca"; // add valid address
await presale.updateAffiliate(affiliateId, newAffiliateAddress);

updateBNBPriceFeed

Updates the price feed(oracle feed) for BNB (Binance Coin).

Copy

function updateBNBPriceFeed(address _priceFeed) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • address _priceFeed: Address of the new BNB price feed contract.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by users with the DEFAULT_ADMIN_ROLE role.

Returns

None


updatePaidWithTokenPriceFeed

Updates the price feed(oracle) for the token used for payments.

Copy

function updatePaidWithTokenPriceFeed(address _priceFeed) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

address _priceFeed: Address of the new token price feed contract(Oracle).

Modifiers

onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by users with the DEFAULT_ADMIN_ROLE role.

Returns

None


setReceiverOfEarnings

Sets the address of the receiver of earnings. Used for transferring paidWith(both native and ERC20 tokens) to be withdrawed.

Copy

function setReceiverOfEarnings(address payable _receiverOfEarnings) external onlyRole(DEFAULT_ADMIN_ROLE)

Parameters

  • address _receiverOfEarnings: Address of the receiver of earnings.

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by users with the DEFAULT_ADMIN_ROLE role.

Returns

None


setFounder

Sets whether an affiliate is a founder or not. Founders hold a unique privilege where they receive any unallocated affiliate bonuses. In scenarios where the maximum level of affiliate is set to 8, and the number of affiliates before the founder is less than 8, the founder receives all leftover bonuses, ensuring that no bonuses remain unclaimed.

Copy

function setFounder(uint256 _affiliateId, bool _isFounder) external onlyRole(MANAGER_ROLE)

Parameters

  • uint256 _affiliateId: ID of the affiliate.

  • bool _isFounder: Boolean indicating whether the affiliate is a founder or not.

Modifiers

  • onlyRole(MANAGER_ROLE): Restricts the function to be called only by users with the MANAGER_ROLE role.

Returns

None


getPrice

Gets the current price of the presale token.

Copy

function getPrice() public view returns (uint256)

Returns

  • uint256: Current price of the presale token.


buyTokensWithBNB

This function enables users to purchase presale tokens using BNB. The amount of BNB sent by the user is converted to presale tokens based on the current exchange rate and the user's affiliate ID. After the token purchase, affiliate bonuses are distributed accordingly, and the transaction details are emitted through an event.

Copy

function buyTokensWithBNB(uint256 _affiliateId) public payable notPaused nonReentrant

Parameters

  • uint256 _affiliateId: ID of the affiliate.

Modifiers

  • payable: Indicates that this function can receive BNB.

  • notPaused: Ensures that the presale contract is not paused.

  • nonReentrant: Prevents reentrancy attacks.

Returns

None

Example

BSCscan

"buyTokensWithBNB" tab

Fields
Value

buyTokensWithBNB

0.001

_affiliateId

1

buyTokensWithBNB - this field should contain the amount of BNB (native token of Binance Smart Chain) you wish to send for purchasing tokens. The value needs to be provided in ether, with comma separators if the value is a float.(If you want to send 0.001 BNB, you should input 0.001).

_affiliateId - this field is used to specify the affiliate ID as a uint256 integer.

Code

Copy

const affiliateId = 1;
const paidBNB = ethers.utils.parseEther("0.001"); // 0.001 eth
await presale.buyTokensWithBNB(affiliateId, {value: paidBNB});

buyTokensWithToken

With this function, users can buy presale tokens using another ERC20 token. The specified amount of ERC20 tokens is transferred from the user's wallet to the presale contract. The tokens are then converted to presale tokens, and the corresponding affiliate bonuses are distributed. Finally, the transaction details are emitted through an event.

Copy

function buyTokensWithToken(uint256 _paidWithTokenAmount, uint256 _affiliateId) external notPaused nonReentrant

Parameters

  • uint256 _paidWithTokenAmount: The amount of a different token (e.g., BUSD) to be exchanged for presale tokens.

  • uint256 _affiliateId: The ID of the affiliate who referred the buyer. This parameter is required for tracking affiliate bonuses.

Modifiers

  • notPaused: This function can only be executed when the presale is not paused.

  • nonReentrant: This function is protected against reentrancy attacks to prevent reentrant calls.

Returns

None

Example

BSCscan

"buyTokensWithToken" tab

Fields
Value

_paidWithTokenAmount

50000000000000000000

_affiliateId

1

_paidWithTokenAmount - this field represents the amount of USDT tokens being paid, expressed in the smallest unit (wei). For USDT, which has 18 decimals, 1 USDT is equivalent to 10^18 wei. (50 * 10^18 = 50 USDT)

_affiliateId - this field is used to specify the affiliate ID as a uint256 integer.

Code

Copy

// assume that USDT token has decimals 18, which means 1 USDT = 1 * 10^18.
const paidUSDT = ethers.utils.parseUnits("50", "ether"); // 50 USDT
const affiliateId = 1;
await presale.buyTokensWithToken(paidUSDT, affiliateId);

buyTokensWithBNBByFiat

Managers can utilize this function to manually purchase presale tokens on behalf of a buyer using BNB (Binance Coin) as a payment method, enabling a fiat-based acquisition process. This function is particularly beneficial for buyers who wish to participate in the presale but prefer using fiat for their purchase.

Upon invocation, the manager specifies essential parameters including the affiliate Id (_affiliateId), buyer's address (_buyer), and whether the presale tokens should be directly sent to the buyer (_sendPresaleTokens). This function requires the manager role (MANAGER_ROLE) for execution and is only operational when the presale contract is not paused to ensure seamless transactions.

Before processing the transaction, several conditions are verified. Firstly, the buyer's address must be linked to an existing affiliate Id within the presale contract, ensuring that only affiliated buyers can participate in this purchase mechanism. Additionally, the amount of BNB sent must exceed a predefined fixed amount(fixedFundsAmount) which will be provided to the buyer in order for buyer to further transact their tokens (presale / BDCA tokens). In addition, the BNB sent by the manager role corresponds to the affiliate bonuses earned, ensuring transparency and alignment with the affiliate program. By default, the total affiliate bonus is equal to 20% of the total amount sent by buyers. Therefore, the manager will send only 20% of the original buyer amount, along with an additional fixed amount to cover at least one transaction for the buyer.

Finally, an event is emitted to record the transaction details, providing a transparent record of the purchase process. This event contains pertinent information including the addresses of the manager and buyer, affiliate Id, the amount of BNB sent, the corresponding presale token amount, and whether the presale tokens were directly sent to the buyer.

Copy

function buyTokensWithBNBByFiat(uint256 _affiliateId, address _buyer, bool _sendPresaleTokens) public payable onlyRole(MANAGER_ROLE) notPaused nonReentrant

Parameters

  • uint256 _affiliateId: The ID of the affiliate who referred the buyer. This parameter is required for tracking affiliate bonuses.

  • address _buyer: The address of the buyer who will receive the presale tokens.

  • bool _sendPresaleTokens: A boolean flag indicating whether the presale token(BDCA) should be send from contract(Presale) to the _buyer address.

Modifiers

  • onlyRole(MANAGER_ROLE): Restricts the function to be called only by users with the manager role.

  • notPaused: This function can only be executed when the presale is not paused.

  • nonReentrant: This function is protected against reentrancy attacks to prevent reentrant calls.

Returns

None

Example

BSCscan

"buyTokensWithBNBByFiat" tab

Fields
Value

buyTokensWithBNBByFiat

0.001

_affiliateId

1

_buyer

0x83190245eca819ff186Da8296aa218f23F059A4c

_sendPresaleTokens

false

buyTokensWithBNBByFiat - this field should contain the amount of BNB (native token of Binance Smart Chain) you wish to send for purchasing tokens. The value needs to be provided in ether, with comma separators if the value is a float(If you want to send 0.001 BNB, you should input 0.001). By default, the total affiliate bonus is equal to 20% of the total amount sent by buyers. Therefore, the manager will send only 20% of the original buyer amount, along with an additional fixed amount fixedFundsAmount to cover at least one transaction for the buyer.

_affiliateId - this field is used to specify the affiliate ID as a uint256 integer.

_buyer - this field is used to specify the address of the buyer who will receive the tokens.

_sendPresaleTokens - this boolean field indicates whether or not to send presale tokens(BDCA) to the _buyer address.

Code

Copy

const affiliateId = 1;
const buyerAddress = "0x00...abc"; // add valid address
const sendPresaleTokens = false; // will not send BDCA tokens to the buyer address
const paidBNB = ethers.utils.parseEther("0.001"); // 0.001 eth
await presale.buyTokensWithBNBByFiat(
    affiliateId,
    buyerAddress,
    sendPresaleTokens,
    {value: paidBNB}
);

buyTokensWithTokenByFiat

Managers can utilize this function to facilitate the purchase of presale tokens using another ERC20 token (by default USDT) as a payment method, enabling a fiat-based acquisition process. This function is particularly beneficial for buyers who wish to participate in the presale but prefer using fiat for their purchase.

Upon invocation, the manager specifies essential parameters including the amount of ERC20 token (_paidWithTokenAmount), the affiliate Id (_affiliateId), buyer's address (_buyer), and whether the presale tokens should be directly sent to the buyer (_sendPresaleTokens). This function requires the manager role (MANAGER_ROLE) for execution and is only operational when the presale contract is not paused to ensure seamless transactions.

Before processing the transaction, several conditions are verified. Firstly, the buyer's address must be linked to an existing affiliate Id within the presale contract, ensuring that only affiliated buyers can participate in this purchase mechanism. Additionally, the amount of BNB sent must be equal the predefined fixed amount (fixedFundsAmount), which will be provided to the buyer in order for the buyer to further transact their tokens (presale / BDCA tokens), and any excess amount will be refunded to the manager who invoked the function. In addition, any excess BNB sent by the manager role corresponds to the affiliate bonuses earned, ensuring transparency and alignment with the affiliate program. By default, the total affiliate bonus is equal to 20% of the total amount sent by buyers. Therefore, the manager will send only 20% of the original buyer amount in ERC20 tokens, along with an additional fixed amount to cover at least one transaction for the buyer.

Finally, an event is emitted to record the transaction details, providing a transparent record of the purchase process. This event contains pertinent information including the addresses of the manager and buyer, affiliate Id, the amount of ERC20 tokens sent, the corresponding presale token amount, and whether the presale tokens were directly sent to the buyer.

Copy

function buyTokensWithTokenByFiat(uint256 _paidWithTokenAmount, uint256 _affiliateId, address _buyer, bool _sendPresaleTokens) external

Parameters

  • uint256 _paidWithTokenAmount: The amount of a different token (USDT) to be exchanged for presale tokens.

  • uint256 _affiliateId: The ID of the affiliate who referred the buyer. This parameter is required for tracking affiliate bonuses.

  • address _buyer: The address of the buyer who will receive the presale tokens.

  • bool _sendPresaleTokens: A boolean flag indicating whether the presale token(BDCA) should be send from contract(Presale) to the _buyer address.

Modifiers

  • onlyRole(MANAGER_ROLE): Restricts the function to be called only by users with the manager role.

  • notPaused: This function can only be executed when the presale is not paused.

  • nonReentrant: This function is protected against reentrancy attacks to prevent reentrant calls.

Returns

None

Example

BSCscan

"buyTokensWithTokenByFiat" tab

Fields
Value

buyTokensWithTokenByFiat

0.001

_paidWithTokenAmount

50000000000000000000

_affiliateId

1

_buyer

0x83190245eca819ff186Da8296aa218f23F059A4c

_sendPresaleTokens

true

buyTokensWithTokenByFiat - this field should contain the fixed amount(fixedFundsAmount) of BNB (native token of Binance Smart Chain) to cover at least one transaction for the buyer.

_paidWithTokenAmount - this field represents the amount of USDT tokens being paid, expressed in the smallest unit (wei). For USDT, which has 18 decimals, 1 USDT is equivalent to 10^18 wei. (50 * 10^18 = 50 USDT)

_affiliateId - this field is used to specify the affiliate ID as a uint256 integer.

_buyer - this field is used to specify the address of the buyer who will receive the tokens.

_sendPresaleTokens - this boolean field indicates whether or not to send presale tokens(BDCA) to the _buyer address.

Code

Copy

// assume that USDT token has decimals 18, which means 1 USDT = 1 * 10^18.
const paidUSDT = ethers.utils.parseUnits("50", "ethers"); // 50 USDT
const affiliateId = 1;
const buyerAddress = "0x00...abc"; // add valid address
const sendPresaleTokens = true; // will send BDCA tokens to the buyer address
await presale.buyTokensWithTokenByFiat(
    paidUSDT,
    affiliateId,
    buyerAddress,
    sendPresaleTokens
);

bnbToPresaleToken

Calculates the amount of presale tokens that can be purchased with a specified amount of BNB.

Copy

function bnbToPresaleToken(uint256 _bnbAmount) external view returns(uint256)

Parameters

  • uint256 _bnbAmount: The amount of BNB for which to calculate the equivalent amount of presale tokens.

Returns

  • uint256: The calculated amount of presale tokens that can be purchased with the specified amount of BNB.


paidWithTokenToPresaleToken

This function allows users to a convert a specified amount of the ERC20 token paidWith to an equivalent amount of presale tokens. It calculates and returns the equivalent presale token amount based on the paidWith token's exchange rate.

Copy

function paidWithTokenToPresaleToken(uint256 _paidWithAmount) external view returns(uint256)

Parameters

  • uint256 _paidWithAmount: The amount of the ERC20 token paidWith to convert to presale tokens.

Returns

  • uint256: The equivalent amount of presale tokens based on the paidWith token amount.


withdraw

This function allows the designated receiverOfEarnings address to withdraw the remaining BNB and paidWith tokens from the contract. It transfers the BNB balance to the receiverOfEarnings address and the paidWith token balance if any.

Copy

function withdraw() external

Returns

None


rescuePresaleTokens

This function enables the contract owner (with the DEFAULT_ADMIN_ROLE) to rescue any remaining presale tokens in the contract if necessary. It transfers the remaining presale tokens to the contract owner's address.

Copy

function rescuePresaleTokens() external onlyRole(DEFAULT_ADMIN_ROLE) isPaused

Modifiers

  • onlyRole(DEFAULT_ADMIN_ROLE): Restricts the function to be called only by the contract owner with the DEFAULT_ADMIN_ROLE. isPaused: Ensures that the function can only be called when the contract is paused.

Returns

None


_releasePresaleTokens

This internal function releases presale tokens to the specified affiliate based on the paid amount and affiliate ID provided. It calculates and returns the amount of presale tokens released to the affiliate.

Copy

function _releasePresaleTokens(uint256 _paidAmount, uint256 _affiliateId) internal returns(uint256)

Parameters

  • uint256 _paidAmount: The amount paid by the user.

  • uint256 _affiliateId: The ID of the affiliate receiving the presale tokens.

Returns

  • uint256: The amount of presale tokens released to the affiliate.


_calculateTokensToReceive

This internal function calculates the number of presale tokens a user will receive based on the specified amount and price.

Copy

function _calculateTokensToReceive(uint256 _amount, uint256 _price) private pure returns (uint256)

Parameters

  • uint256 _amount: The amount of tokens or currency used for the purchase.

  • uint256 _price: The price of the presale token.

Returns

  • uint256: The number of presale tokens a user will receive based on the specified amount and price.


_provideAffiliationPercentages

This internal function calculates and provides affiliate bonuses to the affiliates involved in the presale token purchase. It distributes the bonuses based on the specified fee percentage distribution and the ratio of payments made with BNB or another token.

Copy

function _provideAffiliationPercentages(uint256 _paidWithAmount, uint256 _presaleAmount, uint256 _affiliateId, bool _isBuyingInBNB) internal

Parameters

  • uint256 _paidWithAmount: The amount paid with BNB or ERC20 token.

  • uint256 _presaleAmount: The amount of presale tokens released.

  • uint256 _affiliateId: The ID of the affiliate receiving the bonus.

  • bool _isBuyingInBNB: Flag indicating whether the purchase is made with BNB.

Returns

None


_totalFeePercentageDistribution

This internal function calculates the total fee percentage distribution used for the affiliate bonus calculations.

Copy

function _totalFeePercentageDistribution() internal view returns(uint256)

Returns

  • uint256: The total fee percentage distribution.


_provideFundsForBuyer

This internal function transfers the fixed funds amount to the buyer after a successful presale token purchase.

Copy

function _provideFundsForBuyer(address _buyer) internal

Parameters

  • address _buyer: The address of the buyer.

Returns

None


_feeCalculator

This internal function calculates the fee based on the specified amount, fee percentage, and ratio.

Copy

function _feeCalculator(uint256 _amount, uint256 _feePercentage, uint256 _ratio) internal pure returns(uint256)

Parameters

  • uint256 _amount: The amount used for fee calculation.

  • uint256 _feePercentage: The fee percentage.

  • uint256 _ratio: The ratio used in fee calculation.

Returns

  • uint256: The calculated fee.


_bnbToPayToken

This internal function converts the BNB value to an equivalent amount of presale tokens based on the BNB price.

Copy

function _bnbToPayToken(uint256 _value) internal view returns (uint256)

Parameters

  • uint256 _value: The BNB value to convert.

Returns

  • uint256: The equivalent amount of presale tokens.


_paidWithTokenToPayToken

This internal function converts the value of tokens used for payment to an equivalent amount of presale tokens based on the price of the token used for payment.

Copy

function _paidWithTokenToPayToken(uint256 _value) internal view returns (uint256)

Parameters:

_value: The value of the token used for payment.

Returns

  • uint256: The equivalent amount of presale tokens.


_getBNBPrice

This private function retrieves the latest BNB price from the BNB price feed.

Copy

function _getBNBPrice() private view returns (uint256)

Returns

  • uint256: The latest BNB price.


_getPaidWithTokenPrice

This private function retrieves the latest price of the token used for payment from the token price feed.

Copy

function _getPaidWithTokenPrice() private view returns (uint256)

Returns

  • uint256: The latest price of the token used for payment.