# Meet TokensFarm

TokensFarm is a Farm-as-a-Service provider offering off-the-shelf farms that can be live within minutes!

{% embed url="<https://youtu.be/EZL7vQ-Nmqo>" %}

> ## **What is TokensFarm?**
>
> TokensFarm is a cross-chain Farms-As-A-Service provider offering deployable farms that can be live within hours. It provides an easy-to-use interface, allows projects to incentivize liquidity, and strengthens token and project stability while gaining exposure to TokensFarm hundred of thousands of followers and users. TokensFarm supports all EVM chains & DEXs and doesn’t require coding or integrations. &#x20;
>
> At the same time, it enables crypto investors to have a one-stop shop to earn a yield on different tokens, lowering the entry barrier to DeFi space.
>
> ## Products
>
> TokensFarm currently offers a variety of products, with more under development.
>
> **Staking Farms** - Staking farms allow crypto projects to reward their community for locking tokens on a dynamic APY contract. The contract is fully customizable. Before deployment, the project’s team will decide its duration, reward amount, rate, design, and other functionalities. Staking farms can reduce selling pressure and reward a community for holding faithfully.
>
> **LP Farms** - Liquidity pool farming tends to be commonly referred to as LP farming. It helps grow liquidity for any token on any DEX by staking LP tokens with a dynamic APY. TokensFarm offers multi-dex support for maximum exposure. In addition, TokensFarm’s team assists with deploying the LP farm’s contract, analyzes the metrics, and assists with marketing.
>
> **Uniswap V3 LP Farms** - TokensFarm has recently enabled LP Farms on UniSwap V3. LP providers can now allocate their assets within specific price ranges, enhancing capital utilization and reducing impermanent loss risks. Using TokensFarm’s Uniswap V3 LP farms, you can incentivize token holders to provide liquidity to a trading pair on Uniswap V3.
>
> **Vesting Contracts** - Vesting contracts allow teams to distribute tokens automatically via a smart contract to preapproved, whitelisted addresses. Furthermore, users can preselect their desired chain and claim it automatically. Currently, TokensFarm offers three different types of vesting contracts: Ongoing, Airdrop, and custom.
>
> * Ongoing vesting contracts provide linear vesting on a pre-defined duration, block by block.
> * AirDrop vesting contracts unlock all tokens at once and are claimable on a specific date.
> * Custom vesting contracts are Iterative—the team defines a pre-defined number of batches and days between each batch.
>
> ## TokensFarm’s History & Achievements
>
> TokensFarm was established during the summer of 2021 by the Decentralab Team. Our mission is to make the somewhat complex world of blockchain technology easy and accessible. As such, we’ve created TokensFarm, which makes the complicated task of creating and deploying yield farms simple. Additionally, TokenFarm’s marketplace features many different farms from different projects that farmers can participate in.&#x20;
>
> In the year since TokensFarm’s launch, we’ve reached some impressive milestones that include:
>
> * 100+ Farms
>
> * $40M+ Total Value Locked (TVL)
>
> * 100K Monthly Users
>
> * 3 farms Average per Project
>
> * 73% of clients return
>
> * $1,1M Average ATH TVL per farm
>
> ## About Dcentralab
>
> Dcentralab was founded in 2017 to create an ecosystem of on-chain products designed to accelerate blockchain mass adoption. To date, we’ve developed four different products, including ChainPort and TokensFarm. Decentralab’s products produce value, increase transparency, and lead the decentralized revolution.&#x20;


# Our Products

Staking farms, LP farms, Perpetual Staking, Vesting Contracts and more to come!

## Staking Farm

One of the more popular types of farms at TokensFarm is staking farms. Teams behind crypto projects can easily deploy one to reward their community for holding their token. The team can choose the number of tokens or amount they’d like to reward their community with and the duration of the farm. In addition, TokensFarm supports all major EVM chains so that TokensFarm can support nearly all tokens.&#x20;

Participants from the community can choose to stake their tokens from the project on a farm for a duration. The participants are rewarded with tokens for staking their tokens for a fixed period. Typically, the token reward is the same token as the token staked. However, A project can choose to reward farmers with other tokens. &#x20;

The APY awarded to the farm’s participants is dynamic. It depends on the amount the team allocated to the farm and, more importantly, the number of participants. The more participants the farm has, the fewer rewards the participants will receive and vice-versa. &#x20;

#### Check out this tutorial video to understand how it works!&#x20;

{% embed url="<https://www.youtube.com/watch?t=21s&v=n03wiqWC6_s>" %}

## Perpetual Staking Farms

Similar to a regular staking farm but without a set duration or expiry date. It is an ongoing staking farm for tokens that can incentivize a community to hodl for more extended periods.

### The Benefits of Launching a Staking Farm

Launching a staking farm has multiple benefits to a project and its community. Benefits can include a reduced circulating supply, increased enthusiasm within a token’s community, and interest from non-holders.&#x20;

Crypto projects that have deployed staking farms on TokensFarm have seen a vast reduction in their token’s circulating supply.

The project will also feature in TokensFarm’s farming marketplace. The marketplace receives over 90,000 views per month from DeFi enthusiasts and farmers. In addition, each farm has a convenient “Get Token” button. The “Get Token” button allows users who have yet to own a particular token to purchase it quickly and stake it on the platform.     &#x20;

### Customizable Metrics and Design

TokensFarm’s farms and contracts are fully customizable to fit every project

Customize your farm with the following settings:

* Duration
* Minimum staking time requirements
* Warm-up and cool-down features
* Reward participants with a different token
* Permit early withdrawals or set penalties
* Select your farm’s colors, logo, and images

## LP Farm (Liquidity Pool) <a href="#lp-farm" id="lp-farm"></a>

In addition to staking farms, TokensFarm offers liquidity pool farms, also known as LP Farms. LP farms are also deployable within hours. This type of farm rewards participants that provide liquidity for a particular pair of tokens on a specific DEX (e.g., HORD/BUSD on PancakeSwap).

Participants that provide liquidity on a DEX receive LP tokens representing their stake in the liquidity pool. These LP tokens are staked on an LP farm on TokensFarm in exchange for rewards. The rewards are selected and provided by the crypto project which launched the farm. Usually, rewards take the form of one of the tokens within the LP pair, although a project can reward farmers with a different token. LP farms incentivize liquidity providers to provide liquidity continuously on a DEX.&#x20;

TokensFarm supports all major DEXs, and crypto projects can select their DEX of preference. The project chooses the crypto pair and can choose nearly any pair. The most common choice is their native token and a common stablecoin.    &#x20;

Similar to the staking farms, LP farms also feature a dynamic APY. Dynamic APY means that the fewer participants a farm has, the higher the number of rewards they will receive. With dynamic APY, the opposite is also correct, and the more participants a farm has, the fewer the rewards.    &#x20;

#### Check out this tutorial video to understand how it works!&#x20;

{% embed url="<https://www.youtube.com/watch?v=YRnIxyvxlO4>" %}

### Uniswap V3 LP Farms

Uniswap V3 pools have revolutionized DeFi, and TokensFarm now supports LP farms for these advanced liquidity pools. With Uniswap V3, liquidity providers can concentrate assets within specific price ranges, optimizing capital utilization and enhancing liquidity efficiency. Price ranges reduce the risk of impermanent loss, a top concern for liquidity providers.&#x20;

TokensFarm is committed to serving the evolving DeFi community, and our Uniswap V3 LP Farms offer users dynamic APYs and rewarding liquidity provision. Notable features include:

Customizable Tier Fees: Projects can select tier fees aligned with their liquidity requirements, enabling tailored liquidity provision.

NFT-based Staking: Users stake multiple NFTs, each representing a specific price range. APY rewards are earned only within designated ranges, ensuring efficiency and market alignment.

Uniswap V3 LP Farms share common features with regular LP farms, including rewards in any token, configurable minimum staking time, and flexible early withdrawal options.

### The Benefits of Launching an LP Farm

Launching an LP farm has many different benefits for the project and the token’s community. As the name suggests, it greatly increases a token's liquidity.&#x20;

In our case study, a crypto project called Opulous launched an LP farm via TokensFarm. According to the study, liquidity grew by over 900% in a 55-day timeframe. In a US Dollar based equivalent, liquidity increased from $830,000 to $8,400,000 with 55 days. In addition to this, OPUL’s trading volume also increased drastically.&#x20;

## Multichain Vesting Contracts

There is a bit of a difference between the two farm types of farms listed above and vesting contracts. LP and staking farms reward their community for staking or providing liquidity. Vesting contracts, however, release the portion of tokens belonging to either the projects team and/or early investors.&#x20;

Within TokensFarm vesting contracts, there are several different release methods:

[Ongoing](https://www.youtube.com/watch?v=X5gUN5qFGf4\&t=6s)[<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/YouTube_full-color_icon_%282017%29.svg/159px-YouTube_full-color_icon_%282017%29.svg.png" alt="קובץ:YouTube full-color icon (2017).svg" data-size="line">](https://www.youtube.com/watch?v=X5gUN5qFGf4\&t=6s) - In an ongoing vesting contract, the tokens are distributed all the time, block by block. Tokens are being released every second and can be claimed whenever a user wants, as the counter will keep going up. Note: another name for this is called linear vesting contract).&#x20;

[Custom](https://www.youtube.com/watch?v=BPnEgaTyLx8\&t=2s)<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/YouTube_full-color_icon_%282017%29.svg/159px-YouTube_full-color_icon_%282017%29.svg.png" alt="קובץ:YouTube full-color icon (2017).svg" data-size="line"> - In a custom vesting contract, the tokens are distributed in batches (portions), and the time between each batch is also pre-defined by the project. Tokens are being released only at the time and amount that the project decides. So a user can claim tokens according to the time set. (Note: another name for this is called iterative vesting contract).

[AirDrop](https://www.youtube.com/watch?v=U9mtXliSoak)<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/YouTube_full-color_icon_%282017%29.svg/159px-YouTube_full-color_icon_%282017%29.svg.png" alt="קובץ:YouTube full-color icon (2017).svg" data-size="line"> -  In an Airdrop vesting contract, the tokens are distributed all together, only one time.  The project will set the date, time, the amount of rewards, and the addresses that are eligible.&#x20;

All vesting contracts are fully customizable and adaptable to crypto projects' needs.

### The Benefits of Using Vesting Contracts

There are many different perks for projects to use TokensFarm’s vesting contracts. Benefits include increased transparency with a token’s management and growing trust. It also helps projects to avoid errors by using whitelisted addresses only. It can also help a project avoid a mass sale of tokens from the project’s end or by a team member.&#x20;

### Partial funding

Partial funding is a functionality that allows a project to place a portion of its vesting rewards in a contract. The minimum required funding is 5% of the total vesting amount. The team can later add more tokens to the smart contract during the vesting period.&#x20;

Partial funding enables projects to use their tokens for other usages. Additionally, crypto projects can use it to present a lower circulating supply or avoid unlikely contract issues.&#x20;

Distribution will cease if the tokens within the contract have been depleted before the scheduled end of the contract. The reactivation time and costs of the contract are identical to the launch of a new contract.

##


# Features

TokensFarm’s complete service includes listing on our marketplace, secured contract, cross-chain interoperability, UI Customization, and Live Human Support.

### TokensFarm Supported Chains

We support all EVMs compatible blockchains such as Ethereum, BNB, Polygon, Avalanche, Moon River, Fantom, and many more. View the complete list on our[ about page](https://about.tokensfarm.com/). Can’t locate the chain that you want? Contact us via email at <hello@tokensfarm.com>.

### Cool-down / Warm-up Options

The Cool-Down feature is a pre-set waiting period from when the farmer requests a withdrawal of their staked tokens until they can receive them. The withdrawal consists of two actions - activation of the withdrawal and the withdrawal action after the cool-down period ends.

The warm-up feature is a pre-set waiting period from when a farmer stakes tokens until they start earning APY. The rewards are automatically added to the farmer’s staked balance once the set number of warm-up days is over.

### Dynamic APY

Both TokensFarms LP farms and staking farms make use of a dynamic APY. The Dynamic APY calculates and adjusts the APY based on the number of farm participants and the number of tokens or TVL locked.

The fewer participants a farm has, the greater the rewards. Dynamic APY also works in vice versa, and the larger number of participants a farm has, the lower the APY. Currently, there is no limit to the number of participants using an LP or staking farm.

### **Security**

TokensFarm puts a heavy emphasis on security and understands its profound importance. As such, TokensFarm’s contracts have undergone a minimum of two independent audits. These audits were conducted by the biggest names in the world of blockchain security. For more information on the audits, please see the following links: [Certik audit](https://www.certik.com/projects/tokensfarm), [Zokyo audit](https://www.google.com/url?q=https://drive.google.com/file/d/1YyPfL9BJLQhiPi1bgHtnRrMbNJeklX0A/view\&sa=D\&source=docs\&ust=1662246281890013\&usg=AOvVaw0y23QnJFAOwFTB5agGYsm-).

### **Marketplace**

All LP farms and staking farms hosted on TokensFarm will be featured on TokensFarm’s marketplace. The marketplace is prominently featured on TokensFarm’s main page and includes dozens of active farms. TokensFarm’s website typically receives over 90k unique visitors per month. TokensFarm’s visitors usually have a lot of knowledge and interest regarding cryptocurrencies.

In addition, each farm, active or inactive, includes a “Get \_\_\_\_\_ Tokens.” The blank space is, of course, replaced with the project’s name. This button is featured on the header and is highly visible. The button allows farming enthusiasts to purchase a token that has a farm easily.

### Live Support

TokensFarm’s website features live support by support representatives. Visitors can leave a message or contact a support bot if a support representative is unavailable. The support bot will assist with the majority of issues a user may have.

We also provide many guides and explanations on how to use TokensFarm, how to deploy farms and other valuable information.

### Full Transparency

Transparency is critical when dealing with blockchain technology. TokensFarm’s website lists all details regarding farms and vesting contracts clearly and transparently. The farms clearly state the type of farm, the duration, APY, contract address, minimum requirements, and statistics.

All of the specific details can be easily analyzed and checked.

### TokensFarm White Label

TokensFarm will supply crypto projects with any API endpoint for farms. Available APIs include the dynamic APY, the current TVL, the all-time-high TVL, and more which you can [view here](https://docs.google.com/spreadsheets/d/1ZMp97NPHj4Mx6WiD2Hccp0H1OTL106I-nNuGQn8LEDc/edit?usp=sharing). We can assist with creating and embedment of custom API endpoints as needed. The APIs are embeddable and can be posted on any website as a banner or button.

### $1 Fee Mechanism

Projects can choose to implement an additional \~$1 Tx fee **(**\~$2 on Ethereum) on staking and LP farms. These fees will be accrued and equally redistributed (50 - 50) between the project and TokensFarm.

### Alternative Token Rewards

Alternative token rewards allow projects to reward farmers with tokens different from those associated with the staking or LP farm, which usually is their native token. This feature can be especially useful for dApps or projects with multiple tokens in their ecosystem.


# Launch a Farm for Your Project

What TokensFarm Includes

* Smart-contract deployment & Integration&#x20;
* Fully customizable farm page design
* &#x20;Listing on the TokensFarm Marketplace / Explore section
* &#x20;A token-specific dedicated domain for hosting all of the farms&#x20;
* TokensFarm expert guide on farms' best metrics & publishing&#x20;
* Root smart-contract independent audit&#x20;
* Compatible with seven leading wallets, including MetaMask&#x20;
* Human-managed support bot for all farms&#x20;
* Full QA cycle + Ropsten testing environment&#x20;
* Domain hosting + Cloudflare Security&#x20;
* Full customer support before and after farm creation&#x20;
* Listing of farms on all popular farm aggregators

## Launching Process

<figure><img src="/files/1r8XKXdU3jd3j5oJDPja" alt=""><figcaption></figcaption></figure>

## Farm Extensions

Before a farm ends, a project can choose to extend the farm by adding more rewards. Adding rewards will extend the farm’s duration for a while, depending on the number of tokens added and the farm’s configurations. A project cannot change any other farm parameters following its deployment.

## Farm Pricing

TokensFarm offers transparent pricing for all farms and contracts.

<figure><img src="/files/yp5NHWcsEzoQnpjPm4NB" alt=""><figcaption></figcaption></figure>

## Request a Farm or Contract

Fill out the following form for each type of contract you wish to deploy:

[Launch an LP farm](https://dcentralab.typeform.com/LP-Farm?typeform-source=about.tokensfarm.com)

[Launch a staking farm](https://dcentralab.typeform.com/staking-farm?typeform-source=about.tokensfarm.com)

[Launch a vesting contract](https://dcentralab.typeform.com/tf-vesting?typeform-source=about.tokensfarm.com)


# Using Gnosis Safe

Some explanations how to connect gnosis wallets to Dcentralab apps

## Create Gnosis Safe

First of all you should create a gnosis wallet in <https://gnosis-safe.io/app/welcome> (please keep in mind that gnosis is technically a contract and will be deployed on specified network, so you can't use same wallet in multiple networks and should create on each network another gnosis safe).<br>

<figure><img src="/files/lwG87LW67yHPNOyWdFzd" alt=""><figcaption></figcaption></figure>

During creation you should answer for a few simple question + initialize contract (please notice that this is payable operation and you should have some funds for a network fee)

## Select WalletConnect Safe App

After you have successfully created a gnosis safe you'll be redirected to dashboard. There please select Apps and WalletConnect and follow instructions<br>

<figure><img src="/files/13TifPMXp5wyFGNINX9s" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/z49Yf5euiWb8ll4UB9md" alt=""><figcaption></figcaption></figure>

## Get Tokensfarm WalletConnect Connection Code

Now go to any of our DcentraLab projects (e.g. <https://tokensfarm.com>, <https://app.chainport.io>, <https://www.hord.fi/>) and click Connect Wallet

<figure><img src="/files/mhqDgIdHQABubbYpiPwl" alt="" width="375"><figcaption></figcaption></figure>

Select WalletConnect and Click copy button (if you are on desktop)

<figure><img src="/files/DvXWcedjcqtxRUcRItEp" alt="" width="375"><figcaption></figcaption></figure>

## Paste TokensFarm WalletConnect Connection Code in Safe App

And now you should paste this in your Safe App UI dashboard<br>

<figure><img src="/files/z49Yf5euiWb8ll4UB9md" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/BjVcu6DOChjHZukeMlhL" alt=""><figcaption></figcaption></figure>

## That's It! You're Connected!&#x20;

Go back to TokensFarm app and you should see an active connection with WalletConnect to your gnosis safe.

<figure><img src="/files/ZrwwScmE9gAtrlHZewCY" alt=""><figcaption></figcaption></figure>


# TokensFarmSDK

**INFO** : `TokensFarmSDK.sol` is the contract designed to facilitate the integration of staking systems into other projects. By providing audited code, we empower projects to reward token holders for staking their assets.

\
Integration Process:

* Contract Admin Identification - The client specifies the contract that will manage the SDK (contractAdmin).
* SDK Deployment - Our team deploys the TokensFarmSDK.sol contract, incorporating the provided contract admin address during initialization. This ensures that only authorized parties can manage staking and withdrawal operations.
* Integration Support - We offer a library (SDKFunctionality.sol) and function list to assist with integration. Our development team is available to provide guidance.
* Restricted Access - Functions within SDKFunctionality.sol are exclusively accessible by the designated contract admin.
* Public Information Retrieval - Public getters allow direct access to contract data.<br>


# Getters

Description of all getters

* `getAllPendingStakes`  - it is returning array of all stakes that are waiting to be finalised
* `deposited` - it is returning the deposited amount for specific stake
* `pending` - it is returning the amount that user earned for specific stake&#x20;
* `depositTimestamp` - returning timestamp when specific stake was deposited
* `withdrawTimestamp` - returning timestamp when is the last time when was stake consumed
* `totalPending` - how much was given rewards from beginning till now
* `getNumberOfUserStakes` - number of stakes for user
* `getUserStakesAndPendingAmounts` - it is returning all stakes and all pending amounts for all of the stakes for user

```solidity
* @return array of deposits,pendingAmounts,depositTime and warmupExpirations
```

* getTotalRewardsLockedUnlocked - it is returning rewards that are locked and unlocked
* getStatsForUser - it is returning all necessary info for user

```solidity
* @return totalStakedCurrently
* @return totalEarnedForLifeTime
* @return currentPendingAmount
* @return currentBalanceToWithdraw
```

## List of all getters with their signature

```solidity
function getAllPendingStakes()
function deposited(address _user,uint256 stakeId)
function pending(address _user,uint256 stakeId)
function depositTimestamp(address _user,uint256 stakeId)
function withdrawTimestamp(address _user,uint256 stakeId)
function totalPending()
function getNumberOfUserStakes(address user)
function getUserStakesAndPendingAmounts(address user)
function getTotalRewardsLockedUnlocked()
function getStatsForUser(address _user)
```


# Setters

* In order to change one of these things, through our approved addresses initiating a call, we can change the state of listed params below

```solidity
function setMinTimeToStake(uint256 _minTimeToStake)
function setIsEarlyWithdrawAllowed(bool _isEarlyWithdrawAllowed)
function setWarmup(uint256 _warmup)
```


# Parameters

All public declared parameters act as a getters.\
&#x20;Ex : `uint256 public lastRewardTime` so if you call `TokensFarmSDK.lastRewardTime()`\
you will get timestamp of last time that reward was given

```solidity
    uint256 public lastRewardTime;
    uint256 public accERC20PerShare;
    uint256 public totalDeposits;
    bool public isEarlyWithdrawAllowed;
    uint256 public minTimeToStake;
    IERC20 public rewardToken;
    uint256 public paidOut;
    uint256 public rewardPerSecond;
    uint256 public totalFundedRewards;
    uint256 public totalRewards;
    mapping(address => StakeInfo[]) public stakeInfo;
    uint256 public startTime;
    uint256 public endTime;
    EarlyWithdrawPenalty public penalty;
    uint256 public stakeFeePercent;
    uint256 public rewardFeePercent;
    address payable public feeCollector;
    uint256 public flatFeeAmountDeposit;
    uint256 public flatFeeAmountWithdraw;
    bool public isFlatFeeAllowed;
    uint256 public totalTokensBurned;
    uint256 public totalFeeCollectedETH;
    uint256 public totalFeeCollectedTokens;
    address public farmImplementation;
    uint256 public noOfUsers;
    address[] public participants;
    mapping(address => uint256) public id;
    uint256 public warmupPeriod;
    mapping(address => DepositRequest[]) public depositRequest;
    address[] public waitingList;
    mapping(address => uint256) idInList;
    bool public isInitialisedFully;
    uint256 public firstDepositAt;
    mapping(address => uint256) public totalActiveStakeAmount;
    uint256 public noOfPendingStakes;
    mapping(address => uint256) public totalPendingAmountForUser;
    address public contractAdmin;
    bool public isActive;
    IERC20 public tokenStaked;
    mapping(address => uint256) public lastStakeConsumed;
    mapping(address => uint256) public totalEarnedForUser;
    mapping(address => uint256) public ATHStake;
    mapping(address => uint256) public nextStakeToFinalise;
```


# ISDK.sol

Interface that needs to be implemented into the project in order to use staking helper

In order to fully use this feature, you will have to insert param called farmAddress into your contract admin contract, and make setter for it&#x20;

```solidity
address public farmAddress;
```

```solidity
function setFarmAddress(
    address _farmAddress
) 
    external onlyOnwer 
{ 
    require(_farmAddress != address(0x0));
    farmAddress = _farmAddress;
}
```

```solidity
//"SPDX-License-Identifier: UNLICENSED"
pragma solidity 0.6.12;

interface ISDK {
    // In order to fund the farm you need to call fund

    function makeDepositRequest(
        address _user,
        uint256 _amount
    ) external;

    function finaliseDeposit(
        address user,
        uint256 stakeId
    ) external;

    // If warmup > 0 then these two functions above are used together to deposit

    function deposit(
        address _user,
        uint256 _amount
    ) external;

    // If warmup = 0 then only one function from above is used to deposit

    function ifPaymentCanPassInOneTx(
        address _user,
        uint256 _amount
    ) external view returns(bool);

    // If comes to withdrawal first getter ifPaymentCanPassInOneTx is called (returns true/false)

    function noticeReducedStakeWithoutStakeId(
        address _user,
        uint256 _amount
    ) external;

    // If getter ifPaymentCanPassInOneTx returns true then noticeReducedStakeWithoutStakeId is called

    function provideInfoForWithdrawWithoutStakeId(
        address _user,
        uint256 _amount
    )  external view returns(uint256[] memory, uint256[] memory);

    // If getter ifPaymentCanPassInOneTx returns false then provideInfoForWithdrawWithoutStakeId is called
    // provideInfoForWithdrawWithoutStakeId is returning array of stakes and stakes amount that should be
    // taken from each stake

    function noticeReducedStake(
        address _user,
        uint256 _amount,
        uint256 stakeId
    ) external;

    // And then you have all the info for which stakes and for what amount to call multiple times noticeReducedStake

    function withdrawRewards(
        address _user
    ) external;

    // To withdraw rewards user can call it directly on the contract but also contract admin can do it
}
```


# Deposit

Instruction how to deposit

* There is two way to make a deposit on contracts, depends if warmup is enabled or not
* If `warmupPeriod == 0` contract admin needs to make a deposit through function called `ISDK(farmAddress).deposit()`

  ```solidity
  function deposit(address _user, uint256 amount)
  ```

  &#x20;After that stake is remembered and user starts earning immediately
* If `warmupPeriod > 0` contract admin needs to make deposit through function called `ISDK(farmAddress).makeDepositRequest`

  ```solidity
  function makeDepositRequest(
     address _user,
     uint256 amount
  )
  ```

  &#x20;After that `warmupPeriod` needs to pass in order for BE or contract admin to call function `ISDK(farmAddress).finaliseDeposit`&#x20;

  ```solidity
  function finaliseDeposit(
      address _user,    
      uint256 stakeId
  )
  ```

  once that function is executed user can start earning rewards and his stakes i acknowledged&#x20;


# Withdraw

WITHDRAW SYSTEM :

* If yours project wants to take a fee or report unstake from stake of specific user you need to call `ISDK(farmAddress).noticeReducedStakeWithoutStakeId`&#x20;

```solidity
function noticeReducedStakeWithoutStakeId( 
    address _user,   
    uint256 _amount
)
```

* Once the stake was updated to new state there is mapping called&#x20;

  ```solidity
  mapping(address => uint256) public totalPendingAmountForUser;
  ```

that after `noticeReducedStakeWithoutStakeId` was called, contains newly collected rewards that stake that was updated was earning during staking time.

* In order for user to collect those collected rewards from `totalPendingAmountForUser` he can call directly from contract `TokensFarmSDK.withdrawRewards(msg.sender)` or you can execute withdraw from contract admin through `ISDK(farmAddress).withdrawRewards(addressOfUser)`


# Integrate TokensFarm

Integrate your app and/or server directly with TokensFarm

## Before Getting Started

Production API URL:

```
https://api.tokensfarm.com/
```

Staging API URL:

```
https://staging-api.tokensfarm.com/
```


# Requesting Farm Data

The Farm List is a list of objects that contain relevant data regarding all farms that exist in the TokensFarm ecosystem

## API Calls for all Farms

## Get all farms list

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/list`

#### Path Parameters

| Name       | Type    | Description                                                                                                |
| ---------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| active     | boolean | get only active/ended farms                                                                                |
| sort       | String  | <p>sort=apy -order by apy</p><p>sort=newest - order by date</p><p>sort=days\_left - order by days left</p> |
| page       | Integer | get data by page number                                                                                    |
| farm\_type | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p><p></p>                            |
| token      | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                        |
| page\_size | Integer | the amount of farm objects in a page                                                                       |
| full       | boolean | if "true" will return a larger farm object with more data                                                  |
| view       | String  | example: tile                                                                                              |
| chain      | String  | <p>the chain we want to look for farms at.</p><p>input options: ethereum/binance/polygon</p>               |

{% tabs %}
{% tab title="200 Farms info successfully fetched" %}

```javascript
{
  "farms": [
    {
      "farmLiquidity": 3632131.2221367313,
      "endTime": "2022-05-14T00:40:51+00:00",
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/copi/3s/2/banner.jpg",
      "active": true,
      "vestingType": null,
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 4890477.9825967625,
      "network": {
        "chainName": "binance",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "id": 3,
        "etherscanLink": "https://bscscan.com",
        "factoryGitTag": "master-v0.1.0",
        "networkName": "bsc-mainnet",
        "rpcUrl": "https://bsc-dataseed.binance.org"
      },
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/copi/3s/2/share_image.jpg",
      "symbol": "COPI",
      "vestingPortion": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/copi/3s/2/logo.jpg",
      "id": 70,
      "nonce": "2",
      "startTime": "2022-02-10T16:57:23+00:00",
      "apy": 7.035855449421467,
      "websiteLink": "https://cornucopias.io",
      "projectName": "Cornucopias",
      "type": "STAKING"
    },
    {
      "farmLiquidity": 517847.4872704626,
      "endTime": "2022-02-27T04:15:29+00:00",
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/xcad/lp/1/banner.png",
      "active": false,
      "vestingType": null,
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 2502115.9966024337,
      "network": {
        "chainName": "binance",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "id": 3,
        "etherscanLink": "https://bscscan.com",
        "factoryGitTag": "master-v0.1.0",
        "networkName": "bsc-mainnet",
        "rpcUrl": "https://bsc-dataseed.binance.org"
      },
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/xcad/lp/1/share-image.png",
      "symbol": "XCAD",
      "vestingPortion": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/xcad/lp/1/logo.svg",
      "id": 22,
      "nonce": "3",
      "startTime": "2021-11-18T14:30:09.229000+00:00",
      "apy": 1935.6152852425087,
      "websiteLink": "https://www.xcademytoken.com",
      "projectName": "XCAD",
      "type": "LP"
    },...
  ],
  "pages": {
    "previous_page": null,
    "next_page": 2,
    "has_previous": false,
    "has_next": true,
    "total_records": 72,
    "page_size": 2,
    "current_page": 1,
    "total_pages": 36
  }
}
```

{% endtab %}
{% endtabs %}

## Get active farms list

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/list?active=true`

#### Path Parameters

| Name       | Type    | Description                                                                                                |
| ---------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| active     | boolean | get only active/ended farms                                                                                |
| sort       | String  | <p>sort=apy -order by apy</p><p>sort=newest - order by date</p><p>sort=days\_left - order by days left</p> |
| page       | Integer | get data by page number                                                                                    |
| farm\_type | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p><p></p>                            |
| token      | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                        |
| page\_size | Integer | the amount of farm objects in a page                                                                       |
| full       | boolean | if "true" will return a larger farm object with more data                                                  |
| view       | String  | example: tile                                                                                              |
| chain      | String  | <p>the chain we want to look for farms at.</p><p>input options: ethereum/binance/polygon</p>               |

{% tabs %}
{% tab title="200 Farms info successfully fetched" %}

```javascript
{
  "farms": [
    {
      "apy": 7.035855449421467,
      "vestingPortion": null,
      "nonce": "2",
      "projectName": "Cornucopias",
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 4890477.9825967625,
      "active": true,
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/copi/3s/2/banner.jpg",
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/copi/3s/2/logo.jpg",
      "type": "STAKING",
      "network": {
        "networkName": "bsc-mainnet",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "id": 3,
        "etherscanLink": "https://bscscan.com",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "networkId": 56,
        "factoryGitTag": "master-v0.1.0",
        "chainName": "binance"
      },
      "websiteLink": "https://cornucopias.io",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/copi/3s/2/share_image.jpg",
      "symbol": "COPI",
      "vestingType": null,
      "endTime": "2022-05-14T00:40:51+00:00",
      "id": 70,
      "farmLiquidity": 3647074.898692922,
      "startTime": "2022-02-10T16:57:23+00:00"
    },
    {
      "apy": 71.67932357394619,
      "vestingPortion": null,
      "nonce": "1",
      "projectName": "MetaSoccer",
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 1531297.5523132244,
      "active": true,
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/msu/3s/1/banner.png",
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/msu/3s/1/logo.png",
      "type": "STAKING",
      "network": {
        "networkName": "polygon-mainnet",
        "rpcUrl": "https://polygon-mainnet.infura.io/v3/d00f5394ffca4ef29cfc68fc9a90bf74",
        "factoryProxyAddress": "0x512BeF80308e0F0a813dE68c96Eb702B80A3da10",
        "chainId": "137",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "id": 2,
        "etherscanLink": "https://polygonscan.com",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "networkId": 137,
        "factoryGitTag": "master-v0.1.0",
        "chainName": "polygon"
      },
      "websiteLink": "https://metasoccer.com/",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/msu/3s/1/share_image.png",
      "symbol": "MSU",
      "vestingType": null,
      "endTime": "2022-05-26T12:51:51+00:00",
      "id": 93,
      "farmLiquidity": 1426898.8603975407,
      "startTime": "2022-02-25T12:51:51+00:00"
    },
    {
      "apy": 29.307391884348444,
      "vestingPortion": null,
      "nonce": "1",
      "projectName": "Numbers Protocol",
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 1577975.845589999,
      "active": true,
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/num/3s/1/banner.png",
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/num/3s/1/logo.svg",
      "type": "STAKING",
      "network": {
        "networkName": "bsc-mainnet",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "id": 3,
        "etherscanLink": "https://bscscan.com",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "networkId": 56,
        "factoryGitTag": "master-v0.1.0",
        "chainName": "binance"
      },
      "websiteLink": "https://www.numbersprotocol.io/",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/num/3s/1/share_image.png",
      "symbol": "NUM",
      "vestingType": null,
      "endTime": "2022-04-27T13:46:24+00:00",
      "id": 66,
      "farmLiquidity": 1093587.325891931,
      "startTime": "2022-01-27T13:46:24+00:00"
    },
    {
      "apy": 142.43427124848634,
      "vestingPortion": null,
      "nonce": "2",
      "projectName": "Numbers Protocol",
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 592798.1643238494,
      "active": true,
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/banner.png",
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/logo.svg",
      "type": "LP",
      "network": {
        "networkName": "bsc-mainnet",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "id": 3,
        "etherscanLink": "https://bscscan.com",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "networkId": 56,
        "factoryGitTag": "master-v0.1.0",
        "chainName": "binance"
      },
      "websiteLink": "https://www.numbersprotocol.io",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/share_image.png",
      "symbol": "NUM",
      "vestingType": null,
      "endTime": "2022-04-24T18:10:10+00:00",
      "id": 61,
      "farmLiquidity": 434706.96319200913,
      "startTime": "2022-01-21T08:49:52+00:00"
    },
    {
      "apy": 122.84533141105479,
      "vestingPortion": null,
      "nonce": "4",
      "projectName": "Opulous",
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 448838.96708728105,
      "active": true,
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/opul/lp/4/banner.png",
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/opul/lp/4/logo.svg",
      "type": "LP",
      "network": {
        "networkName": "mainnet",
        "rpcUrl": "https://mainnet.infura.io/v3/d00f5394ffca4ef29cfc68fc9a90bf74",
        "factoryProxyAddress": "0xddac0912E0c3Be0B8C8f201cf33C9EeB2f8B1497",
        "chainId": "1",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "id": 1,
        "etherscanLink": "https://etherscan.io",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "networkId": 1,
        "factoryGitTag": "master-v0.1.0",
        "chainName": "ethereum"
      },
      "websiteLink": "https://www.opulous.org",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/opul/lp/4/share_image.png",
      "symbol": "OPUL",
      "vestingType": null,
      "endTime": "2022-06-05T09:30:39+00:00",
      "id": 91,
      "farmLiquidity": 423522.1924849945,
      "startTime": "2022-02-25T09:01:03+00:00"
    },
    {
      "apy": 27.74445408047816,
      "vestingPortion": null,
      "nonce": "2",
      "projectName": "Brokoli Network",
      "vestingDistributionPeriod": null,
      "farmLiquidityMax": 459443.96936112584,
      "active": true,
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/brkl/3s/2/banner.png",
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/brkl/3s/2/logo.png",
      "type": "STAKING",
      "network": {
        "networkName": "bsc-mainnet",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "id": 3,
        "etherscanLink": "https://bscscan.com",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "networkId": 56,
        "factoryGitTag": "master-v0.1.0",
        "chainName": "binance"
      },
      "websiteLink": "https://brokoli.network",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/brkl/3s/2/share_image.jpeg",
      "symbol": "BRKL",
      "vestingType": null,
      "endTime": "2022-05-05T14:14:01+00:00",
      "id": 64,
      "farmLiquidity": 374253.291275867,
      "startTime": "2022-01-25T14:14:01+00:00"
    },...
  ],
  "pages": null
}
```

{% endtab %}
{% endtabs %}

### Other Useful Examples

## Active LP Farms (Only)

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/list?active=true&farm_type=LP`

Filtered farms by: farm status = active ,farm type = LP

For only staking farms just use: farm\_type=STAKING

#### Path Parameters

| Name       | Type    | Description                                                                                                |
| ---------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| active     | boolean | get only active/ended farms                                                                                |
| sort       | String  | <p>sort=apy -order by apy</p><p>sort=newest - order by date</p><p>sort=days\_left - order by days left</p> |
| page       | Integer | get data by page number                                                                                    |
| farm\_type | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p><p></p>                            |
| token      | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                        |
| page\_size | Integer | the amount of farm objects in a page                                                                       |
| full       | boolean | if "true" will return a larger farm object with more data                                                  |
| view       | String  | example: tile                                                                                              |
| chain      | String  | <p>the chain we want to look for farms at.</p><p>input options: ethereum/binance/polygon</p>               |

{% tabs %}
{% tab title="200 Farms info successfully fetched" %}

```javascript
{
  "farms": [
    {
      "startTime": "2022-01-21T08:49:52+00:00",
      "active": true,
      "symbol": "NUM",
      "endTime": "2022-04-24T18:10:10+00:00",
      "projectName": "Numbers Protocol",
      "vestingDistributionPeriod": null,
      "apy": 137.6832558404504,
      "vestingType": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/logo.svg",
      "id": 61,
      "farmLiquidity": 421913.18798642384,
      "websiteLink": "https://www.numbersprotocol.io",
      "network": {
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryGitTag": "master-v0.1.0",
        "etherscanLink": "https://bscscan.com",
        "chainName": "binance",
        "networkName": "bsc-mainnet",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "id": 3
      },
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/banner.png",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/share_image.png",
      "farmLiquidityMax": 592798.1643238494,
      "type": "LP",
      "vestingPortion": null,
      "nonce": "2"
    },
    {
      "startTime": "2022-01-06T09:16:01+00:00",
      "active": true,
      "symbol": "ENV",
      "endTime": "2022-05-06T09:16:00+00:00",
      "projectName": "ENVOY",
      "vestingDistributionPeriod": null,
      "apy": 300.4611692358352,
      "vestingType": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/logo.png",
      "id": 59,
      "farmLiquidity": 16282.831608913908,
      "websiteLink": "https://envoy.art",
      "network": {
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryGitTag": "master-v0.1.0",
        "etherscanLink": "https://bscscan.com",
        "chainName": "binance",
        "networkName": "bsc-mainnet",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "id": 3
      },
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/banner.png",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/share_image.png",
      "farmLiquidityMax": 337763.32145191595,
      "type": "LP",
      "vestingPortion": null,
      "nonce": "2"
    }
  ],
  "pages": null
}
```

{% endtab %}
{% endtabs %}

## Get active LP and Staking Farms that are deployed on the Binance Chain

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/list?active=true&farm_type=LP,STAKING&chain=binance`

Filtered farms by: farm status = active, farm type = LP or STAKING, deployed chain = BNB chain

#### Path Parameters

| Name       | Type    | Description                                                                                                                                |
| ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| active     | boolean | get only active/ended farms                                                                                                                |
| sort       | String  | <p>sort=apy -order by apy</p><p>sort=newest - order by date</p><p>sort=days\_left - order by days left</p>                                 |
| page       | Integer | get data by page number                                                                                                                    |
| farm\_type | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p><p></p>                                                            |
| token      | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                                                        |
| page\_size | Integer | the amount of farm objects in a page                                                                                                       |
| full       | boolean | if "true" will return a larger farm object with more data                                                                                  |
| view       | String  | example: tile                                                                                                                              |
| chain      | String  | <p>the chain we want to look for farms at.</p><p>the chain we want to look for farms at.</p><p>input options: ethereum/binance/polygon</p> |

{% tabs %}
{% tab title="200 Farms info successfully fetched" %}

```javascript
{
  "farms": [
    {
      "startTime": "2022-01-21T08:49:52+00:00",
      "active": true,
      "symbol": "NUM",
      "endTime": "2022-04-24T18:10:10+00:00",
      "projectName": "Numbers Protocol",
      "vestingDistributionPeriod": null,
      "apy": 137.6832558404504,
      "vestingType": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/logo.svg",
      "id": 61,
      "farmLiquidity": 421913.18798642384,
      "websiteLink": "https://www.numbersprotocol.io",
      "network": {
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryGitTag": "master-v0.1.0",
        "etherscanLink": "https://bscscan.com",
        "chainName": "binance",
        "networkName": "bsc-mainnet",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "id": 3
      },
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/banner.png",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/share_image.png",
      "farmLiquidityMax": 592798.1643238494,
      "type": "LP",
      "vestingPortion": null,
      "nonce": "2"
    },
    {
      "startTime": "2022-01-06T09:16:01+00:00",
      "active": true,
      "symbol": "ENV",
      "endTime": "2022-05-06T09:16:00+00:00",
      "projectName": "ENVOY",
      "vestingDistributionPeriod": null,
      "apy": 300.4611692358352,
      "vestingType": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/logo.png",
      "id": 59,
      "farmLiquidity": 16282.831608913908,
      "websiteLink": "https://envoy.art",
      "network": {
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryGitTag": "master-v0.1.0",
        "etherscanLink": "https://bscscan.com",
        "chainName": "binance",
        "networkName": "bsc-mainnet",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "id": 3
      },
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/banner.png",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/share_image.png",
      "farmLiquidityMax": 337763.32145191595,
      "type": "LP",
      "vestingPortion": null,
      "nonce": "2"
    }
  ],
  "pages": null
}
```

{% endtab %}
{% endtabs %}

## Get farms whose reward tokens are DCD

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/list?token=DCD`

Filtered farms by the reward token address

#### Path Parameters

| Name       | Type    | Description                                                                                                |
| ---------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| active     | boolean | get only active/ended farms                                                                                |
| sort       | String  | <p>sort=apy -order by apy</p><p>sort=newest - order by date</p><p>sort=days\_left - order by days left</p> |
| page       | Integer | get data by page number                                                                                    |
| farm\_type | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p><p></p>                            |
| token      | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                        |
| page\_size | Integer | the amount of farm objects in a page                                                                       |
| full       | boolean | if "true" will return a larger farm object with more data                                                  |
| view       | String  | example: tile                                                                                              |
| chain      | String  | <p>the chain we want to look for farms at.</p><p>input options: ethereum/binance/polygon</p>               |

{% tabs %}
{% tab title="200 Farms info successfully fetched" %}

```javascript
{
  "farms": [
    {
      "startTime": "2022-01-21T08:49:52+00:00",
      "active": true,
      "symbol": "NUM",
      "endTime": "2022-04-24T18:10:10+00:00",
      "projectName": "Numbers Protocol",
      "vestingDistributionPeriod": null,
      "apy": 137.6832558404504,
      "vestingType": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/logo.svg",
      "id": 61,
      "farmLiquidity": 421913.18798642384,
      "websiteLink": "https://www.numbersprotocol.io",
      "network": {
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryGitTag": "master-v0.1.0",
        "etherscanLink": "https://bscscan.com",
        "chainName": "binance",
        "networkName": "bsc-mainnet",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "id": 3
      },
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/banner.png",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/num/lp/2/share_image.png",
      "farmLiquidityMax": 592798.1643238494,
      "type": "LP",
      "vestingPortion": null,
      "nonce": "2"
    },
    {
      "startTime": "2022-01-06T09:16:01+00:00",
      "active": true,
      "symbol": "ENV",
      "endTime": "2022-05-06T09:16:00+00:00",
      "projectName": "ENVOY",
      "vestingDistributionPeriod": null,
      "apy": 300.4611692358352,
      "vestingType": null,
      "logo": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/logo.png",
      "id": 59,
      "farmLiquidity": 16282.831608913908,
      "websiteLink": "https://envoy.art",
      "network": {
        "factoryProxyAddress": "0x827ca5Bfe9b0c90F69A4abCe446F3bcD00D93AbB",
        "networkId": 56,
        "chainId": "56",
        "factoryUpdatedAt": "2022-01-16T12:00:00+00:00",
        "factoryGitTag": "master-v0.1.0",
        "etherscanLink": "https://bscscan.com",
        "chainName": "binance",
        "networkName": "bsc-mainnet",
        "factoryUpdatedGitTag": "2022-01-16T12:00:00+00:00",
        "rpcUrl": "https://bsc-dataseed.binance.org",
        "id": 3
      },
      "banner": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/banner.png",
      "shareImage": "https://s3.amazonaws.com/static.tokensfarm.com/env/lp/2/share_image.png",
      "farmLiquidityMax": 337763.32145191595,
      "type": "LP",
      "vestingPortion": null,
      "nonce": "2"
    }
  ],
  "pages": null
}
```

{% endtab %}
{% endtabs %}


# Get Farm Address and Full Details

In order to participate in the farm and make a deposit, withdrawal, or any other functions, first we need to get the farm address by calling the TokensFarm API

### Get a List of Specific Farms with their Full Details

A farm's address will be included in the full farm details. In order to participate in a farm, you must first get the "full details" object, which will contain the farm's address. The address will allow you to interact with the contract.

{% hint style="info" %}
In the response, you will find the farm address under the field "TokensFarm"
{% endhint %}

## Filter by the token symbol to get full details for all corresponding farms

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/list?token=<token_symbol>&full=true`

will response object with full details on the farm.\
"TokensFarm" parameter on response will contain the address of the farm

#### Path Parameters

| Name       | Type    | Description                                                                                                |
| ---------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| active     | boolean | get only active/ended farms                                                                                |
| sort       | String  | <p>sort=apy -order by apy</p><p>sort=newest - order by date</p><p>sort=days\_left - order by days left</p> |
| page       | Integer | get data by page number                                                                                    |
| farm\_type | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p><p></p>                            |
| token      | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                        |
| page\_size | Integer | the amount of farm objects in a page                                                                       |
| full       | boolean | if "true" will return a larger farm object with more data                                                  |
| view       | String  | example: tile                                                                                              |

{% tabs %}
{% tab title="200: OK Farm full info successfully fetched" %}
response example: <https://api.tokensfarm.com/farm/list?token=DCD&full=true>
{% endtab %}
{% endtabs %}

### Get a Particular Farm's Object with Full Details

## Get a specific farm's object with full details

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/config?symbol=HORD&type=LP&nonce=2`

must be filtered by symbol, type and nonce

#### Path Parameters

| Name   | Type    | Description                                                                                                                             |
| ------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | String  | <p>the symbol of the specific token<br>for example: token=PORTX</p>                                                                     |
| type   | String  | <p>farm\_type=LP,STAKING<br>will return all the lp and staking farms</p>                                                                |
| nonce  | Integer | <p>nonce will be a count of the amount of time farms made for this token.</p><p>you can find a farm nonce with "Get farms list" API</p> |

{% tabs %}
{% tab title="200: OK Farm full info successfully fetched" %}
response example:\
&#x20;<https://api.tokensfarm.com/farm/config?symbol=HORD&type=LP&nonce=2>
{% endtab %}
{% endtabs %}


# Monitoring a Farm's Status

It is possible to monitor a farm's status and fetch specific details through our API calls

## Getting Farm Stats

Farm stats contain all farm deposit dates and amounts

{% hint style="info" %}
Use previous GET farms list API to fetch the farm Id
{% endhint %}

## Getting Token's Price

An API call to get the price feed for the token of a specific farm

## Get the price of the reward token in a specific farm

<mark style="color:blue;">`GET`</mark> `https://api.tokensfarm.com/farm/price`

#### Path Parameters

| Name | Type    | Description                                                           |
| ---- | ------- | --------------------------------------------------------------------- |
|      | integer | <p>The farm Id will can be found by using <br>"Get farm list" API</p> |

{% tabs %}
{% tab title="200: OK Price info successfully fetched" %}

```javascript
{
  "price": 0.487912
}
```

{% endtab %}
{% endtabs %}


# Deposit into a farm

Once you have the farm's address, you may now use the farm's contract to participate and earn rewards.

### Deposit

To deposit into a TokensFarm contract, you must call `deposit` on the `TokensFarm` smart contract.

Notice that it is possible to deposit multiple times.

{% hint style="info" %}
First, make sure to `approve` spend on the ERC20 token that you wish to farm
{% endhint %}

```solidity
function deposit(uint256 _amount)
```

| Parameters | Type      | Description                                             |
| ---------- | --------- | ------------------------------------------------------- |
| Amount     | `uint256` | The amount that the user wishes to deposit to the farm. |

#### Example script for deposit in JS

```javascript
const hre = require("hardhat");
async function main(){    
        const tokensFarmContract = await hre.ethers.getContractAt(
        tokensFarmArtifact.abi,
        "the contracts address here"
        );
        const erc20TokenContract = await hre.ethers.getContractAt(
        erc2-TokenArtifact.abi,
        "the contracts address here"
        );
        let amountToDeposit = 5000;
        //First approve to tokensFarm contract to spend the tokens
        await erc20TokenContract.approve(amountToDeposit);
        //Call deposit function    
        await tokensFarmFactory.deposit(amountToDeposit);
}
```


# Withdraw from a farm

Withdrawing Rewards and staked tokens from a farm contract

### Withdraw

To withdraw from a TokensFarm contract, you must call `withdraw` on the `TokensFarm` smart contract.

{% hint style="info" %}
In order to withdraw, you must first `GET` the Stake ID. go to "Get Stake Ids and Stake Details" bellow
{% endhint %}

```solidity
function withdraw(
        uint256 _amount,
        uint256 stakeId
    )
```

| Parameters | Type      | Description                                          |
| ---------- | --------- | ---------------------------------------------------- |
| \_amount   | `uint256` | the amount the user is wish to withdraw to the farm. |
| stakeId    | `uint256` | the id of the staker                                 |

### Get Stake Ids and Stake Details

To get staking info, pending amounts, and stake IDs from a TokensFarm contract, you must call `getUserStakesAndPendingAmounts` on the `TokensFarm` smart contract.

```solidity
function getUserStakesAndPendingAmounts(address user)
external view returns (uint256[] memory, uint256[] memory, uint256[] memory)
```

| Parameters | Type      | Description                         |
| ---------- | --------- | ----------------------------------- |
| user       | `address` | the user address to get the data on |

returns:

<table><thead><tr><th width="242">Parameters</th><th width="234.9992523364486">Type</th><th>Description</th></tr></thead><tbody><tr><td>deposits</td><td><code>uint256[]</code></td><td>An array of stake Ids for each user deposit.</td></tr><tr><td>pendingAmount</td><td><code>uint256[]</code></td><td>An array of the amount deposited in each stake</td></tr><tr><td>depositeTime</td><td><code>uint256[]</code></td><td>An array of the time each staking occurred</td></tr></tbody></table>

{% hint style="info" %}
if the user has staked only once, then for in order to withdraw this particular stake, insert into the Withdraw Function the stake ID parameter: stakeID `= deposits[0]`, where `deposits` is the array that is returned from the `getUserStakesAndPendingAmounts` function.\
If a user staked multiple times, then you must call the `Withdraw` function multiple times - one for each stake with the following: `stakeId = deposit[0..n]`&#x20;
{% endhint %}

#### Example script for withdrawing

```javascript
const hre = require("hardhat");

async function main(){
    const tokensFarmContract = await hre.ethers.getContractAt(
        tokensFarmArtifact.abi,
        "the contracts address here"
    );
    let userAddress = "user address that wish to withdraw";
    let stakeId;
    let {deposits, amounts, depositeTimes } = await tokensFarmContract.getUserStakesAndPendingAmounts(userAddress);
    stakeId = deposits[0]; //withdraw only the user first deposit
    
    //Call withdraw function
    await tokensFarmContract.withdraw(userAddress, stakeId);
}
```


# TokensFarm Contract Interface

A list of functions for interacting with the TokensFarm Contract

```solidity
interface ITokensFarm {
    function deposit(uint256 _amount) external;
    function withdraw(uint256 _amount, uint256 stakeId) external;
    function getUserStakesAndPendingAmounts(address user) external view;
    function getTotalRewardsLockedUnlocked() external view returns (uint256, uint256);
    function deposited(address _user, uint256 stakeId) public view;
    function pending(address _user, uint256 stakeId) public view;
    function totalPending() external view;
    function getNumberOfUserStakes(address user) external view;
    function fund(uint256 _amount) external;
    function emergencyWithdraw(uint256 stakeId) external;
    function updatePool() public;
    function depositTimestamp(address _user, uint256 stakeId) public view;
    function withdrawTimestamp(address _user, uint256 stakeId) public view;
}
```


# How to integrate TokensFarmSDK

* `deposit` - remember deposit and based on that calculate all info for giving rewards
* `reduceStakeOrUnstake` - remember that stake was used to pay something or it was unstaked
* `withdrawRewards` - claim collected rewards for user

```solidity
pragma solidity 0.6.12;

import "ISDK.sol";

contract ExampleContract {
    address public farmAddress;
    
    function setFarmAddress(
        address _farmAddress
    ) 
        external 
        onlyOnwer 
    { 
        require(_farmAddress != address(0x0));
        farmAddress = _farmAddress;
    }
    
    function deposit()
        external 
        onlyOnwer
    {
        // If warmup == 0 => deposit
        ISDK(farmAddress).deposit(msg.sender, amount);
        
        // If warmup != 0 makeDepoistRequest + finaliseDeposit
        ISDK(farmAddress).makeDepositRequest(msg.sender, amount);
        // After warmup has passed
        ISDK(farmAddress).finaliseDeposit(_user, stakeId);
    }
    
    function reduceStakeOrUnstake()
        external
        onlyOwner
    {
        // IF Example Contract is storring stake amount in multiple stakes
        ISDK(farmAddress).noticeReducedStake(
            msg.sender,
            amount,
            stakeID
       );
       
       // IF Example Contract is just adding stake amount to one balance 
        ISDK(farmAddress).noticeReducedStakeWithoutStakeId(
            msg.sender,
            amount,
            stakeID
        );
    }
    
    function withdrawRewards()
        external
        onlyOwner
    {
        ISDK(farmAddress).withdrawRewards(msg.sender);
    }
}
```


# How to Embed TokensFarm

This is a library that can be embedded on any URL to allow users to participate in a farm

### How to Add <a href="#how-to-add" id="how-to-add"></a>

Include the following in your website's HTML code:

```html
<script src="https://tf-embedded.pages.dev/dist/embedded/TFLoader.js" type="text/javascript"></script>
// Some code
```

once script will be loaded `window.TF` object will be exposed. before use you need init with a valid params

```javascript
  function initTokensFarm() {
	document.addEventListener('tf-farm-loaded', (event) => {
		// farm object to verify and determinate when farm is loaded
		console.log(event.detail.farm);
		// if you need to override any style color
		document.documentElement.style.setProperty('--tf-emb-overlay-color', '#000000');
	});
	TF.init({
		dynamicId: '....', // dynamic environment id for wallet connectivity 
		id: 'embedded', // id of html element where you want to inject 
		farmType: 'lp', // farm type (you can find in tokensfarm.com)
		nonce: 15, // farm nonce (you can find in tokensfarm.com)
		token: 'XCAD', // farm tokenSymbol (you can find in tokensfarm.com)
		darkMode: true // theme light/dark
	});
}

document.addEventListener("DOMContentLoaded", (event) => {
	if (TF?.init) {
		initTokensFarm();
	} else {
		document.addEventListener('tf-loaded', initTokensFarm);
	}
});
```

after farm object will be loaded you can open/close modal

```javascript
  TF.show();
  // this will emit event
  document.addEventListener('tf-farm-modal-opened', () => ...)
  TF.hide();
  // this will emit event
  document.addEventListener('tf-farm-modal-closed', () => ...)
```

\
\
\ <br>


# Getters of TokensFarm Contract

### Get info from relevant contract public fields

#### The staked ERC-20 token's address

```solidity
IERC20 public tokenStaked;
```

#### Total amount of tokens deposited to a farm

```solidity
 uint256 public totalDeposits;
```

#### Total amount of tokens that were paid out as rewards

```solidity
uint256 public paidOut;
```

#### The current total rewards amount

```solidity
uint256 public totalRewards;
```

#### The amount of tokens rewarded per second

```solidity
uint256 public rewardPerSecond;
```

#### The farm's start and end times

```solidity
uint256 public startTime;
uint256 public endTime;
```

#### The early withdrawal penalty

```solidity
EarlyWithdrawPenalty public penalty;
```

#### The fee rates in percentages %

```solidity
uint256 public stakeFeePercent;
uint256 public rewardFeePercent;
uint256 public flatFeeAmount;
```

#### The number of farm participants

```solidity
uint256 public noOfUsers;
```

#### The addresses of all farm participants and `mapping` of users to get the `index`

```solidity
address[] public participants;
mapping(address => uint256) public id;
```

## Getters

### Get the Address of a Staked Token&#x20;

```
IERC20 public tokenStaked;
```

### Get the Amount of Deposited ERC-20 Tokens via `stakeId`

```solidity
function deposited(address _user, uint256 stakeId)
```

| Parameters | Type      | Description                             |
| ---------- | --------- | --------------------------------------- |
| `user`     | `address` | The `user` address whose data you fetch |
| `stakeId`  | `uint256` | The `stakeId` of the particular stake   |

returns:

<table><thead><tr><th width="242">Parameters</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>stake.amount</code></td><td><code>uint256</code></td><td>The resulting number will be the ERC-20 amount that was deposited in the requested stake.</td></tr></tbody></table>

### Get pending reward amount

```solidity
function pending(address _user, uint256 stakeId)
```

<table><thead><tr><th width="207.33333333333331">Parameters</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>user</td><td><code>address</code></td><td>The <code>user</code> address whose data you fetch</td></tr><tr><td>stakeId</td><td><code>uint256</code></td><td>The <code>stakeId</code> of the particular stake</td></tr></tbody></table>

returns:

<table><thead><tr><th width="242">Parameters</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>rewardAmount</td><td><code>uint256</code></td><td>The amount of pending ERC-20 rewards</td></tr></tbody></table>

### How many time a user staked

To get the number of user stakes from a TokensFarm contract, you must call `getNumberOfUserStakes` on the `TokensFarm` smart contract.

```solidity
function getNumberOfUserStakes(address user)
```

| Parameters | Type      | Description                             |
| ---------- | --------- | --------------------------------------- |
| user       | `address` | The `user` address whose data you fetch |

returns:

<table><thead><tr><th width="242">Parameters</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>stakeInfo[user].length</td><td><code>uint256</code></td><td>The resulting number will represent how many times the user has staked.</td></tr></tbody></table>

### Get deposit timestamp

```solidity
function depositTimestamp(address _user, uint256 stakeId)
```

<table><thead><tr><th width="262.35455543358944">Parameters</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>user</td><td><code>address</code></td><td>The <code>user</code> address whose data you fetch</td></tr><tr><td>stakeId</td><td><code>uint256</code></td><td>The <code>stakeId</code> of the particular stake</td></tr></tbody></table>

returns:

<table><thead><tr><th width="242">Parameters</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>timestamp</td><td><code>uint256</code></td><td>The timestamp of the deposit</td></tr></tbody></table>

### Get withdraw timestamp

```solidity
function withdrawTimestamp(address _user, uint256 stakeId)
```

<table><thead><tr><th width="262.35455543358944">Parameters</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>user</td><td><code>address</code></td><td>The <code>user</code> address whose data you fetch</td></tr><tr><td>stakeId</td><td><code>uint256</code></td><td>The <code>stakeId</code> of the particular stake</td></tr></tbody></table>

returns:

<table><thead><tr><th width="242">Parameters</th><th width="150">Type</th><th>Description</th></tr></thead><tbody><tr><td>timestamp</td><td><code>uint256</code></td><td>The timestamp of the withdraw</td></tr></tbody></table>


# PerpetualTokensFarmSDK

**INFO** : `PerpetualTokensFarmSDK.sol` is contract that serves to help other projects to integrate staking system into them. We are providing audited code that is going to help yours project to reward yours clients by earning them rewards cause they are holding your token .\
\
This is the flow of usage of this feature:

• First client comes to us providing the address of the contractAdmin(contract that is going to use our SDK)

• Our developers are deploying the TokensFarmSDK.sol contract with yours contract address inside of the initialisation so SDK can know who can only report the stakes and withdrawals

• Once developers deploy contract, we are going to provide library and list of the functions that you are going to integrate with help of our developers

• Interface called ISDK.sol contains functions that are only callable by the contract that you provided

• Getters are public so you can fetch them by directly calling functions from contract&#x20;

• Setters are changing the state of the contract so we took precaution and implemented security system into our TokensFarmSDKFactory.sol and this is the contract that is the owner of the SDK contract and only through that contract we can change the state of the farm

PerpetualTokensFarmSDK is the repetitive TokensFarmSDK. It has the ability to have multiple rewarding periods witch are called epochs &#x20;


# Getters

Description of all getters

* `getAllPendingStakes`  - it is returning array of all stakes that are waiting to be finalised
* `deposited` - it is returning the deposited amount for specific stake
* `pending` - it is returning the amount that user earned for specific stake&#x20;
* `depositTimestamp` - returning timestamp when specific stake was deposited
* `totalPending` - how much was given rewards from beginning till now
* `getNumberOfUserStakes` - number of stakes for user
* `getUserStakesAndPendingAmounts` - it is returning all stakes and all pending amounts for all of the stakes for user

```solidity
* @return array of deposits,pendingAmounts,depositTime and warmupExpirations
```

* getTotalRewardsLockedUnlocked - it is returning rewards that are locked and unlocked
* getStatsForUser - it is returning all necessary info for user

```solidity
* @return totalStakedCurrently
* @return totalEarnedForLifeTime
* @return currentPendingAmount
* @return currentBalanceToWithdraw
```

## List of all getters with their signature

```solidity
function getAllPendingStakes()
function deposited(address _user,uint256 stakeId)
function pending(address _user,uint256 stakeId)
function depositTimestamp(address _user,uint256 stakeId)
function totalPending()
function getNumberOfUserStakes(address user)
function getUserStakesAndPendingAmounts(address user)
function getTotalRewardsLockedUnlocked()
function getStatsForUser(address _user)
```


# Setters

* In order to change one of these things, through our approved addresses initiating a call, we can change the state of listed params below

```solidity
function setMinTimeToStake(uint256 _minTimeToStake)
function setIsEarlyWithdrawAllowed(bool _isEarlyWithdrawAllowed)
function setWarmup(uint256 _warmup)
```


# Parameters

All public declared parameters act as a getters.\
&#x20;Ex : `uint256 public lastRewardTime` so if you call `PerpetualTokensFarmSDK.lastRewardTime( epochId )`\
you will get timestamp of last time that reward was given in that specific epoch

**Epoch independent parameters**

* These ones you can get like this `PerpetualTokensFarmSDK.tokenStaked()`

<pre class="language-solidity"><code class="lang-solidity"><strong>    IERC20 public tokenStaked;
</strong>    IERC20 public tokenStaked;
    address payable public feeCollector;
    uint256 public totalFeeCollectedETH;
    uint256 public totalFeeCollectedTokens;
    address public farmImplementation;
    uint256 public epochId;
    mapping(address => StakeInfo[]) public stakeInfo;
    address public contractAdmin;
    bool public isActive;
    mapping(address => uint256) public totalEarnedForUser;
    mapping(address => uint256) public totalPendingAmountForUser;
    bool public init;
    mapping(address => uint256) public lastStakeConsumed;
    mapping(address => DepositRequest[]) public depositRequest;
    address[] public waitingList;
    mapping(address => uint256) public idInList;
    uint256 public noOfPendingStakes;
    mapping(address => uint256) public ATHStake;
    mapping(address => uint256) public nextStakeToFinalise;   
</code></pre>

**Epoch depending parameters**<br>

* These ones you need to fetch epochId first :&#x20;

`epochId = PerpetualTokensFarmSDK.epochId() (current epoch)`

Or you can choose your own `epochId` that you want to investigate

And once you have `epochId` you can get the parameter :&#x20;

`PerpetualTokensFarmSDK.lastRewardTime( epochId )` \
`You will get lastRewardTime of that epoch`

<pre class="language-solidity"><code class="lang-solidity"><strong>    mapping(uint256 => uint256) public lastRewardTime;
</strong>    mapping(uint256 => uint256) public accERC20PerShare;
    mapping(uint256 => uint256) public totalDeposits;
    mapping(uint256 => bool) public isEarlyWithdrawAllowed;
    mapping(uint256 => uint256) public minTimeToStake;
    mapping(uint256 => uint256) public rewardPerSecond;
    mapping(uint256 => uint256) public totalFundedRewards;
    mapping(uint256 => uint256) public totalRewards;
    mapping(uint256 => uint256) public startTime;
    mapping(uint256 => uint256) public endTime;
    mapping(uint256 => EarlyWithdrawPenalty) public penalty;
    mapping(uint256 => uint256) public rewardFeePercent;
    mapping(uint256 => uint256) public flatFeeAmountDeposit;
    mapping(uint256 => uint256) public flatFeeAmountWithdraw;
    mapping(uint256 => bool) public isFlatFeeAllowed;
    mapping(uint256 => uint256) public totalTokensBurned;
    mapping(uint256 => uint256) public paidOut;
    mapping(uint256 => address[]) public participants;
    mapping(uint256 => uint256) public noOfUsers;
    mapping(uint256 => mapping(address => uint256)) public id;
    mapping(uint256 => uint256) public firstDepositAt;
    mapping(address => mapping(uint256 => uint256)) public totalActiveStakeAmountPerEpoch;
    mapping(uint256 => uint256) public warmupPeriod;
</code></pre>


# ISDK.sol

Interface that needs to be implemented into the project in order to use staking helper

In order to fully use this feature, you will have to insert param called farmAddress into your contract admin contract, and make setter for it&#x20;

```solidity
address public farmAddress;
```

```solidity
function setFarmAddress(
    address _farmAddress
) 
    external onlyOnwer 
{ 
    require(_farmAddress != address(0x0));
    farmAddress = _farmAddress;
}
```

```solidity
//"SPDX-License-Identifier: UNLICENSED"
pragma solidity 0.6.12;

interface ISDK {
    // In order to fund the farm you need to call fund

    function makeDepositRequest(
        address _user,
        uint256 _amount
    ) external;

    function finaliseDeposit(
        address user,
        uint256 stakeId
    ) external;

    // If warmup > 0 then these two functions above are used together to deposit

    function deposit(
        address _user,
        uint256 _amount
    ) external;

    // If warmup = 0 then only one function from above is used to deposit

    function ifPaymentCanPassInOneTx(
        address _user,
        uint256 _amount
    ) external view returns(bool);

    // If comes to withdrawal first getter ifPaymentCanPassInOneTx is called (returns true/false)

    function noticeReducedStakeWithoutStakeId(
        address _user,
        uint256 _amount
    ) external;

    // If getter ifPaymentCanPassInOneTx returns true then noticeReducedStakeWithoutStakeId is called

    function provideInfoForWithdrawWithoutStakeId(
        address _user,
        uint256 _amount
    )  external view returns(uint256[] memory, uint256[] memory);

    // If getter ifPaymentCanPassInOneTx returns false then provideInfoForWithdrawWithoutStakeId is called
    // provideInfoForWithdrawWithoutStakeId is returning array of stakes and stakes amount that should be
    // taken from each stake

    function noticeReducedStake(
        address _user,
        uint256 _amount,
        uint256 stakeId
    ) external;

    // And then you have all the info for which stakes and for what amount to call multiple times noticeReducedStake

    function withdrawRewards(
        address _user
    ) external;

    // To withdraw rewards user can call it directly on the contract but also contract admin can do it
}
```


# Deposit

* There is two way to make a deposit on contracts, depends if warmup is enabled or not
* If `warmupPeriod == 0` contract admin needs to make a deposit through function called `ISDK(farmAddress).deposit()`

  ```solidity
  function deposit(address _user, uint256 amount)
  ```

  &#x20;After that stake is remembered and user starts earning immediately
* If `warmupPeriod > 0` contract admin needs to make deposit through function called `ISDK(farmAddress).makeDepositRequest`

  ```solidity
  function makeDepositRequest(
     address _user,
     uint256 amount
  )
  ```

  &#x20;After that `warmupPeriod` needs to pass in order for BE or contract admin to call function `ISDK(farmAddress).finaliseDeposit`&#x20;

  ```solidity
  function finaliseDeposit(
      address _user,    
      uint256 stakeId
  )
  ```

  once that function is executed user can start earning rewards and his stakes i acknowledged&#x20;


# Withdraw

WITHDRAW SYSTEM :

* If yours project wants to take a fee or report unstake from stake of specific user you need to call `ISDK(farmAddress).noticeReducedStakeWithoutStakeId`&#x20;

```solidity
function noticeReducedStakeWithoutStakeId(  
    address _user,   
    uint256 _amount
)
```

* Once the stake was updated to new state there is mapping called&#x20;

  ```solidity
  mapping(address => uint256) public totalPendingAmountForUser;
  ```

that after `noticeReducedStakeWithoutStakeId` was called, contains newly collected rewards that stake that was updated was earning during staking time.

* In order for user to collect those collected rewards from `totalPendingAmountForUser` he can call directly from contract `TokensFarmSDK.withdrawRewards(msg.sender)` or you can execute withdraw from contract admin through `ISDK(farmAddress).withdrawRewards(addressOfUser)`


# PerpetualTokensFarm

**INFO** : `PerpetualTokensFarm.sol` is yielding smart contract that is enabling project to defend value of their token by giving users rewards in certain way. This contract has ability to have multiple epochs and each epoch can have different configuration. So you can maintain your token price for longer period of time with different params. <br>

• Client comes to us to deploy `PerpetualTokensFarm` that has his token as stake token, based on amount that you deposit and time when you deposit your rewards gets calculated and you get rewards because you are hodlling clients token.

Config object for a farm accessible via GET request to TF API:

`brew install jq && curl -X GET https://test-api.tokensfarm.com/farm/config?symbol=portx&type=lp&nonce=1 | jq .`

From received JSON object it will be possible to use \
`brew install jq && curl -X GET https://test-api.tokensfarm.com/farm/config?symbol=portx&type=lp&nonce=1 | jq .contracts.PerpetualTokensFarm`&#x20;

or&#x20;

`brew install jq && curl -X GET https://test-api.tokensfarm.com/farm/config?symbol=portx&type=lp&nonce=1 | jq .farmProxyAddress` <br>

and also&#x20;

`brew install jq && curl -X GET https://test-api.tokensfarm.com/farm/config?symbol=portx&type=lp&nonce=1 | jq .abi`&#x20;

for calling farm contract functions directly.

* There are **2** types of **PerpetualTokensFarm** farm contracts
  * *STAKING* (reward and staking token are same or different) stake one and get same or other token as reward but also with liquidity pool being out of the game
  * *LP* (reward and staking token are different) stake one and get other token as reward but with liquidity pool being in game
* Both types will have **4** modes in which will they operate
  * *Regular one*(`warmup = 0` and `cooldown = 0`) where user can deposit and withdraw whenever he wants with certain penalty if early withdraw is allowed
  * Warmup on(`warmup > 0` and `cooldown = 0`) where user will deposit and need to wait warmup period to expire in order to start earn any rewards and withdraw normally
  * Cooldown on(`warmup = 0` and `cooldown > 0`) where user will deposit normally but they will need to schedule their withdrawal and once they initiate cooldown countdown, once that expires they can withdraw their rewards + assets
  * Warmup and Cooldown is on(`warmup > 0` and `cooldown > 0`) where user will deposit and need to wait warmup period to expire in order to start earn any rewards and where users will need to schedule their withdrawal and once they initiate cooldown countdown, once that expires they can withdraw their rewards + assets

\
This is the flow of usage of this feature:

• First client comes to us and provide us this params :&#x20;

```solidity
uint256 _startTime,
uint256 _rewardPerSecond,
uint256 _totalBudget,
uint256 _minTimeToStake,
bool _isEarlyWithdrawAllowed,
uint256 _stakeFeePercent,
uint256 _rewardFeePercent,
uint256 _flatFeeAmountDeposit,
uint256 _flatFeeAmountWithdraw,
bool _isFlatFeeAllowed,
uint256 _penalty
address _rewardToken,
address _tokenStaked,
uint256 _warmup,
uint256 _coolDown
```

• Our developers are deploying the PerpetualTokensFarm.sol contract&#x20;

• Getters are public so you can fetch them by directly calling functions from contract&#x20;

• Setters are changing the state of the contract so we took precaution and implemented security system into our TokensFarmFactory.sol and this is the contract that is the owner of the PerpetualTokensFarm contract and only through that contract we can change the state of the farm


# Getters

Description of all getters<br>

```solidity
getAllPendingStakes() returns (DepositRequest[] memory) - returns all stakes that are ready to be finalised
```

```solidity
getAllPendingWithdrawals(address _user) returns (UnStakeRequest[] memory) - returns all stakes that are scheduled to be withdrawn
```

```solidity
function pending(
    address _user,
    uint256 stakeId
)  returns (uint256) - returnes amount that user earned for specific stake
```

```solidity
function totalPending() returns (uint256) - amount that is waiting to be withdrawn on global level
```

```solidity
function getUserStakesAndPendingAmounts(address user)
 returns (
  uint256[] memory,
  uint256[] memory,
  uint256[] memory
) - returnes all user stakes, pending amount for those stakes and deposit time for those stakes
```

```solidity
function getTotalRewardsLockedUnlocked() returns (uint256, uint256)
- returnes rewards locked and unlocked
```

```solidity
function getStatsForUser(
    address _user
) returns (uint256, uint256, uint256) - returns totalStakedCurrently, totalEarnedForLifeTime, currentPendingAmount
```


# Setters

In order to change one of these things, through our approved addresses initiating a call, we can change the state of listed params below

```solidity
function setMinTimeToStake(
    uint256 _minTimeToStake
)

function setIsAllowed(
   bool _isEarlyWithdrawAllowed,
   bool _isFlatFeeAllowed
)

function setFeePercents(
  uint256 _stakeFeePercent,
  uint256 _rewardFeePercent
)

function setFlatFees(
    uint256 _flatFeeAmountDeposit,
    uint256 _flatFeeAmountWithdraw
)

function setWarmupCoolDown(
    uint256 _warmup,
    uint256 _coolDown
)

function setFeeCollector(
    address payable _feeCollector
)
```


# Parameters

All public declared parameters act as a getters.\
&#x20;Ex : `uint256 public lastRewardTime` so if you call `PerpetualTokensFarmSDK.lastRewardTime(epochId)`\
you will get timestamp of last time that reward was given

```solidity
 // ***** EPOCH INDEPENDENT PARAMETERS ******//

    // Address of ERC20 token contract.
    IERC20 public tokenStaked;
    // Address of the ERC20 Token contract.
    IERC20 public erc20;
    // Fee collector address
    address payable public feeCollector;
    // Total fee collected
    uint256 public totalFeeCollectedETH;
    // Total fee collected in tokens
    uint256 public totalFeeCollectedTokens;
    // Address of farm instance
    address public farmImplementation;
    // Number of epochs
    uint256 public epochId;
    // Info of each user that stakes ERC20 tokens
    mapping(address => StakeInfo[]) public stakeInfo;
    // Array of withdraw requests
    mapping(address => UnStakeRequest[]) public withdrawRequest;
    // Array of deposit requests
    mapping(address => DepositRequest[]) public depositRequest;
    // Waiting list
    address[] public waitingList;
    // Id of user in waiting list
    mapping(address => uint256) public idInList;
    // Is farm fully initialised
    bool public init;
    // Number of all pending stakes
    uint256 public noOfPendingStakes;
    // Total tokens currently staked for user per epoch
    mapping(address => uint256) public totalActiveStakeAmount;
    // If params for next epoch are all set
    bool public initNewEpoch;
    // If all stakes from prev epoch are migrated
    bool public allStakesAreMigrated;
    // Index of last user migrated
    uint256 public lastUserMigrated;
    // All time high amount to be staked
    mapping(address => uint256) public ATHStake;
    // Total earned for user
    mapping(address => uint256) public totalEarnedForUser;

    // ***** EPOCH DEPENDING PARAMETERS ******//

    // Last time number that ERC20s distribution occurs for every epoch
    mapping(uint256 => uint256) public lastRewardTime;
    // Accumulated ERC20s per share, times 1e18 for every epoch
    mapping(uint256 => uint256) public accERC20PerShare;
    // Total tokens deposited in the farm for every epoch
    mapping(uint256 => uint256) public totalDeposits;
    // If contractor allows early withdraw on stakes for every epoch
    mapping(uint256 => bool) public isEarlyWithdrawAllowed;
    // Minimal period of time to stake for every epoch
    mapping(uint256 => uint256) public minTimeToStake;
    // ERC20 tokens rewarded per second for every epoch
    mapping(uint256 => uint256) public rewardPerSecond;
    // Total rewards added to farm for every epoch
    mapping(uint256 => uint256) public totalFundedRewards;
    // Total current rewards for every epoch
    mapping(uint256 => uint256) public totalRewards;
    // The time when farming starts for every epoch
    mapping(uint256 => uint256) public startTime;
    // The time when farming ends for every epoch
    mapping(uint256 => uint256) public endTime;
    // Early withdraw penalty for every epoch
    mapping(uint256 => EarlyWithdrawPenalty) public penalty;
    // Stake fee percent for every epoch
    mapping(uint256 => uint256) public stakeFeePercent;
    // Reward fee percent for every epoch
    mapping(uint256 => uint256) public rewardFeePercent;
    // Flat fee amount to deposit for every epoch
    mapping(uint256 => uint256) public flatFeeAmountDeposit;
    // Flat fee amount to withdraw for every epoch
    mapping(uint256 => uint256) public flatFeeAmountWithdraw;
    // Fee option for every epoch
    mapping(uint256 => bool) public isFlatFeeAllowed;
    // Total tokens burned for every epoch
    mapping(uint256 => uint256) public totalTokensBurned;
    // Paid out amounts for every epoch
    mapping(uint256 => uint256) public paidOut;
    // Mapping of every participants array of every epoch
    mapping(uint256 => address[]) public participants;
    // Number of active users per epoch
    mapping(uint256 => uint256) public noOfUsers;
    // Mapping of every users spot in array in every epoch
    mapping(uint256 => mapping(address => uint256)) public id;
    // When first deposit was made for that epoch
    mapping(uint256 => uint256) public firstDepositAt;
    // Total tokens currently staked for user per epoch
    mapping(address => mapping(uint256 => uint256)) public totalActiveStakeAmountPerEpoch;
    // Cool down period in seconds
    mapping(uint256 => uint256) public coolDownPeriod;
    // Warm up period in seconds
    mapping(uint256 => uint256) public warmupPeriod;
    // Total number of users in epoch
    mapping(uint256 => uint256) public totalNoOfUsers;
```


# Deposit

* There is two way to make a deposit on contracts, depends if warmup is enabled or not
* If `warmupPeriod == 0` user needs to make a deposit through function called `deposit()`

  ```solidity
  function deposit(uint256 amount)
  ```

  &#x20;After that stake is remembered and user starts earning immediately
* If `warmupPeriod > 0` user needs to make deposit through function called `makeDepositRequest`

  ```solidity
   function makeDepositRequest(
          uint256 _amount
      )
  ```

  &#x20;After that `warmupPeriod` needs to pass in order for BE or user to call function `finaliseDeposit`&#x20;

  ```solidity
   function finaliseDeposit(
          address _user,
          uint256 stakeId
    )
  ```

  once that function is executed user can start earning rewards and his stakes i acknowledged&#x20;


# Withdraw

&#x20;WITHDRAW SYSTEM : You can withdraw in two ways \
\
• You can withdraw stake + rewards for that stake in one go\
&#x20;   1\. If `coolDown == 0` user can call `withdraw` and immediately withdraw

```solidity
function withdraw(
    uint256 _amount,
    uint256 stakeId
)
```

&#x20;2\. if `coolDown > 0` user needs to first initiate withdraw request calling makeWithdrawRequest

```solidity
function makeWithdrawRequest(
    uint256 _amount,
    uint256 stakeId
)
```

&#x20; After coolDown period has passed user will initiate withdraw&#x20;

```solidity
function withdraw(
    uint256 _amount,
    uint256 stakeId
)id
```

\
• You can only withdraw earned rewards for all stakes by user calling&#x20;

```solidity
function withdrawRewards()
```


# Social Media

TokensFarm's Social Accounts - Follow & Subscribe for updates and more !

[**Telegram**](https://t.me/tokensfarm)&#x20;

[**Twitter**](https://twitter.com/TokensFarm)&#x20;

[**Reddit**](https://www.reddit.com/r/TokensFarm/)&#x20;

[**YouTube**](https://www.youtube.com/channel/UCvWcomeKj9_5Ha9HiG5yAJA)&#x20;

[**Medium**](https://medium.com/tokensfarm)&#x20;

[**LinkedIn**](https://www.linkedin.com/products/dcentralab-tokensfarm/)&#x20;


# About DcentraLab

DcentraLab is creating an ecosystem of on-chain products designed to accelerate blockchain mass adoption, produce value, increase transparency, and lead the decentralized revolution.&#x20;

DcentraLab is in the space for more than 5 years, our products include one of the largest blockchain bridges - [ChainPort](https://www.chainport.io/) in the world, a unique farm-as-a-service platform - [TokensFarm](https://tokensfarm.com/), and a managed portfolio app [Hord](https://www.hord.app/about).&#x20;

Working at Dcentralab is an incredible opportunity. With us, you will dive deep into cutting-edge technologies, grow with a rapidly expanding industry, and play a key role in Dcentralab’s success!

Our company is full of individuals that strive for the highest professional standards. All of our teams are hard-coded with the willingness to take ownership, perform creative problem solving, and enjoy life!&#x20;

**Join us!** [Click here](https://www.dcentralab.com/jobs) to check our career page&#x20;


# FAQ

Frequently Asked Questions

## A. About us

### **I. What is TokensFarm?**

TokensFarm is a cross-chain Farms-As-A-Service provider offering deployable farms that can be live within hours. It provides an easy-to-use interface, allows projects to incentivize liquidity, and strengthens token and project stability while gaining exposure to TokensFarm hundred of thousands of followers and users. TokensFarm supports all EVM chains & DEXs and doesn’t require coding or integrations.

At the same time, it enables crypto investors to have a one-stop shop to earn a yield on different tokens, lowering the entry barrier to DeFi space.

### II. Who created TokensFarm?

TokensFarm was established during the summer of 2021 by the Decentralab Team. Dcentralab was founded in 2017 to create an ecosystem of on-chain products designed to accelerate blockchain mass adoption. To date, we’ve developed four different products, including ChainPort and TokensFarm. Decentralab’s products produce value, increase transparency, and lead the decentralized revolution.

### **III. Is TokensFarm secure?**

TokensFarm puts a heavy emphasis on security and understands its profound importance. TokensFarm’s contracts have undergone a minimum of two independent audits. These audits were conducted by the biggest names in the world of blockchain security.

### **IV. Which blockchains are supported?**

TokensFarm supports all leading blockchains and DEXs. Supported chains include Ethereum, and most EVMs, while supported DEXs include PancakeSwap, Uniswap, and Quickswap. TokensFarm will add additional DEXs and chains in the future.

### **V. Which wallets are supported?**

TokensFarm supports all popular wallet options. Supported wallets include Metamask, Ledger, Trezor, Coinbase Wallet, and many others.

## **B.** Yield Farming

### I. What is Yield Farming?

Yield farming is an investment strategy based on DeFi (decentralized finance) to maximize cryptocurrency returns. Returns for yield farming are generally calculated in annual percentage yields or APYs.

### II. **What is a dynamic APY?**

The Dynamic APY calculates and adjusts the APY based on the number of farm participants and the number of tokens or TVL locked.

The fewer participants a farm has, the greater the rewards. Dynamic APY also works in vice versa, and the larger number of participants a farm has, the lower the APY.

### **III. What is TVL, and how is it calculated?**

Total value locked or TVL is the number of user funds a DeFi protocol holds, usually in a USD equivalent. These funds may be locked in a protocol for different functionalities such as lending, staking, or providing liquidity. TVL is calculated by multiplying the number of tokens vested by their value in USD.

### **IV. What are the risks of yield farming?**

All forms of investment contain risk. With yield farming, the most significant risks are smart contracts exploits, gas costs, and impermanent loss. If not appropriately audited and secured, smart contracts can face exploits and hacks by bad actors. Gas costs or Tx fees can become expensive on specific blockchains at certain times, cutting profitability.\
\
Impermanent loss can also affect farmers. When farmers provide liquidity to a token pair on a DEX, one of the tokens can shift sharply in value. If that occurs, it negatively affects the farmers' returns.&#x20;

## **C. About Staking Farms**

### **I. What are staking farms?**

Staking farms are a smart contract protocol available on TokensFarm. On staking farms, users receive rewards in the form of tokens for staking a specific token on the protocol. The rewards are provided by the farms' creators and are usually a crypto project. Typically the rewards are in the form of the token required for staking, although projects may select other tokens.

### **II.  Where do staking rewards come from?**

The token rewards are supplied by the crypto project or entity that launched the farm.

### **III.  Is there a minimum or maximum amount to stake?**

Currently, there are no minimum or maximum staking amount limitations on TokensFarm.

### **IV.** Will I be able to withdraw my tokens at any time?

Different farms have different time requirements for withdrawing tokens while staking. Please check the farm where you wish to stake tokens for requirements before staking.

### V. **Are staking rewards in the form of the same token staked or different tokens?**

The staking rewards depend on the project that has set them. Typically the rewards are in the form of the same token staked, although a project can choose a different token.

### **VI. When will I receive my rewards?**

Farmers will receive their staking rewards as soon as the minimum staking time requirements have been completed. Each farm has different requirements for minimum staking time, so check the farm’s information before staking.

### **VII.  Where will I receive my staking rewards?**

You can either restake the rewards you’ve received or withdraw the funds. Should you withdraw the funds, the smart contract will send your funds to the wallet you’ve connected.

### **VIII. Will staked rewards automatically be restaked?**

After minimum staking requirements are complete, farmers can choose to restake rewards or withdraw them.

### **IX. Can I withdraw my rewards and keep the tokens staked?**

Yes. As long as all requirements have been met, you can withdraw rewards and keep staked tokens staked.

### **D. About LP Staking**

### **I. What is an AMM?**

While in the past, DEXs relied on order books, all modern DEXs rely on AMMs or automated market making. AMMs require two equal pools of a token pair (e.g., WBTC/USDT) for a token pair to be tradable. Individuals and not the DEX provide liquidity for token pairs.

### II. **What is liquidity providing?**

Providing liquidity is a type of DeFi-based investment strategy. Individuals can provide liquidity on any DEX for any token pair. In exchange for liquidity, these individuals receive LP tokens representing their stake in the liquidity pool.

### **III. What is impermanent loss?**

Impermanent loss is a hypothetical loss called an unrealized loss. This unrealized loss occurs when one of the tokens in the token pair experiences extreme volatility. When this volatility occurs, it would hypothetically be more profitable to hold the tokens. A liquidity provider may still make a profit when experiencing impermanent loss, but it wouldn’t be as great as buying or selling.

### **IV. What is an LP token?**&#x20;

LP tokens represent a liquidity provider's stake for a specific pair on a DEX. The DEX requires the LP tokens when a liquidity provider wants to withdraw their liquidity from a pool. Liquidity providers can also stake their LP tokens on TokensFarm in exchange for rewards.

### **V. Where do LP farm rewards come from?**

Typically crypto projects deploy LP farms on TokensFarm to ensure continuous liquidity on DEXs. As such, the projects provide rewards.

### **VI. Will I still earn trading fees if I stake my LP tokens?**

Yes. You will still receive fees from trades on the DEX in addition to the LP farm’s rewards.

### **VII. Why are the rewards not LP tokens?**

LP tokens are generated by the DEX when an individual provides liquidity. The LP tokens represent the share of liquidity the provider has lent to the DEX. LP tokens have no real value besides being used to withdraw liquidity or represent their share. TokensFarm offers rewards in tokens when certain LP tokens are staked.

### **VIII. Will I be able to withdraw my LP tokens at any time?**

Different farms have different time requirements for withdrawing LP tokens while staking. Please check the farm where you wish to stake LP tokens for requirements before staking.

### IX. **When will I receive my staking rewards?**

Different farms have different time requirements for withdrawing staking rewards. Please check the farm where you wish to stake tokens for its requirements before staking.

### X. **Where will I receive my LP staking rewards?**

**The smart contract will send your funds to the wallet you’ve connected.**

### **XI. Can I withdraw my rewards and keep the tokens staked?**

Yes. The tokens staked and the rewards are different types of tokens. LP tokens aren’t widely tradable, while the reward tokens are.

## **E. About Vesting Contracts**

### **I. What is a vesting contract?**

Vesting contracts release the portion of tokens belonging to either the projects team, advisors and/or early investors. Projects can choose between three different types of release schedules in TokensFarm’s vesting contracts.

### **II. How do I know if I am whitelisted for a vesting contract?**

Simply connect your wallet to the contract to see if you’re eligible.

### **III.** How are tokens distributed?

There are three different ways to distribute tokens with TokensFarm’s vesting contracts.  In Airdrop, all tokens are released at once to all addresses. There are also linear and iterative releases that release tokens in a certain period or according to an algorithm. In addition, tokens from the vesting contract can be released on different chains.  All vesting contracts are fully customizable and adaptable to crypto projects' needs.

### **IV.  What are early withdrawal & burn?**

Some users may wish to withdraw their funds early if a project has set a specific time frame for vesting, such as a linear or iterative release. Projects can allow users to do so, implement a form of penalty such as a “cool off” period, or deny their request.

### **V. What is partial funding?**

Partial funding is a functionality that allows a project to place a portion of its vesting rewards in a contract. The minimum required funding is 5% of the total vesting amount. The team can later add more tokens to the smart contract during the vesting period.

Partial funding enables projects to use their tokens for other usages. Additionally, crypto projects can use it to present a lower circulating supply or avoid unlikely contract issues. Distribution will cease if the tokens within the contract have been depleted before the scheduled end of the contract. The reactivation time and costs of the contract are identical to the launch of a new contract.

## **F. For Projects**

### **I. How much does it cost to launch a farm?**

Different farms have different pricing. You can see TokensFarm’s full pricing [here](https://about.tokensfarm.com/pricing).

### **II. Is there any discount for second and onwards farms?**

Yes. TokensFarm offers discounts on second farms and onwards. [Contact us](mailto:Hello@tokensfarm.com) for more.

### III. **Is it possible to make the payment in crypto?**

Yes. We accept all major stablecoins as well as bank transfers.

### **IV. Is it possible to extend the duration of the farm? What is the cost?**

Yes. The cost is $2000, which is payable in USDT and USDC. Simply contact the TokensFarm team and let us know the duration you’d like to set.

### **V. Once the farm is live, is it possible to change its parameters?**

Unfortunately no. However, a project can choose to deploy a new farm.

### **VI. How long does it take to launch a farm?**

A farm can go live within a few hours after completing the payment and filling in the specifics.

### **VII.  Can I launch a farm if our token is only traded on CEXs?**

Yes. While LP farms may be irrelevant, you may launch a staking farm on TokensFarm.

### **VIII. What do we have to do to launch a farm?**

Simply fill out one of the forms below and stay in touch with TokensFarm’s team.

[Launch an LP farm](https://dcentralab.typeform.com/LP-Farm?typeform-source=about.tokensfarm.com)

[Launch a staking farm](https://dcentralab.typeform.com/staking-farm?typeform-source=about.tokensfarm.com)

[Launch a vesting contract](https://dcentralab.typeform.com/tf-vesting?typeform-source=about.tokensfarm.com)

### **IX. Do I need to do any coding work to be able to launch the farm?**&#x20;

No coding is required to launch a farm. TokensFarm’s team will deal with all technical aspects.

## **Who Created TokensFarm?**

TokensFarm was created by [DcentraLab](https://www.dcentralab.com/). Experienced team of developers building blockchain products since 2017, already well known in the cryptosphere for applications such as [2key](https://2key.io/), [Hord ](https://hord.app/)and [ChainPort](https://chainport.io/).

## **What is a Crypto Farm (Yield Farming)?**

Yield farming is an investment strategy in decentralized finance or DeFi. Yield farming is the practice of staking or lending cryptocurrency assets (tokens) in order to generate high returns or rewards in the form of additional cryptocurrency. This innovative yet risky and volatile application of decentralized finance (DeFi), but skyrocketed in popularity recently thanks to further innovations like liquidity mining. Yield farming is currently the biggest growth driver of the still-nascent DeFi sector.

## What is the difference between LP Farms and Staking Farms?

Technically they have the same type of coding logic used in the smart contracts, but most people like to call it Farming. \
**Staking** is token per token you get the 0.3% of fee and the rewards only per this token you chose.\
**LP farming** will be for a pair of tokens (example: ETH-BUSD) - by adding liquidity you will get in return the LP token that will be generated instead of the 2 other tokens, with this LP token you are staking on the LP farm.

**Why use yield farming?**

A farm incentivizes users to **not** **sell** their tokens by earning rewards for keeping the tokens staked in the smart contract. When projects set up a farm, they push rewards (their tokens) into the contract, so users will earn those rewards for free, just by staking tokens in the farm. The calculation of earning rewards is through [APY](#what-is-apy-dynamic-apy-and-how-is-it-calculated).

## **Where Are The Rewards Come From?**

Rewards are deposited by the token issuer as part of their marketing, and incentive initiatives. Crypto tokens usually have a limited supply, therefore, the biggest rewards will be given in the early stages of any project.

## **How Can I Earn Rewards?**

Choose any of the [live farms](https://tokensfarm.com/) and stake tokens/LP tokens on your farm of choice. Read the farm’s guidelines to ensure that you stake when it is live, stake for the minimum days period, and see any other important information regarding how the farm operates.

## **What Is APY/Dynamic APY and how is it calculated?**

In TokensFarm, we use a Dynamic APY, to automatically adjust the APY value for the active period.\
Dynamic APY increases as users leave the farm, and decreases as users join. Hence, the more tokens staked into a farm, the lower the APY becomes. At TokensFarm, we consider 100-300% APY as a healthy target for projects’ farms.

**Calculating** **APY** = (Reward per block / Number of tokens staked for that block) \* Number of blocks in 1 full year

**Calculating Rewards per block** = Project's total rewards  / Total number of blocks in the farm

## **What Blockchains are supported?**

We support all the Ethereum virtual machine (EVM) compatible blockchains such as:\
Ethereum<img src="/files/ODuMxEDNFSt2gwgo1MVJ" alt="" data-size="line">, BNB<img src="/files/xmsRBZUlkNCqGVpKW3ta" alt="" data-size="line">, Polygon<img src="/files/gPscq6VQsXzE9aPx6zKf" alt="" data-size="line">, Avalanche<img src="/files/5EK0fAlvYcczIQNNZE9U" alt="" data-size="line">, Fantom<img src="/files/ld4wwzpuSO6EaTU8XcSI" alt="" data-size="line">, Hecko<img src="/files/NNTIohuktI8zAzPmuCUw" alt="" data-size="line">, OkEx Chain<img src="/files/4OXgObqtpN1NcnkeRNWD" alt="" data-size="line">, and more.

## **Is There a Limit to the Amount of tokens or People That Can Enter a Farm?**

There is no such limit. The contract can have as many participants and tokens as possible. The rewards are divided according to the relative holding of each participant out of the total tokens in the contract. The APY adjusts accordingly, as users adding or removing tokens from the contract.

## **What is the Security Protocol of TokensFarm?**

TokensFarm is using the highest security standards in the crypto space. All of the TokensFarm smart contracts have been audited by a minimum of 2 auditors. Audit reports can be found on the website footer. All TokensFarm smart contracts are independently audited by leading blockchain security firms, such as [Certik](https://www.certik.com/projects/tokensfarm) and [Zokyo](https://github.com/zokyo-sec/audit-reports/tree/main/TokensFarm)

**Despite the above, before using this site**, please do your own research on how staking and smart contracts work. Make sure that you understand the risks, read our [Privacy Policy](https://about.tokensfarm.com/privacy-policy) & [Terms of Service](https://about.tokensfarm.com/terms-of-service), and review the audits.

Don’t risk more than you can lose!

TokensFarm has no part in the management of tokens presented on its website. Tokens fall under the responsibility of those projects that issued them.

## **What is Impermanent Loss?**

This phenomenon occurs when the price of a token increases or decreases after a user deposits tokens in a liquidity pool. This change is considered a loss when the dollar value of your token at the time of your withdrawal becomes less than its amount at the time of deposit. Read more [here](https://medium.com/coinmonks/understanding-impermanent-loss-9ac6795e5baa#:~:text=Impermanent%20loss%20is%20a%20loss,withdrawn%20from%20the%20liquidity%20poo), to learn about impermanent loss.\
Read more: [Here](https://medium.com/coinmonks/understanding-impermanent-loss-9ac6795e5baa#:~:text=Impermanent%20loss%20is%20a%20loss,withdrawn%20from%20the%20liquidity%20pool)

## What is Compounding ?

Compounding refers to generating earnings from previous earnings. Move your rewards made from staking into the tokens that you are staking on the farm. Given the following, compounding is an effective way to increase your rewards earned. Some experts advise compounding once or twice each week. Note that compounding means that you are making a transaction on the chain of the farm. If the chain carries with it high fees, such as Ethereum in 2022, then definitely consider the gas fee(s) prior to compounding.

The thing which earns you rewards is the amount you stake. Logically, if a user stake more - he will earn more. Compounding is the ability of an asset to generate earnings, which are then reinvested or remain invested with the goal of generating their own earnings.\
In other words, compounding refers to generating earnings from previous earnings.\
Given the following, compounding is great, and of course, will have much better results.\
Note:  that this action works best on chains with as low as zero Tx fees like BNB, but most probably won't work on the expensive gas fee like on Uniswap/Ethereum, which will eat all of the profit.\
\
Increasing the position in the LP carries its own risk of impermanent loss and the added impermanent loss vs the extra gained tokens are not directly comparable but vary on a case by case basis. Also, the act itself of withdrawing some of the reward tokens and buying stable with half of it carries its own impermanent loss possibility to the other side, which again is not directly comparable with the gains, but can vary depending on the case.&#x20;

## What is AMM ?&#x20;

[Read Here](https://medium.com/dragonfly-research/what-explains-the-rise-of-amms-7d008af1c399)

## Why Don’t I Receive LP Tokens as Rewards?

On an LP farm, you stake LP tokens, however, the rewards will always be the Token of the project.

## What is the cost to deploy a farm on TokensFarm?

Each farm or contract has a different deployment cost. Prices vary, and are between $2000 and $8500, depending on the type of contract, the chain, and how many contracts have been created for that token before.

Check the [pricing page](https://about.tokensfarm.com/pricing).


# Tokensfarm Audits

See the following list of Audits:

{% file src="/files/vf9fnIcPyjwaNfzUHTT2" %}
Perpetual Staking Withdrawals & Referral Dashboard
{% endfile %}

{% file src="/files/ysmXdMF7QAHkBJapNfvs" %}
SDK contracts were added
{% endfile %}

{% file src="/files/mt7dl0aJ0OyWt65gHRLm" %}
Perpetual and both merkles were added
{% endfile %}

{% file src="/files/yL7QERoLwalmChpvDbyu" %}
Finalization of all aspects of TokensFarm&#x20;
{% endfile %}

{% file src="/files/8uBgAwpPtK87kGFecXIi" %}
New scope(vesting farms added)
{% endfile %}

{% file src="/files/QSwvhlKXy2IfKbAfBRcA" %}
New scope(correction of first version)
{% endfile %}

{% file src="/files/2ym0LVdAYLy5PgjozSAB" %}
New scope (finalized)
{% endfile %}

{% file src="/files/lfmJXTwNHKDkfEXalRR3" %}

{% file src="/files/4xY2feCblSY7eCXvZSfU" %}
New scope (visibility specifiers was added)
{% endfile %}

{% file src="/files/MmiON26cAWQJqBvRAk4M" %}

{% file src="/files/hzU6OpHGszA6uiCgSUFZ" %}
TotalWithdrawn fixed logic
{% endfile %}

{% file src="/files/5DFvouixVUGcE4qmkipd" %}
Set start time
{% endfile %}

{% file src="/files/5yva1a7lpE9kobu8Fpar" %}
Parțial funding
{% endfile %}

{% file src="/files/XgXKNEp4UXcTN28lSaYl" %}
Finalized partial funding
{% endfile %}


# Support

### Questions Regarding TokensFarm?

Check out our tutorials on [how to use the TokensFarm platform.](https://about.tokensfarm.com/how-it-works)

### Having An Issue?

If you're experiencing difficulties when using TokensFarm’s features, try these steps:

* Refresh the page&#x20;
* Clear your browser's cache & cookies&#x20;
* Restart your device&#x20;
* Try another RPC&#x20;
* Make sure you're viewing the correct ACTIVE/INACTIVE farm.

### Need Further Assistance?

Contact our support team via the bot on our homepage or send us an email at: <Hello@tokensfarm.com>


# Legal

Legal Documentation

### [TokensFarm's Terms of Service](https://about.tokensfarm.com/terms-of-service)

### [TokensFarm's Privacy Policy](https://about.tokensfarm.com/privacy-policy)


