bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 15쪽
in the Quick Start guide for full details.
### Beneficiary functions
The following functions are callable only by the [beneficiary](#operatorrewarder-beneficiary) of the `OperatorRewarder` contract:
#### Claim commission fee
See [Claim commission fees](#claim-commission-fees) in the Quick Start guide for full details.
#### Set commission fee
Updates the commission fee taken from delegator rewards. The new fee cannot exceed the `maxFeeBasisPoints` set by the owner.
Before updating the fee, the contract internally claims all currently accrued fees held by the contract to the beneficiary address.
```solidity
// Sets the fee to 10% (1000 basis points)
operatorRewarder.setFee(1000);
```
### Owner functions
The following functions are callable only by the owner of the `OperatorRewarder` contract:
#### Set maximum fee
Updates the maximum commission fee the beneficiary is allowed to set. If the new maximum is lower than the current fee, then the current fee is automatically adjusted down and unpaid fees are claimed to the beneficiary.
```solidity
// Sets the max fee to 20% (2000 basis points)
operatorRewarder.setMaxFee(2000);
```
#### Transfer beneficiary
Transfers the beneficiary role to a new address. Does not automatically claim unpaid fees for the outgoing beneficiary, allowing for the recovery of any unpaid fees in the event that a beneficiary account is compromised or lost.
```solidity
operatorRewarder.transferBeneficiary(newBeneficiaryAddress);
```
### View functions
#### Get fee basis points
Returns the current commission fee percentage applied to delegator rewards.
```solidity
// Returns the current fee in basis points (e.g., 1000 = 10%)
uint16 currentFee = operatorRewarder.feeBasisPoints();
```
#### Get maximum fee basis points
Returns the maximum fee percentage the beneficiary is allowed to set.
```solidity
uint16 maxFee = operatorRewarder.maxFeeBasisPoints();
```
#### Get unpaid fee
Returns the total amount of unclaimed $ZAMA commission fees accumulated for the beneficiary.
```solidity
uint256 unpaid = operatorRewarder.unpaidFee();
```
#### Get earned rewards
Returns the amount of $ZAMA rewards accrued by a delegator that are available to be claimed.
```solidity
uint256 pending = operatorRewarder.earned(delegatorAddress);
```
#### Get historical reward
Returns the cumulative total of all rewards generated by this pool since the rewarder was started, net of unpaid fees. This is computed as the sum of:
* The rewarder's current $ZAMA token balance.
* Rewards earned by the pool from `ProtocolStaking` but not yet claimed.
* All rewards already paid out to delegators.
minus the unpaid fee portion owed to the beneficiary.
```solidity
uint256 historical = operatorRewarder.historicalReward();
```
#### Get owner
Returns the owner address (inherited from `ProtocolStaking`).
```solidity
address protocolOwner = operatorRewarder.owner();
```
#### Get beneficiary
Returns the current beneficiary address.
```solidity
address beneficiaryAddr = operatorRewarder.beneficiary();
```
#### Get claimer
Returns the authorized claimer for a given receiver address. If no claimer is set, the receiver address itself is returned.
```solidity
address authorizedClaimer = operatorRewarder.claimer(receiverAddress);
```
#### Get token
Returns the staking token ($ZAMA) address.
```solidity
IERC20 stakingToken = operatorRewarder.token();
```
#### Get ProtocolStaking
Returns the address of the linked `ProtocolStaking` contract.
```solidity
address protocolStakingAddr = address(operatorRewarder.protocolStaking());
```
#### Get OperatorStaking
Returns the address of the linked `OperatorStaking` contract.
```solidity
address operatorStakingAddr = address(operatorRewarder.operatorStaking());
```
#### Check started
Returns `true` if the rewarder has been started and is accepting reward claims.
```solidity
bool started = operatorRewarder.isStarted();
```
#### Check shutdown
Returns `true` if the rewarder has been shut down, meaning it no longer computes new rewards from the `ProtocolStaking` contract.
```solidity
bool shutdown = operatorRewarder.isShutdown();
```
### Events
| Event | Description |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `BeneficiaryTransferred(oldBeneficiary, newBeneficiary)` | Emitted when the beneficiary is updated. |
| `ClaimerAuthorized(receiver, claimer)` | Emitted when a delegator authorizes another address to claim their rewards. |
| `FeeClaimed(beneficiary, amount)` | Emitted when commission fees are claimed. |
| `FeeUpdated(oldFee, newFee)` | Emitted when the commission fee is changed. |
| `MaxFeeUpdated(oldFee, newFee)` | Emitted when the maximum allowed fee is changed by the owner. |
| `RewardsClaimed(receiver, amount)` | Emitted when a delegator claims their rewards. |
| `Shutdown()` | Emitted when the `OperatorRewarder` is shut down by the owner, preventing future rewards distribution. |
### Errors
| Error | Cause |
| ----------------------------------------------------- | ------------------------------------------------------------------------ |
| `AlreadyShutdown()` | Attempted an action, but the rewarder is already shut down. |
| `AlreadyStarted()` | Attempted to start a rewarder that has already been started. |
| `BeneficiaryAlreadySet(beneficiary)` | The new beneficiary is identical to the current one. |
| `CallerNotBeneficiary(caller)` | The caller is not the authorized beneficiary. |
| `CallerNotOperatorStaking(caller)` | The caller is not the linked `OperatorStaking` contract. |
| `CallerNotProtocolStakingOwner(caller)` | The caller is not the owner of the `ProtocolStaking` contract. |
| `ClaimerAlreadySet(receiver, claimer)` | The new claimer is identical to the current one. |
| `ClaimerNotAuthorized(receiver, claimer)` | The caller does not have permission to claim on behalf of the delegator. |
| `FeeAlreadySet(feeBasisPoints)` | The new fee is identical to the current one. |
| `InvalidBasisPoints(basisPoints)` | The basis points input is out of bounds (e.g., above 10000). |
| `InvalidBeneficiary(beneficiary)` | The provided beneficiary address is zero. |
| `InvalidClaimer(claimer)` | The provided claimer address is zero. |
| `MaxBasisPointsExceeded(basisPoints, maxBasisPoints)` | The new fee exceeds the maximum set by the owner. |
| `MaxFeeAlreadySet(maxFeeBasisPoints)` | The new maximum fee is identical to the current one. |
| `NotStarted()` | Attempted an action, but the rewarder hasn't been started yet. |
## Staking rewards calculation
{% hint style="info" %}
For a full interactive walkthrough with example outputs, see the [APY notebook](https://github.com/zama-ai/fhevm/blob/main/protocol-contracts/contracts/staking/APY.ipynb).
{% endhint %}
### Calculating the rewards rate
The rewards rate is defined as tokens-per-second and is determined as follows:
1. The total yearly rewards amount to be paid out is determined once a year as a percentage of the current total supply of $ZAMA. This percentage (`TOTAL_YEARLY_INFLATION_PROPORTION`) is a variable controlled by the [Protocol DAO governance](/protocol/protocol-apps/governance/governance) and is currently set to **5%**.
2. This total amount is divided between the roles, with 40% going to coprocessor operators and 60% to KMS operators.
3. Each per role amount is converted into a per role tokens-per-second reward rate for the year.
```python
SECONDS_PER_YEAR = 365 * 24 * 60 * 60
TOTAL_SUPPLY = 11_000_000_000 * 10**18
def get_reward_rate(total_yearly_inflation_proportion: float) -> tuple[int, int]:
"""
Compute the reward rates for KMS and Coprocessors based on total supply.
:param total_yearly_inflation_proportion: Decimal value of the total yearly inflation (e.g. 0.05)
:return: A tuple (rate_kms, rate_coprocessors) in tokens per second (with 18 decimals)
"""
total_fees_rewards = int(TOTAL_SUPPLY * total_yearly_inflation_proportion)
total_fees_rewards_kms = int(total_fees_rewards * 0.60)
total_fees_rewards_coprocessors = int(total_fees_rewards * 0.40)
rate_kms = total_fees_rewards_kms // SECONDS_PER_YEAR
rate_coprocessors = total_fees_rewards_coprocessors // SECONDS_PER_YEAR
return rate_kms, rate_coprocessors
```
### Calculating the APR
The native APR for delegating to an operator depends on several factors:
1. [**Reward Rate:**](#calculating-the-rewards-rate) The rate of tokens per second, retrieved from `ProtocolStaking.rewardRate()`.
2. **Tokens per Pool:** The number of deposited tokens in each eligible `OperatorStaking` pool, retrieved from `ProtocolStaking.balanceOf(address(OperatorStaking))`.
3. **Fees per Pool:** The commission fee for each corresponding `OperatorRewarder` in basis points, retrieved from `OperatorRewarder.feeBasisPoints()`.
```python
import math
SECONDS_PER_YEAR = 365 * 24 * 60 * 60
def compute_native_apr(
reward_rate: int,
num_tokens_per_pool: list[int],
fees_per_pool: list[int]
) -> list[float]:
"""
Compute the native APR for each eligible OperatorStaking pool.
:return: List of percentage APRs for each pool
"""
assert len(num_tokens_per_pool) == len(fees_per_pool), "Pool/Fee length mismatch"
assert all(0 <= fee <= 10000 for fee in fees_per_pool), "Fees must be within 0 and 10000"
assert all(0 <= tokens for tokens in num_tokens_per_pool), "Token amounts must be non-negative"
assert reward_rate >= 0, "Reward rate must be non-negative"
weights = [int(math.sqrt(tokens)) for tokens in num_tokens_per_pool]
total_weight = sum(weights)
fee_factors = [1 - (fee / 10000) for fee in fees_per_pool]
rate_per_sec_per_pool = [reward_rate * (weight / total_weight) for weight in weights]
pool_aprs = []
for i in range(len(fee_factors)):
net_reward_per_sec = rate_per_sec_per_pool[i] * fee_factors[i]
pool_apr = (net_reward_per_sec / num_tokens_per_pool[i]) * SECONDS_PER_YEAR * 100
pool_aprs.append(pool_apr)
return pool_aprs
```
## Upgradeability
The `ProtocolStaking` and `OperatorStaking` contracts are upgradeable using the **UUPS (Universal Upgradeable Proxy Standard)** with 2-step ownership transfer. Only the owner can upgrade these contracts.
The `OperatorRewarder` contract is not upgradeable.
# Confidential Tokens
# Confidential wrapper
This document gives an overview of the **Confidential Wrapper,** a smart contract that wraps standard ERC-20 tokens into confidential ERC-7984 tokens. Built on Zama's FHEVM, it enables privacy-preserving token transfers where balances and transfer amounts remain encrypted.
## Terminology
* **Confidential Token**: The ERC-7984 confidential token wrapper.
* **Underlying Token**: The standard ERC-20 token wrapped by the confidential wrapper.
* **Wrapping**: Converting ERC-20 tokens into confidential tokens.
* **Unwrapping**: Converting confidential tokens back into ERC-20 tokens.
* **Rate**: The conversion ratio between underlying token units and confidential token units (due to decimal differences).
* **Operator**: An address authorized to transfer confidential tokens on behalf of another address.
* **Observer**: An address authorized by the wrapper owner to decrypt the wrapper's encrypted amounts on its behalf. See [Observers](#observers).
* **Denylist**: The set of addresses barred from wrapping, unwrapping, and transferring. See [Denylist](#denylist).
* **Owner**: The owner of the wrapper contract. In the FHEVM protocol, this is initially set to the Protocol DAO governance (see [governance.md](/protocol/protocol-apps/governance/governance)). Ownership will then be transferred to the underlying token's owner.
* **Registry**: The registry contract that maps ERC-20 tokens to their corresponding confidential wrappers. More information [here](/protocol/protocol-apps/confidential-tokens/wrapper-registry).
* **ACL**: The Access Control List (ACL) contract that manages the permissions for encrypted amounts. More information in the [FHEVM library documentation](https://docs.zama.org/protocol/protocol/overview/library#access-control).
* **Input proof**: A proof that the encrypted amount is valid. More information in the [Zama SDK documentation](https://docs.zama.org/protocol/sdk/guides/encrypt-decrypt).
* **Public decryption**: A request to publicly decrypt an encrypted amount. More information in the [Zama SDK documentation](https://docs.zama.org/protocol/sdk/guides/encrypt-decrypt).
## Contract information
| Resource | Link |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Deployed addresses | [Addresses directory](/protocol/protocol-apps/addresses) |
| Source code | [ConfidentialWrapper.sol](https://github.com/zama-ai/protocol-apps/blob/main/contracts/confidential-wrapper/contracts/ConfidentialWrapper.sol) |
## Structure
```mermaid
flowchart
subgraph Ethereum
Protocol-DAO -- owner --> Registry
Registry -- registers --> Confidential-Wrapper
Protocol-DAO -- owner --> Confidential-Wrapper
end
```
More information on the registry contract can be found in the [wrapper-registry.md](/protocol/protocol-apps/confidential-tokens/wrapper-registry) file.
## Quick Start
{% hint style="warning" %}
### **Decimal conversion**
The wrapper enforces a maximum number of decimals for the confidential token. When wrapping, amounts are rounded down and excess tokens are refunded. Currently, this maximum is set to **6 decimals** only. See [Maximum number of decimals](#maximum-number-of-decimals) for more information.
{% endhint %}
{% hint style="warning" %}
### **Unsupported tokens**
**Shielded Zama protocol staking shares do not earn rewards**
Operator staking shares issued by the Zama [staking protocol](/protocol/protocol-apps/staking) are vault-style shares that represent a proportional claim on the underlying staked assets. Staking rewards are accrued to the active holder of the shares. Wrapping these shares transfers their custody to the confidential wrapper contract, which becomes the address of record and the effective recipient of all future rewards. Consequently, holders of shielded shares do not earn staking rewards as long as their underlying shares remain shielded.
Non-standard tokens are not supported. This includes fee-on-transfer, deflationary, and rebasing tokens. See [Non-standard token types](#non-standard-token-types) for a full breakdown.
{% endhint %}
### Get the confidential wrapper address of an ERC-20 token
An onchain registry contract maps ERC-20 tokens to their corresponding verified confidential wrappers. Make sure to check the registry contract to ensure the confidential wrapper is valid before wrapping. More information [here](/protocol/protocol-apps/confidential-tokens/wrapper-registry).
### Wrap ERC-20 → Confidential token
There are two ways to wrap. The single-transaction `transferAndCall` path is **recommended** whenever the underlying token supports it.
#### Recommended: single transaction with `transferAndCall` (ERC-1363)
If the underlying token implements the [ERC-1363](https://eips.ethereum.org/EIPS/eip-1363) extension (`transferAndCall`), wrapping can be done in a **single transaction** without a prior approval. The wrapper implements `IERC1363Receiver`, so transferring the underlying token directly to the wrapper triggers its `onTransferReceived` callback, which mints the confidential token and refunds any excess.
```solidity
// `data` carries the recipient; pass empty bytes to wrap to msg.sender.
underlyingToken.transferAndCall(address(wrapper), amount, abi.encodePacked(to));
```
This avoids the two-transaction `approve` + `wrap` flow and its associated allowance management. The same `Wrap` event is emitted and excess tokens are refunded to the original sender.
`data` must be empty to wrap to the sender, or exactly the 20-byte packed address `abi.encodePacked(to)`. Anything else reverts with `InvalidWrapRecipientEncoding`, including the 32-byte `abi.encode(to)`.
{% hint style="info" %}
### **ERC-1363 support**
Only tokens that implement the ERC-1363 `transferAndCall` extension can use this path. For tokens without it, use the `approve` + `wrap` flow below.
{% endhint %}
#### Fallback: `approve` + `wrap`
For underlying tokens that do not support ERC-1363, prior to wrapping the confidential wrapper contract must be approved by the `msg.sender` on the underlying token.
```solidity
wrapper.wrap(to, amount);
```
The wrapper will mint the corresponding confidential token to the `to` address and refund the excess tokens to the `msg.sender` (due to decimal conversion).
Both paths emit a `Wrap` event where `roundedAmount` is the actual amount of underlying tokens wrapped (i.e. `amount` rounded down to the nearest multiple of `rate()`):
```solidity
event Wrap(address indexed to, uint256 roundedAmount, euint64 encryptedWrappedAmount);
```
Considerations:
* `amount` must be a value using the same decimal precision as the underlying token.
* `to` must not be the zero address.
{% hint style="info" %}
### **Low amount handling**
If the amount is less than the rate, the wrapping will succeed but the recipient will receive 0 confidential tokens and the excess tokens will be refunded to the `msg.sender`.
{% endhint %}
### Unwrap confidential token → ERC-20
Unwrapping is a **two-step asynchronous process**: an `unwrap` must be first made and then finalized with `finalizeUnwrap`. The `unwrap` function can be called with or without an input proof.
#### 1) Unwrap request
{% hint style="warning" %}
### **Unsupported `from`**
Accounts with a zero balance that have never held tokens cannot be the `from` address in unwrap requests.
{% endhint %}
**With input proof**
{% hint style="info" %}
### **Input proof**
To unwrap any amount of confidential tokens, the `from` address must first create an encrypted input to generate an `encryptedAmount` (`externalEuint64`) along its `inputProof`. The amount to be encrypted must use the same decimal precision as the confidential wrapper. More information in the [Zama SDK documentation](https://docs.zama.org/protocol/sdk/guides/encrypt-decrypt).
{% endhint %}
```solidity
wrapper.unwrap(from, to, encryptedAmount, inputProof);
```
Alternatively, an unwrap request can be made without an input proof if the encrypted amount (`euint64`) is known to `from`. For example, this can be the confidential balance of `from`.
This requests an unwrap request of `encryptedAmount` confidential tokens from `from`. Considerations:
* `msg.sender` must be `from` or an approved operator for `from`.
* `from` must not be the zero address.
* `encryptedAmount` will be burned in the request.
* **NO** transfer of underlying tokens is made in this request.
It emits an `UnwrapRequested` event:
```solidity
event UnwrapRequested(address indexed receiver, bytes32 indexed unwrapRequestId, euint64 amount);
```
**Without input proof**
Alternatively, an unwrap request can be made without an input proof if the encrypted amount (`euint64`) is known to `from`. For example, this can be the confidential balance of `from`.
```solidity
wrapper.unwrap(from, to, encryptedAmount);
```
On top of the above unwrap request considerations:
* `msg.sender` must be approved by ACL for the given `encryptedAmount` ⚠️ (see [ACL documentation](https://docs.zama.org/protocol/protocol/overview/library#access-control)).
#### 2) Finalize unwrap
The unwrap request must be finalized with `finalizeUnwrap`. The `unwrapRequestId` is the identifier emitted by the `UnwrapRequested` event in the `unwrap` function.
{% hint style="info" %}
### **Public decryption**
The encrypted amount `unwrapAmount_` emitted by the `UnwrapRequested` event must be publicly decrypted to get the `unwrapAmountCleartext` along its `decryptionProof`. More information in the [Zama SDK documentation](https://docs.zama.org/protocol/sdk/guides/encrypt-decrypt).
{% end프로젝트로 돌아가기