bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 39쪽
kup length, in the farm's time unit. |
| `lockingEarlyWithdrawalPenaltyBps` | `BN` | Penalty in basis points for withdrawing before the lockup ends. |
| `scopePrices` | `Address` | Scope oracle prices account the farm reads for reward accrual. |
| `strategyId` | `Address` | kliquidity strategy this farm is attached to. Default if none. |
| `vaultId` | `Address` | kvault this farm is attached to. Default if none. |
| `farmVault` | `Address` | Token account that holds the staked tokens. |
</Accordion>
### Get Farm State
Live on-chain read of a single farm: stake token, totals, time gates, and reward slots.
```typescript icon="typescript" getFarmState theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { FarmState, DEFAULT_PUBLIC_KEY } from '@kamino-finance/farms-sdk';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); // farm address
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farmState = await FarmState.fetch(rpc, FARM);
if (!farmState) console.log(`Farm not found: ${FARM}`);
console.log('Delegated:', farmState.isFarmDelegated === 1);
console.log('Frozen:', farmState.isFarmFrozen === 1);
console.log('Total staked (raw):', farmState.totalStakedAmount.toString());
console.log('Deposit warmup (s):', farmState.depositWarmupPeriod);
console.log('Withdrawal cooldown (s):', farmState.withdrawalCooldownPeriod);
// rewardInfos is a fixed-size array; only slots with a real mint are active.
const activeRewards = farmState.rewardInfos.filter(
(r) => r.token.mint.toString() !== DEFAULT_PUBLIC_KEY.toString(),
);
activeRewards.forEach((r) =>
console.log({
mint: r.token.mint.toString(),
decimals: r.token.decimals.toNumber(),
rewardsAvailable: r.rewardsAvailable.toString(),
rewardType: r.rewardType,
}),
);
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`depositWarmupPeriod` and `withdrawalCooldownPeriod` are farm-level time gates in seconds, stored on the farm state with no REST equivalent. The cooldown is the wait between unstaking and being able to withdraw. To load several farms at once, use `FarmState.fetchMultiple(rpc, [addr, ...])`. On a non-delegated farm, `farms.getStakedAmountForFarm(FARM)` returns the total staked in share units, already divided by the stake-token decimals.
</Note>
### Find Farms
Discover farms by their stake token, or batch-load known farm addresses in one call.
```typescript icon="typescript" findFarms theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { Farms } from '@kamino-finance/farms-sdk';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const STAKE_MINT = address('AYUjc3a3QQUiLE6jP7V29UMeUZGADdtiVxhSjoLcqYwr'); // stake (share) token mint
const FARM_ADDRESSES = [
address('8qcg3HogEhVXXUxkgbgcC8wtZgVwRjQsaxiCMYRpkvKA'),
address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'),
];
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farms = new Farms(rpc);
// Discover by stake mint (non-delegated farms only).
const byMint = await farms.getFarmsForMint(STAKE_MINT);
byMint.forEach((f) => console.log('farm:', f.key.toString()));
// Batch-load specific farms by address (any farm type).
const byKeys = await farms.getAllFarmStatesByPubkeys(FARM_ADDRESSES);
byKeys.forEach((f) =>
console.log({
farm: f.key.toString(),
delegated: f.farmState.isFarmDelegated === 1,
rewardCount: f.farmState.numRewardTokens.toString(),
}),
);
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`getFarmsForMint` filters on the stake-token mint, so it only finds non-delegated farms. Delegated farms leave that field empty, so you get their address elsewhere (a reserve's `farmCollateral` / `farmDebt`, or a kvault's `vaultFarm`; see the locating table in the [overview](/docs/build/developers/rewards/overview)) and batch-load them with `getAllFarmStatesByPubkeys`.
</Note>
### Get Incentive APY
Compute a farm's reward APY two ways: the easy path for a strategy farm, and the generic path for any farm.
```typescript icon="typescript" getIncentiveApy theme={null}
import { createSolanaRpc, address, type Address } from '@solana/kit';
import { Farms } from '@kamino-finance/farms-sdk';
import { Kamino } from '@kamino-finance/kliquidity-sdk';
import Decimal from 'decimal.js';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const ORACLE_PRICES_URL = 'https://api.kamino.finance/oracles/prices?source=scope';
const FARM = address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'); // farm address
const STRATEGY = address('CjUsr5w686AHi1qNHYUggz6jGoAPwKVA4K9v4hQaGtzu'); // strategy address
const STAKE_DECIMALS = 6; // strategy share token decimals
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farms = new Farms(rpc);
const kamino = new Kamino('mainnet-beta', rpc);
// 1. Easy path: APY straight from the strategy, no prices to supply.
const byStrategy = await farms.getRewardsAPYForStrategy(STRATEGY);
console.log('Total incentives APY:', (byStrategy.totalIncentivesApy * 100).toFixed(4) + '%');
// 2. Generic path: supply reward prices and the staked-token price yourself.
const rows: Array<{ mint: string; price: string }> = await (await fetch(ORACLE_PRICES_URL)).json();
const priceByMint = new Map(rows.map((r) => [r.mint, new Decimal(r.price)]));
const getPrice = async (mint: Address): Promise<Decimal> =>
priceByMint.get(mint.toString()) ?? new Decimal(0);
const stakedTokenPrice = await kamino.getStrategySharePrice(STRATEGY);
const [farmAndKey] = await farms.getAllFarmStatesByPubkeys([FARM]);
const calc = await farms.calculateFarmIncentivesApy(
farmAndKey,
getPrice,
stakedTokenPrice,
STAKE_DECIMALS,
);
calc.incentivesStats.forEach((s) =>
console.log({
mint: s.rewardMint.toString(),
apy: (s.incentivesApy * 100).toFixed(4) + '%',
yearlyRewards: s.yearlyRewards.toString(),
}),
);
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`getRewardsAPYForStrategy` is the easy path for a strategy farm: the SDK derives the share price and reward prices itself. `calculateFarmIncentivesApy` is generic and works for any farm, but you supply a `getPrice` callback for reward tokens (from the oracle endpoint) plus the staked-token price (from the kliquidity SDK, since a strategy share is not an oracle-tracked asset). The two totals land close to each other.
</Note>
### Simulate APY After Stake or Unstake
Project how the incentive APY changes after a hypothetical stake or unstake, reusing the `getPrice` callback and `stakedTokenPrice` from the previous example.
```typescript icon="typescript" simulateApy theme={null}
const totalStaked = await farms.getStakedAmountForFarm(FARM); // total staked, in share units
const [farmAndKey] = await farms.getAllFarmStatesByPubkeys([FARM]);
const scenarios = [
{ label: 'baseline (no change)', delta: new Decimal(0) },
{ label: 'stake +100% (double the pool)', delta: totalStaked },
{ label: 'unstake -50% (halve the pool)', delta: totalStaked.div(2).neg() },
];
for (const s of scenarios) {
const sim = await farms.simulateFarmIncentivesApy(
farmAndKey,
s.delta,
getPrice,
stakedTokenPrice,
STAKE_DECIMALS,
);
console.log(`${s.label}: ${(sim.totalIncentivesApy * 100).toFixed(4)}%`);
}
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`stakedTokenDelta` is in share units (the decimal share amount, not raw lamports) and adds to the current total stake. A positive delta simulates staking more, so the same rewards spread over a bigger pool and APY falls. A negative delta simulates unstaking, so APY rises.
</Note>
## Farm Types
TypeScript shapes used by the Farms SDK for farm reads.
<Tabs>
<Tab title="FarmState">
On-chain farm account. Fetched with `FarmState.fetch` / `fetchMultiple`. See the collapsible field reference at the top of the page for what each value means.
```typescript theme={null}
class FarmState {
token: TokenInfo; // stake token (empty on delegated farms)
rewardInfos: RewardInfo[]; // fixed-size; unused slots have a default mint
numRewardTokens: BN;
totalStakedAmount: BN;
isFarmDelegated: number; // 1 when delegated
isFarmFrozen: number;
delegateAuthority: Address; // set on delegated farms
depositWarmupPeriod: number; // seconds
withdrawalCooldownPeriod: number; // seconds
depositCapAmount: BN;
scopePrices: Address;
strategyId: Address;
vaultId: Address;
}
```
</Tab>
<Tab title="TokenInfo">
A token's mint, decimals, and owning token program.
```typescript theme={null}
class TokenInfo {
mint: Address;
decimals: BN;
tokenProgram: Address;
}
```
</Tab>
<Tab title="RewardInfo">
One reward slot on a farm.
```typescript theme={null}
class RewardInfo {
token: TokenInfo; // reward token mint and decimals
rewardsVault: Address;
rewardsAvailable: BN;
minClaimDurationSeconds: BN; // claim cooldown for this reward
rewardType: number;
rewardsPerSecondDecimals: number;
}
```
</Tab>
<Tab title="FarmIncentives">
Per-reward APY breakdown returned by the APY methods.
```typescript theme={null}
type FarmIncentives = {
incentivesStats: IncentiveRewardStats[];
totalIncentivesApy: number;
};
type IncentiveRewardStats = {
rewardMint: Address;
rewardDecimals: Decimal;
incentivesApy: number;
yearlyRewards: Decimal;
dailyRewards: Decimal;
hasRewardAvailable: boolean;
};
```
</Tab>
</Tabs>
## Additional Resources
<CardGroup>
<Card title="API Examples" icon="book" href="https://api-docs.kamino.com/" />
<Card title="SDK Repository" icon="github" href="https://github.com/Kamino-Finance/farms-sdk" />
</CardGroup>
# User Position
Source: https://kamino.com/docs/build/developers/rewards/data/user-position
Read a wallet's farm stake, lockup and cooldown status, and pending rewards with the Kamino Farms SDK
## Reading User Position Data
<Note>
The reads below use the non-delegated helpers (`getUserForUndelegatedFarm`, `getUserStateKeyForUndelegatedFarm`). For delegated farms, position accounting lives in the parent program (klend or kvault). For the TypeScript shapes returned here, see [Position Types](#position-types).
</Note>
### Get All Positions
Live read of every farm a wallet is staked in, with the active stake valued in USD.
```typescript icon="typescript" getAllPositions theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { Farms, DEFAULT_PUBLIC_KEY } from '@kamino-finance/farms-sdk';
import { Kamino } from '@kamino-finance/kliquidity-sdk';
import Decimal from 'decimal.js';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const USER = address('YOUR_WALLET_ADDRESS'); // user address
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farms = new Farms(rpc);
const kamino = new Kamino('mainnet-beta', rpc);
const now = new Decimal(Math.floor(Date.now() / 1000));
const sumStake = (m: Map<unknown, Decimal>): Decimal =>
[...m.values()].reduce((acc, v) => acc.add(v), new Decimal(0));
const positions = await farms.getAllFarmsForUser(USER, now);
if (positions.size === 0) console.log('No farm positions for', USER);
for (const [farm, userFarm] of positions) {
const activeShares = sumStake(userFarm.activeStakeByDelegatee);
const isStrategyFarm = userFarm.strategyId.toString() !== DEFAULT_PUBLIC_KEY.toString();
const price = isStrategyFarm ? await kamino.getStrategySharePrice(userFarm.strategyId) : null;
console.log({
farm: farm.toString(),
activeShares: activeShares.toString(),
valueUsd: price ? '$' + activeShares.mul(price).toFixed(2) : 'n/a',
});
}
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`getAllFarmsForUser` returns a `Map<farmAddress, UserFarm>` with stake in share units. For USD value, multiply active shares by the share price. On a strategy farm the share price comes from the kliquidity SDK, because the stake token is a strategy share rather than an oracle-tracked asset.
</Note>
### Get Position Detail
Deep detail for one farm: active stake plus pending deposit and withdrawal, with their unlock timestamps.
```typescript icon="typescript" getPositionDetail theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { Farms } from '@kamino-finance/farms-sdk';
import { Kamino } from '@kamino-finance/kliquidity-sdk';
import Decimal from 'decimal.js';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); // non-delegated farm
const STRATEGY = address('ErNSr9mSDC9EkuvfUZQvedqTFiybvRsF838tiXn3Ektd'); // for the share price
const USER = address('YOUR_WALLET_ADDRESS'); // user address
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farms = new Farms(rpc);
const kamino = new Kamino('mainnet-beta', rpc);
const now = new Decimal(Math.floor(Date.now() / 1000));
const sumStake = (m: Map<unknown, Decimal>): Decimal =>
[...m.values()].reduce((acc, v) => acc.add(v), new Decimal(0));
const tsToText = (ts: { toString(): string }): string => {
const secs = Number(ts.toString());
return secs > 0 ? new Date(secs * 1000).toISOString() : 'none';
};
const userFarm = await farms.getUserForUndelegatedFarm(USER, FARM, now);
const active = sumStake(userFarm.activeStakeByDelegatee);
const pendingDeposit = sumStake(userFarm.pendingDepositStakeByDelegatee);
const pendingWithdrawal = sumStake(userFarm.pendingWithdrawalUnstakeByDelegatee);
const price = await kamino.getStrategySharePrice(STRATEGY);
console.log({
activeStakeEarning: active.toString(),
valueUsd: '$' + active.mul(price).toFixed(2),
pendingDepositWarmingUp: pendingDeposit.toString(),
becomesActiveAt: tsToText(userFarm.userState.pendingDepositStakeTs),
pendingWithdrawalCoolingDown: pendingWithdrawal.toString(),
withdrawableAt: tsToText(userFarm.userState.pendingWithdrawalUnstakeTs),
});
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
Active stake earns rewards. Pending deposit is warming up and becomes active at `pendingDepositStakeTs`. Pending withdrawal is cooling down and becomes withdrawable at `pendingWithdrawalUnstakeTs`. The stake amounts come back in share units; the unlock timestamps live on the raw `userState`.
</Note>
### Get Lockup and Cooldown
A wallet's deposit lockup status on a farm: the full lockup period, how much the user has left, and when it frees up.
```typescript icon="typescript" getLockupAndCooldown theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { Farms } from '@kamino-finance/farms-sdk';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const FARM = address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'); // non-delegated farm
const USER = address('YOUR_WALLET_ADDRESS'); // user address
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farms = new Farms(rpc);
const nowSeconds = Math.floor(Date.now() / 1000);
const { lockupRemainingDuration, farmLockupOriginalDuration, farmLockupExpiry } =
await farms.getLockupDurationAndExpiry(FARM, USER, nowSeconds);
const status =
lockupRemainingDuration <= 0
? 'unlocked'
: `locked until ${new Date(farmLockupExpiry * 1000).toISOString()}`;
console.log({
farmLockupPeriodSeconds: farmLockupOriginalDuration,
remainingForUserSeconds: lockupRemainingDuration,
status,
});
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`getLockupDurationAndExpiry` returns three values in seconds: the farm's full lockup period, how much of it this user has left, and the unix expiry timestamp. This is the deposit lockup. It is distinct from the per-unstake withdrawal cooldown shown in the position detail, which is driven by `pendingWithdrawalUnstakeTs` once you actually unstake. Use it to enable or disable a withdraw button and show a countdown.
</Note>
### Get Pending Rewards
A wallet's claimable rewards on a farm, per reward token, in tokens and USD, with whether each has cleared its claim cooldown.
```typescript icon="typescript" getPendingRewards theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { Farms, FarmState, DEFAULT_PUBLIC_KEY } from '@kamino-finance/farms-sdk';
import Decimal from 'decimal.js';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const ORACLE_PRICES_URL = 'https://api.kamino.finance/oracles/prices?source=scope';
const FARM = address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'); // farm address
const USER = address('YOUR_WALLET_ADDRESS'); // user address
const rpc = createSolanaRpc(RPC_ENDPOINT);
const farms = new Farms(rpc);
const now = new Decimal(Math.floor(Date.now() / 1000));
const farmState = await FarmState.fetch(rpc, FARM);
if (!farmState) console.log(`Farm not found: ${FARM}`);
const { userState } = await farms.getUserStateKeyForUndelegatedFarm(USER, FARM);
const rows: Array<{ mint: string; price: string }> = await (await fetch(ORACLE_PRICES_URL)).json();
const priceByMint = new Map(rows.map((r) => [r.mint, new Decimal(r.price)]));
// getOraclePrices reads the farm's on-chain Scope prices, which the rewards calc needs.
const oraclePrices = await farms.getOraclePrices(farmState);
const { userPendingRewardAmounts, hasReward } = farms.getUserPendingRewards(
userState,
farmState,
now,
oraclePrices,
);
console.log('Has claimable reward:', hasReward);
farmState.rewardInfos.forEach((info, i) => {
const mint = info.token.mint;
if (mint.toString() === DEFAULT_PUBLIC_KEY.toString()) return;
const decimals = info.token.decimals.toNumber();
const amount = userPendingRewardAmounts[i].div(new Decimal(10).pow(decimals));
if (amount.lte(0)) return;
const price = priceByMint.get(mint.toString());
const minClaim = Number(info.minClaimDurationSeconds.toString());
const sinceClaim = now.toNumber() - Number(userState.lastClaimTs[i].toString());
const claimable = sinceClaim >= minClaim ? 'Yes' : `in ~${Math.ceil((minClaim - sinceClaim) / 60)}m`;
console.log({
reward: mint.toString(),
pending: amount.toString(),
valueUsd: price ? '$' + amount.mul(price).toFixed(2) : 'n/a',
claimable,
});
});
```
<a href="https://github.com/Kamino-Finance/farms-sdk">
<Icon icon="github" />
<span>View Code</span>
</a>
<Note>
`getUserPendingRewards` returns one pending amount per reward slot in raw units, plus a `hasReward` flag. Humanize each amount by its reward-token decimals and value it with the oracle endpoint. `getOraclePrices(farmState)` takes the `FarmState` object, not the address. A reward is claimable once `now` minus `lastClaimTs` has cleared the reward's `minClaimDurationSeconds`.
</Note>
## Position Types
TypeScript shapes returned by the Farms SDK for user position reads.
<Tabs>
<Tab title="UserFarm">
A wallet's position in one farm, with stake in share units, grouped by delegatee.
```typescript theme={null}
type UserFarm = {
userStateAddress: Address;
farm: Address;
stakedToken: Address;
activeStakeByDelegatee: Map<Address, Decimal>;
pendingDepositStakeByDelegatee: Map<Address, Decimal>;
pendingWithdrawalUnstakeByDelegatee: Map<Address, Decimal>;
pendingRewards: PendingReward[];
delegateAuthority: Address;
strategyId: Address;
userState: UserState;
};
```
</Tab>
<Tab title="UserState">
On-chain user account. Stake amounts are WAD-scaled; timestamps are unix seconds.
```typescript theme={null}
class UserState {
owner: Address;
farmState: Address;
isFarmDelegated: number;
activeStakeScaled: BN;
pendingDepositStakeScaled: BN;
pendingDepositStakeTs: BN;
pendingWithdrawalUnstakeScaled: BN;
pendingWithdrawalUnstakeTs: BN;
lastClaimTs: BN[]; // per reward slot
rewardsIssuedUnclaimed: BN[]; // per reward slot
}
```
</Tab>
<Tab title="PendingReward">
One reward t프로젝트로 돌아가기