> For the complete documentation index, see [llms.txt](https://docs.pharos.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pharos.xyz/native-staking/developer-guide.md).

# Developer Guide

The native staking contract is `0x4100000000000000000000000000000000000000` on [Pacific Mainnet](https://docs.pharos.xyz/getting-started/network/pacific-mainnet.md) and [Atlantic Testnet](https://docs.pharos.xyz/getting-started/network/atlantic-testnet.md). Pool IDs are `bytes32`; user addresses are `address`.

Use the complete ABI matching the deployed Staking implementation, including its read methods and events. Amounts are integers in wei: **1 PROS = 10^18 wei**. Use integer arithmetic or `BigInt` throughout.

## Find Validators

Use `getAllValidators()` to discover current pools and `getValidator(poolId)` for each pool's details. This list does not include every historical pool.

Determine status by checking `isValidatorPendingExit(poolId)` first, then `isValidatorActive(poolId)` and `isValidatorPendingAdd(poolId)`. An existing pool outside these sets is Inactive. The `status` field alone is insufficient; a zero-value result for a nonexistent pool must not be displayed as an Inactive validator.

## Delegation and Rewards

| Method                                    | Behavior                                                                                 |
| ----------------------------------------- | ---------------------------------------------------------------------------------------- |
| `delegate(poolId)`                        | Send native PROS in transaction `value`. No ERC-20 approval or separate amount argument. |
| `delegateWithApproval(poolId, signature)` | Delegate with the designated approver's signature and native transaction value.          |
| `getDelegatorReward(poolId, user)`        | Read current unclaimed rewards, including rewards attributable to matured pending stake. |
| `claimReward(poolId)`                     | Claim all available rewards for the caller in this pool.                                 |
| `compoundRewards(poolId)`                 | Move eligible rewards into pending stake in the same pool.                               |

For the pool owner, `getDelegatorReward(poolId, owner)` includes unclaimed validator commission and self-stake rewards. Both `claimReward` and `compoundRewards` act on the caller's own rewards; the owner wallet must make the call to access the owner's balance. See [Commission and Rewards](https://docs.pharos.xyz/native-staking/validator-guide/commission-and-rewards.md) for examples.

Before delegation, check `paused()`, pool capacity, `delegationEnabledMapping(poolId)`, `getDelegationApprover(poolId)`, and the user's pending stake. The pool must be Active or Pending Add and must not be Pending Exit. Pending Exit takes precedence over Active during exit processing.

Compounding does not check the delegation switch, approval requirement, or Active status. Apply the [compounding conditions](https://docs.pharos.xyz/native-staking/rewards-and-claiming.md#compound-rewards) separately; compounding in an inactive pool does not reactivate it or start new rewards.

Approval uses EIP-712 with domain name `PharosStaking`, version `1`, the target `chainId`, and the staking proxy as `verifyingContract`. The signed type is `DelegationApproval(bytes32 poolId,address delegator,uint256 nonce)`. Read the nonce from `getDelegationApprovalNonce(poolId, user)`; the delegator must be the transaction caller. The signature contains no amount or expiry and is consumed by a successful delegation.

For automated compounding, users call `setCompoundOperator(poolId, operator, validUntil)`, where expiry is a future Unix timestamp in seconds (`uint64`). An authorized operator calls `compoundRewardsFor(poolId, user)` and pays gas. Check the `authorized` result from `getCompoundOperator`; revoke with the zero address and an expiry of `0`. This authorization cannot withdraw funds.

## Read Positions Correctly

Read related state at the same block to avoid mixing snapshots across an epoch boundary.

| Display                 | Source                                                                                               |
| ----------------------- | ---------------------------------------------------------------------------------------------------- |
| Current epoch           | `currentEpoch()` or `getBlockchainInfo()`                                                            |
| Effective user stake    | `getDelegator(...).stake`, plus pending stake when `getPendingStakeInfo(...).canActivateNow` is true |
| Pending stake           | `getPendingStakeInfo(...)`; show separately only while it is not yet effective                       |
| Unclaimed rewards       | `getDelegatorReward(poolId, user)`; do not add pending-stake rewards again                           |
| Outstanding withdrawals | `getDelegator(...).pendingWithdrawStake`, including principal and rewards                            |
| Pool stake              | `getValidator(...).totalStake` includes pending stake; `stakeSnapshot` is used for rewards           |

`principalStake` excludes compounded rewards and is not interchangeable with effective stake. Global `totalStake()` is the sum of active pools' reward snapshots.

`getUserValidators(user)` can omit positions containing only immature pending stake or withdrawals. Supplement it with delegation events and `getUserActiveWithdrawalPoolsV5(user, cursor, limit)`, plus any legacy requests described below. This aggregate query scans all current and retained historical pools and can exceed RPC call gas limits; fall back to event-derived pool IDs and per-pool reads.

Treat RPC failures as unavailable data, not zero balances. Some validator-status getters also revert while the contract is paused.

## Withdrawals

Ordinary delegators use `undelegate(poolId)` for a full exit or `undelegatePartial(poolId, amount)` for a partial exit. The partial amount is effective stake, including compounded rewards; the resulting withdrawal also includes proportional unclaimed rewards. Owners use the [owner withdrawal methods](https://docs.pharos.xyz/native-staking/validator-guide/withdraw-or-exit.md).

1. Read `WithdrawalQueuedV5` for the request ID, amount, and actual `unlockEpoch`.
2. List outstanding IDs with `getActiveWithdrawalRequestIdsV5(poolId, user)` and read each through `getWithdrawalRequestV5(poolId, user, requestId)`. Request ID `0` is valid.
3. A request is claimable when it exists and `currentEpoch >= unlockEpoch`.
4. Use `claimStake(poolId)` for all unlocked requests, `claimStakeRequest(poolId, requestId)` for one, or `claimStakeRequests(poolId, requestIds)` for a batch of up to 64. An invalid, duplicate, or locked request reverts the whole batch.

`getDelegatorPendingWithdraw` summarizes only the earliest outstanding V5 request; it is not the pool's total withdrawal balance. Preserve history from events because claimed request details are deleted. V5 and compatibility events can describe the same withdrawal; count it once.

For pre-upgrade requests, query `getUserPendingUndelegations(user)` and claim through `claimStake(poolId)`. Legacy array indices are not V5 request IDs. Outstanding legacy requests must be claimed before the same user can delegate again or create V5 withdrawals in that pool.

## Configuration and Transaction Checks

Read the ChainConfig address from `cfg()` and string values through `getConfig(key)`. Relevant keys include `chain.epoch_duration` (milliseconds), `staking.min_delegator_stake`, `staking.max_staking_pool_value`, `staking.delegation_withdraw_effective_epoch`, and `staking.withdraw_effective_epoch`. An RPC error or invalid value must not trigger a default intended for an unset configuration.

Simulate writes with the actual caller, value, and signature before submission. Confirm successful receipts and business events: `StakeDelegated.amount` is the accepted stake, while withdrawal events supply the final request amount and unlock epoch. A transaction hash alone does not confirm success. Users do not call `advanceEpoch()`; the chain advances epochs.

When paused, new delegations, unstaking requests, reward claims, and compounding are blocked. Claims for already unlocked withdrawals and revocation of compound authorization remain available.

Reward payouts use `CoinMinted`, which Pharos nodes process to credit native PROS. Confirm payouts through receipts, business events, and balances; a generic local EVM does not mint native balances merely because this event is emitted.

## Estimate Delegator APR

For an estimate based on inflation rewards after commission, use:

```
APR = (currentInflationRate() / 100000)
    × (lastInflationTotalSupplySnapshot() / totalStake())
    × (1 - getCommissionRate(poolId) / 10000)
```

This is a mathematical ratio; preserve precision with scaled integer arithmetic and multiply by 100 to display a percentage. Display it only for Active pools with staking rewards enabled (`chain.enable_pos_staking`), valid snapshots, and nonzero `totalStake()`.

The estimate excludes transaction priority fees and the effect of compounding. It is not APY or a guaranteed return. Do not use `getValidatorApr(poolId)` directly: it calculates a different metric and can retain old snapshots for exited pools.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.pharos.xyz/native-staking/developer-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
