bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 9쪽
ods(stream: DonationStream) -> uint256:
"""
@dev Return the number of due periods for a stream.
"""
if (
stream.donor == empty(address)
or stream.periods_remaining == 0
or stream.period_length == 0
or block.timestamp < stream.next_ts
):
return 0
return min(
(block.timestamp - stream.next_ts) // stream.period_length + 1,
stream.periods_remaining,
)
```
**▶Example▼**
<a id="streams_and_rewards_due"></a>
### `streams_and_rewards_due`
`DonationStreamer.streams_and_rewards_due() -> (DynArray[uint256, 1024], DynArray[uint256, 1024]): view`
Returns two arrays: the IDs of all due streams and their corresponding ETH rewards, ordered from newest to oldest. Iterates over up to 1024 streams starting from the most recent. This function is intended for off-chain use (e.g., by keeper bots) and should not be called on-chain.
Returns: a tuple of (due stream IDs, corresponding rewards) (`DynArray[uint256, 1024]`, `DynArray[uint256, 1024]`).
**<>Source code▼**
```vyper
@view
@external
def streams_and_rewards_due(
) -> (DynArray[uint256, N_MAX_VIEW], DynArray[uint256, N_MAX_VIEW]):
"""
@notice Return due stream ids and rewards, newest first.
@dev Not meant to be called onchain; iterates over up to N_MAX_VIEW streams starting from the newest.
"""
due_ids: DynArray[uint256, N_MAX_VIEW] = empty(DynArray[uint256, N_MAX_VIEW])
rewards: DynArray[uint256, N_MAX_VIEW] = empty(DynArray[uint256, N_MAX_VIEW])
count: uint256 = self.stream_count
if count == 0:
return due_ids, rewards
# Walk backward from newest to oldest, capped for view usage.
limit: uint256 = min(count, N_MAX_VIEW)
for i: uint256 in range(limit, bound=N_MAX_VIEW):
stream_id: uint256 = count - 1 - i
stream: DonationStream = self.streams[stream_id]
periods_due: uint256 = self._due_periods(stream)
if periods_due == 0:
continue
due_ids.append(stream_id)
if periods_due == stream.periods_remaining:
rewards.append(stream.reward_remaining)
else:
rewards.append(stream.reward_per_period * periods_due)
return due_ids, rewards
```
**▶Example▼**
```shell
>>> DonationStreamer.streams_and_rewards_due()
([2, 0], [1000000000000000, 3000000000000000])
```
<a id="stream_count"></a>
### `stream_count`
`DonationStreamer.stream_count() -> uint256: view`
Returns the total number of streams that have been created. Stream IDs are sequential starting from 0.
Returns: total number of streams created (`uint256`).
**<>Source code▼**
```vyper
stream_count: public(uint256)
```
**▶Example▼**
<a id="streams"></a>
### `streams`
`DonationStreamer.streams(arg0: uint256) -> DonationStream: view`
Returns the full `DonationStream` struct for a given stream ID. Completed or cancelled streams return a zeroed-out struct.
The `DonationStream` struct contains the following fields:
| Field | Type | Description |
| --- | --- | --- |
| `donor` | `address` | Address of the stream creator; legacy field name |
| `pool` | `address` | Target FXSwap pool address |
| `coins` | `address[2]` | Token addresses for the pool |
| `amounts_per_period` | `uint256[2]` | Token amounts added as refuel per period |
| `period_length` | `uint256` | Duration of each period in seconds |
| `reward_per_period` | `uint256` | ETH reward paid per period execution |
| `next_ts` | `uint256` | Timestamp when the next period becomes due |
| `reward_remaining` | `uint256` | Total ETH rewards still to be paid out |
| `amounts_remaining` | `uint256[2]` | Token amounts still scheduled for refueling |
| `periods_remaining` | `uint256` | Number of periods left to execute |
| Input | Type | Description |
| --- | --- | --- |
| `arg0` | `uint256` | Stream ID |
Returns: the stream data (`DonationStream`).
**<>Source code▼**
```vyper
struct DonationStream:
# Static
donor: address
pool: address
coins: address[N_COINS]
amounts_per_period: uint256[N_COINS]
period_length: uint256
reward_per_period: uint256
# Dynamic
next_ts: uint256
reward_remaining: uint256
amounts_remaining: uint256[N_COINS]
periods_remaining: uint256
streams: public(HashMap[uint256, DonationStream])
```
**▶Example▼**
---
# Automating FXSwap Refuels
Source: [https://docs.curve.finance/developer/amm/fxswap/automation/overview](https://docs.curve.finance/developer/amm/fxswap/automation/overview)
The permissionless refuel-automation contracts let a provider escrow token amounts and ETH execution rewards, release refuels on a schedule, and pay any account that executes due periods. The deployed contract names retain the earlier `DonationStreamer` terminology; the product mechanism remains a **refuel**.
Use the [DonationStreamer reference](https://docs.curve.finance/developer/amm/fxswap/automation/donation-streamer.md) to create, inspect, execute, or cancel individual streams. [StreamExecutor](https://docs.curve.finance/developer/amm/fxswap/automation/stream-executor.md) is an optional batching helper for keeper bots.
<a id="contract-roles"></a>
## Contract roles
| Party or contract | Responsibility | Risk borne |
| --- | --- | --- |
| Refuel provider | Chooses pool, amounts, schedule, and reward; funds tokens and ETH upfront | Token custody, pool/refuel failures, and an underpriced execution reward |
| `DonationStreamer` | Escrows funds, tracks periods, calls the pool, refunds cancellation balances, and pays executors | No admin or upgrade authority; behavior is fixed by deployed code |
| Executor | Submits due streams and receives the funded ETH reward | Gas, failed execution, competition, and reward profitability |
| `StreamExecutor` | Finds due streams, batches up to 32 IDs per streamer call, and forwards earned ETH | A failing stream can revert the batch; the caller bears the transaction cost |
| FXSwap pool | Applies the refuel cap, unlock schedule, protection, fee, and recentering rules | Can reject a scheduled period when live pool guards are not satisfied |
There is no owner or admin on `DonationStreamer`. A stream can be cancelled only by the address stored in its immutable `donor` field. Anyone can execute a due stream.
<a id="lifecycle"></a>
## Lifecycle
1. **Approve tokens.** The provider approves `DonationStreamer` for each non-zero total amount.
2. **Create the stream.** `create_stream` pulls the full token totals and escrows `reward_per_period * n_periods` in ETH.
3. **Wait until due.** The stream starts with `next_ts` equal to the creation timestamp; later periods advance by `period_length`.
4. **Execute one or more periods.** Any caller can execute. The streamer approves the pool, calls `add_liquidity(..., donation=True)`, and pays the proportional ETH reward.
5. **Complete or cancel.** The final execution clears storage. Before completion, only the creator can cancel and recover remaining tokens and reward.
Integer division determines `amounts_per_period`. Any token remainder is included in the final period.
<a id="custody-and-approvals"></a>
## Custody and approvals
Creating a stream transfers the full scheduled token amounts into `DonationStreamer`; the provider no longer holds them. Approve the streamer address, not the pool, for stream creation. During execution, the streamer grants the target pool only the amount needed for that call and resets the allowance afterward.
The contract checks that:
- `coins[0]` and `coins[1]` match the target pool;
- at least one amount is non-zero;
- `period_length` and `n_periods` are positive;
- token balance changes exactly match requested transfers;
- the ETH value covers all configured rewards.
Fee-on-transfer and rebasing tokens therefore require explicit compatibility testing and can fail the exact-balance checks.
<a id="execution-economics-and-failure-recovery"></a>
## Execution economics and failure recovery
Executors decide whether the funded reward covers gas and transaction risk. The protocol does not top up an underpriced stream, and no keeper is obligated to execute it.
A due execution can fail because the FXSwap refuel cap is reached, token approval or transfer behavior changes, the target pool is incompatible, or another state-dependent pool guard reverts. Funds remain in stream storage after a reverted transaction. Recovery options are:
- retry after the pool state or cap allows the refuel;
- execute the stream directly instead of through a batch to isolate the failure; or
- have the creator cancel the stream and recover remaining escrow.
`execute(stream_id)` returns `False` when no period is due. A reverted pool call is different: it reverts the transaction and pays no reward.
`StreamExecutor.execute()` is atomic. If a streamed pool call reverts, the helper transaction reverts and does not forward rewards from that attempt. Keeper implementations should be able to fall back to individual `DonationStreamer.execute(id)` calls to isolate the failing stream.
<a id="discover-and-monitor-streams"></a>
## Discover and monitor streams
Index these events:
- `StreamCreated` to discover the stream ID, creator, pool, token totals, period length, period count, and reward;
- `StreamExecuted` to record periods completed, token amounts added, and reward paid;
- `StreamCancelled` to close the stream and record token and reward refunds.
Read `stream_count()` to bound enumeration and `streams(id)` for current storage. `is_due(id)` checks one stream. `streams_and_rewards_due()` returns up to the contract's view bound of due IDs and rewards for keeper discovery.
Completed or cancelled stream IDs are not reused; their `streams(id)` getter returns a zeroed struct. Indexers should derive lifecycle status from events plus current storage rather than treating an empty struct as proof of which terminal action occurred.
<a id="operational-checklist"></a>
## Operational checklist
- Verify the deployed automation address and source on each supported chain.
- Confirm the target pool and exact coin ordering before approval.
- Size executor rewards against realistic gas and competition.
- Monitor due-but-unexecuted periods and pool cap utilization.
- Alert on repeated execution failures and keep creator cancellation access available.
- Reconcile streamer token and ETH escrow with indexed stream state.
- Remember that automation schedules refuels; it does not guarantee recentering or prevent depletion.
---
# StreamExecutor
Source: [https://docs.curve.finance/developer/amm/fxswap/automation/stream-executor](https://docs.curve.finance/developer/amm/fxswap/automation/stream-executor)
The `StreamExecutor` is a convenience contract that batch-executes all due refuel streams in a single call and forwards the earned ETH rewards to the caller. It queries the [`DonationStreamer`](https://docs.curve.finance/developer/amm/fxswap/automation/donation-streamer.md) for due streams, executes them in chunks of 32, and sends the accumulated ETH balance to `msg.sender`.
This contract is designed for keeper bots that want to claim all available rewards with a single transaction. Streams can also be executed via the [frontend UI](https://curvefi.github.io/refuel-automation/).
Read the [automation overview](https://docs.curve.finance/developer/amm/fxswap/automation/overview.md) before operating a keeper. The caller bears gas and revert risk, and batching does not guarantee that a due stream is executable against current pool state.
`StreamExecutor.vy`
The source code for the `StreamExecutor.vy` contract can be found on [GitHub](https://github.com/curvefi/refuel-automation). The contract is written in [Vyper](https://vyperlang.org/) version `0.4.3`.
The contract is deployed at the same address on all chains (via CREATE3):
- Ethereum: [`0x4a8Cc5Cb8f7242be9944E1313793c2E5411c462A`](https://etherscan.io/address/0x4a8Cc5Cb8f7242be9944E1313793c2E5411c462A)
- Gnosis: [`0x4a8Cc5Cb8f7242be9944E1313793c2E5411c462A`](https://gnosisscan.io/address/0x4a8Cc5Cb8f7242be9944E1313793c2E5411c462A)
- Polygon: [`0x4a8Cc5Cb8f7242be9944E1313793c2E5411c462A`](https://polygonscan.com/address/0x4a8Cc5Cb8f7242be9944E1313793c2E5411c462A)
**{ }Contract ABI▼**
```json
[{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"execute","outputs":[],"stateMutability":"nonpayable","type":"function"}]
```
<a id="execution"></a>
## Execution
<a id="execute"></a>
### `execute`
`StreamExecutor.execute()`
Queries all due streams from the [`DonationStreamer`](https://docs.curve.finance/developer/amm/fxswap/automation/donation-streamer.md), executes them in batches of 32 via `execute_many`, and sends the accumulated ETH rewards to the caller. If no streams are due, the call succeeds but no ETH is sent.
**<>Source code▼**
```vyper
STREAMER: constant(address) = 0x2b786BB995978CC2242C567Ae62fd617b0eBC828
@external
def execute():
self._execute_due()
@internal
def _execute_due():
due_ids: DynArray[uint256, N_MAX_VIEW] = empty(DynArray[uint256, N_MAX_VIEW])
rewards: DynArray[uint256, N_MAX_VIEW] = empty(DynArray[uint256, N_MAX_VIEW])
due_ids, rewards = staticcall DonationStreamer(STREAMER).streams_and_rewards_due()
chunk: DynArray[uint256, N_MAX_EXECUTE] = empty(DynArray[uint256, N_MAX_EXECUTE])
for i: uint256 in range(len(due_ids), bound=N_MAX_VIEW):
chunk.append(due_ids[i])
if len(chunk) == N_MAX_EXECUTE:
extcall DonationStreamer(STREAMER).execute_many(chunk)
chunk = empty(DynArray[uint256, N_MAX_EXECUTE])
if len(chunk) > 0:
extcall DonationStreamer(STREAMER).execute_many(chunk)
if self.balance > 0:
send(msg.sender, self.balance)
```
**▶Example▼**
```shell
>>> StreamExecutor.execute()
```
<a id="__default__"></a>
### `__default__`
`StreamExecutor.__default__()`
Payable fallback function that allows the contract to receive ETH from the `DonationStreamer` during stream execution. The `DonationStreamer` sends ETH rewards to `msg.sender` (the `StreamExecutor`) which are then forwarded to the original caller in the `execute` function.
**<>Source code▼**
```vyper
@external
@payable
def __default__():
pass
```
**▶Example▼**
```shell
# ETH is received automatically when DonationStreamer pays rewards
# No direct user interaction needed
```
---
# Building on FXSwap
Source: [https://docs.curve.finance/developer/amm/fxswap/guides/building](https://docs.curve.finance/developer/amm/fxswap/guides/building)
Protocols can compose FXSwap swaps and LP positions into vaults, strategies, collateral systems, and other financial applications. Safe composition requires separating user-owned LP supply from refuel accounting, valuing positions against executable withdrawals, and treating pool price getters as AMM state rather than automatically safe lending oracles.
Start with the [swap integration guide](https://docs.curve.finance/developer/amm/fxswap/guides/integration.md) if the protocol only executes trades. This page is for applications that hold LP tokens, consume pool state, or build accounting around FXSwap.
<a id="identify-the-deployment-first"></a>
## Identify the deployment first
Before accepting an LP token or reading pool state:
1. Confirm the pool is registered and is on the protocol's versioned allowlist.
2. Read `version()`, `coins(0)`, `coins(1)`, and both coin decimals.
3. Record the pool, factory, `VIEW()`, and `MATH()` addresses.
4. Verify that the integration supports that exact deployed interface.
The reviewed Ethereum pools report `v2.1.0d`. Do not assume another pool is compatible because it shares the Twocrypto factory or exposes a similar ABI.
<a id="lp-token-and-supply-accounting"></a>
## LP-token and supply accounting
The pool contract is also its own ERC-20 LP token:
- `decimals()` returns `18`;
- `balanceOf(account)` is the account's withdrawable LP balance;
- `totalSupply()` includes user LP tokens **and outstanding refuel shares**;
- `donation_shares()` is the outstanding refuel-share supply;
- `user_supply()` returns `totalSupply() - donation_shares()`.
Refuel shares have no owner account and cannot be transferred or withdrawn. They can be burned when the pool recenters. A protocol must not treat `totalSupply()` as entirely user-owned supply when calculating ownership percentages, rewards, or market capitalization.
Use `user_supply()` when a denominator specifically means the LP tokens held by user accounts, such as distributing a user-only incentive. It is not an unconditional claim on a fixed fraction of each raw pool balance. Pool withdrawals use the deployed pool's accounting and can be affected by fees, imbalance, state changes, refuel shares, and the selected withdrawal method.
<a id="deposits-and-withdrawals"></a>
## Deposits and withdrawals
Use the pool's quote methods before building transaction bounds:
| Task | Quote method | Execution method |
| --- | --- | --- |
| Add two-sided or one-sided liquidity | `calc_token_amount(amounts, true)` | `add_liquidity` |
| Proportional withdrawal | Compute the pro-rata starting point and simulate | `remove_liquidity` |
| Single-coin withdrawal | `calc_withdraw_one_coin(lpAmount, i)` | `remove_liquidity_one_coin` |
| Fixed-out withdrawal | `calc_withdraw_fixed_out(lpAmount, i, amountI)` | `remove_liquidity_fixed_out` |
Quotes are state-sensitive. Simulate the exact receiver and calldata, set non-zero minimum amounts, and apply a deadline in the calling contract. Test fee-on-transfer, rebasing, callback-capable, or otherwise unusual tokens explicitly before supporting them.
<a id="value-lp-positions-by-realizable-outcomes"></a>
## Value LP positions by realizable outcomes
`lp_price()` and `get_virtual_price()` are useful pool accounting signals, but neither is a universal mark-to-market price for every integration:
- `lp_price()` is a 1e18 LP-price estimate using pool state;
- `get_virtual_price()` calculates the current 1e18 virtual price;
- `virtual_price()` exposes the cached internal value;
- withdrawal quotes incorporate the selected exit path and current imbalance.
For user-facing valuations, state the block number, external coin prices, token decimals, and valuation method. For solvency or risk decisions, stress executable withdrawal values across imbalance, price movement, fee changes, and refuel depletion instead of multiplying LP balance by a single getter.
<a id="pool-balances-are-accounted-balances"></a>
## Pool balances are accounted balances
`balances(i)` returns the pool's internally accounted raw balance for coin `i`. It is not interchangeable with `IERC20(coins(i)).balanceOf(pool)`.
Direct token transfers, pending pre-transfer flows, and other accounting paths can make the ERC-20 balance differ from the pool's stored balance. Use `balances(i)` for invariant and pool-state interpretation. Use the ERC-20 balance only when the integration specifically needs custody reconciliation, and explain any difference rather than silently treating it as available liquidity.
<a id="fees-imbalance-and-refuel-depletion"></a>
## Fees, imbalance, and refuel depletion
FXSwap charges a dynamic fee between `mid_fee()` and `out_fee()`, both at 1e10 precision. The realized fee depends on normalized balances and `fee_gamma()`. Deposits and withdrawals have their own fee paths, so a balanced-looking notional position does not imply a fee-free exit.
Refuel shares increase `totalSupply()` but are not user positions. When available refuel shares burn during recentering, both `donation_shares()` and `totalSupply()` decrease while account `balanceOf` values remain unchanged. Applications that snapshot supply, calculate rewards, or reconcile share price must handle this state transition.
<a id="oracle-getters-are-amm-state"></a>
## Oracle getters are AMM state
| Getter | Meaning | Safe-use boundary |
| --- | --- | --- |
| `last_prices()` | Latest normalized observed pool price | The deployed source explicitly describes it as unsafe and manipulable |
| `price_oracle()` | Exponential moving average of prior observed prices | Useful for understanding pool recentering; not automatically a manipulation-resistant lending price |
| `price_scale()` | Center of concentrated liquidity | A poo프로젝트로 돌아가기