> For the complete documentation index, see [llms.txt](https://docs.aftermath.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aftermath.finance/for-developers/typescript-sdk/products/farms.md).

# Farms

The Farms system provides functionality for managing staking pools and staked positions on the Sui network, allowing users to stake tokens and earn rewards.

### Initialization

```typescript
const afSdk = await Aftermath.create({ network: "MAINNET" });

const farms = afSdk.Farms();
```

### Constants

```typescript
Farms.constants = {
	minimalRewardsToClaim: BigInt("1000000"), // Minimum rewards that can be claimed
};
```

### Farms Class Methods

#### Staking Pool Management

```typescript
// Get single staking pool
const pool = await farms.getStakingPool({
	objectId: "0x...",
});

// Get multiple staking pools
const pools = await farms.getStakingPools({
	objectIds: ["0x...", "0x..."],
});

// Get all staking pools
const allPools = await farms.getAllStakingPools();

// Get TVL and rewards TVL summaries together
const summaries = await farms.getFarmSummaries({
	farmIds: ["0x..."],
});
// -> Array<{ farmId, tvl, rewardsTvl }>
```

Omit `farmIds` to fetch summaries for every farm. `getFarmSummaries` also accepts an optional final `AbortSignal`.

#### Staked Positions

```typescript
// Get user's staked positions
const positions = await farms.getOwnedStakedPositions({
	walletAddress: "0x...",
});

// Get owner caps
const ownerCaps = await farms.getOwnedStakingPoolOwnerCaps({
	walletAddress: "0x...",
});

// Get one-time admin caps
const adminCaps = await farms.getOwnedStakingPoolOneTimeAdminCaps({
	walletAddress: "0x...",
});
```

#### Create Staking Pool

```typescript
const tx = await farms.getCreateStakingPoolTransaction({
	lockEnforcement: "Strict", // "Strict" | "Relaxed"
	minLockDurationMs: 604800000, // 1 week
	maxLockDurationMs: 31536000000, // 1 year
	maxLockMultiplier: BigInt("2000000000"), // 2x
	minStakeAmount: BigInt("1000000"), // Minimum stake amount
	stakeCoinType: "0x...",
	walletAddress: "0x...",
});
```

### FarmsStakedPosition Class

Represents and manages an individual staked position.

#### Position Information

```typescript
const position = new FarmsStakedPosition(stakedPositionObject);

// Check if position is locked
const isLocked = position.isLocked({ stakingPool });

// Get unlock timestamp
const unlockTime = position.unlockTimestamp();

// Get reward coin types
const rewardTypes = position.rewardCoinTypes();

// Check for claimable rewards
const hasRewards = position.hasClaimableRewards({ stakingPool });

// Calculate total APR
const apr = position.calcTotalApr({
	rewardsUsd: 1000,
	stakeUsd: 10000,
});
```

#### Position Transactions

```typescript
// Deposit additional tokens
const depositTx = await position.getDepositPrincipalTransaction({
	depositAmount: BigInt("1000000"),
	walletAddress: "0x...",
	isSponsoredTx: false,
});

// Unstake position
const unstakeTx = await position.getUnstakeTransaction({
	walletAddress: "0x...",
	stakingPool: stakingPoolObject,
	claimSuiAsAfSui: false,
});

// Lock position
const lockTx = await position.getLockTransaction({
	lockDurationMs: 2592000000, // 30 days
	walletAddress: "0x...",
});

// Harvest rewards
const harvestTx = await position.getHarvestRewardsTransaction({
	walletAddress: "0x...",
	stakingPool: stakingPoolObject,
	claimSuiAsAfSui: false,
});
```

### FarmsStakingPool Class

Manages a staking pool and its associated functionality.

#### Pool Information

```typescript
const pool = new FarmsStakingPool(stakingPoolObject);

// Get reward coin types
const rewardTypes = pool.rewardCoinTypes();

// Calculate APR for specific coin
const apr = pool.calcApr({
	coinType: "0x...",
	price: 1.5,
	decimals: 9,
	tvlUsd: 1000000,
});

// Calculate total APR across all rewards
const totalApr = pool.calcTotalApr({
	coinsToPrice: { "0x...": 1.5 },
	coinsToDecimals: { "0x...": 9 },
	tvlUsd: 1000000,
});

// Calculate multiplier for lock duration
const multiplier = pool.calcMultiplier({
	lockDurationMs: 2592000000, // 30 days
});
```

#### Pool Transactions

```typescript
// Stake tokens
const stakeTx = await pool.getStakeTransaction({
	stakeAmount: BigInt("1000000"),
	lockDurationMs: 2592000000, // 30 days
	walletAddress: "0x...",
	isSponsoredTx: false,
});

// Initialize rewards
const initRewardsTx = await pool.getInitializeRewardTransaction({
	rewardAmount: BigInt("1000000"),
	emissionScheduleMs: 2592000000, // 30 days
	emissionRate: BigInt("100"),
	emissionDelayTimestampMs: 0,
	rewardCoinType: "0x...",
	walletAddress: "0x...",
	ownerCapId: "0x...", // or oneTimeAdminCapId
});

// Top up rewards
const topUpTx = await pool.getTopUpRewardsTransaction({
	rewards: [
		{
			rewardAmount: BigInt("1000000"),
			rewardCoinType: "0x...",
		},
	],
	walletAddress: "0x...",
	ownerCapId: "0x...", // or oneTimeAdminCapId
});

// Increase emissions
const increaseEmissionsTx = await pool.getIncreaseRewardsEmissionsTransaction({
	ownerCapId: "0x...",
	rewards: [
		{
			rewardCoinType: "0x...",
			emissionScheduleMs: 2592000000,
			emissionRate: BigInt("200"),
		},
	],
	walletAddress: "0x...",
});
```

### Types

#### Farm Types

```typescript
type FarmsLockEnforcement = "Strict" | "Relaxed";
type FarmsMultiplier = bigint;

interface FarmsStakingPoolRewardCoin {
	coinType: string;
	rewards: bigint;
	rewardsAccumulatedPerShare: bigint;
	emissionRate: bigint;
	emissionSchedulesMs: number;
	emissionStartTimestamp: number;
	lastRewardTimestamp: number;
	rewardsRemaining: bigint;
	actualRewards: bigint;
}

interface FarmsStakedPositionRewardCoin {
	coinType: string;
	baseRewardsAccumulated: bigint;
	baseRewardsDebt: bigint;
	multiplierRewardsAccumulated: bigint;
	multiplierRewardsDebt: bigint;
}
```

### Example Usage

```typescript
const afSdk = await Aftermath.create({ network: "MAINNET" });
const farms = afSdk.Farms();

// Get all staking pools
const stakingPools = await farms.getAllStakingPools();

// Get user's staked positions
const stakedPositions = await farms.getOwnedStakedPositions({
	walletAddress: "0x...",
});

// Create a new staking position
const stakingPool = stakingPools[0];
const stakeTx = await stakingPool.getStakeTransaction({
	stakeAmount: BigInt("1000000"),
	lockDurationMs: 2592000000, // 30 days
	walletAddress: "0x...",
});

// Harvest rewards from a position
const position = stakedPositions[0];
const harvestTx = await position.getHarvestRewardsTransaction({
	walletAddress: "0x...",
	stakingPool: stakingPool,
});
```
