bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 13쪽
int256` | Timestamp of the last cached EMA update | Advances at most once per block during relevant state changes |
| `ma_time() -> uint256` | Approximate EMA half-life in seconds | Decoded from the packed recentering parameter |
<a id="last_prices"></a>
## `last_prices`
`FXSwap.last_prices() -> uint256: view`
Returns the latest normalized pool price with 1e18 precision. The contract updates it from the post-operation balances and invariant:
```text
last_prices = Math.get_p(xp, D, A_gamma) × price_scale ÷ 1e18
```
The deployed source explicitly marks this value as unsafe and manipulable. Use it to inspect or reproduce pool behavior, not as an independent market price.
<a id="price_oracle"></a>
## `price_oracle`
`FXSwap.price_oracle() -> uint256: view`
Returns the EMA target price with 1e18 precision. If time has elapsed since `last_timestamp()`, the view calculates the current value without writing storage:
```text
alpha = exp(-(elapsed × 1e18) / internal_ma_parameter)
oracle = min(last_prices, 2 × price_scale) × (1 - alpha)
+ cached_oracle × alpha
```
The contribution from `last_prices` is capped at twice `price_scale`. A later state-changing operation can cache the calculated value and timestamp.
The oracle follows pool observations; it does not fetch an external FX feed. External markets influence it indirectly when arbitrage trades against the pool.
<a id="price_scale"></a>
## `price_scale`
`FXSwap.price_scale() -> uint256: view`
Returns the current liquidity center with 1e18 precision. It is neither the latest trade price nor the EMA itself.
A relevant state-changing operation can evaluate a move from `price_scale` toward `price_oracle`. The move occurs only when the oracle distance, `adjustment_step`, profit conditions, and available recentering budget allow it. A swap or liquidity operation therefore does not guarantee a `price_scale` update.
Read [Mechanism and Parameters](https://docs.curve.finance/developer/amm/fxswap/pools/mechanism.md) for the recentering conditions and [Refuels](https://docs.curve.finance/developer/amm/fxswap/pools/refuels.md) for the finite refuel budget.
<a id="ma_time"></a>
## `ma_time`
`FXSwap.ma_time() -> uint256: view`
Returns the approximate EMA half-life in seconds. The pool stores the exponent denominator internally and returns:
```text
packed_ma_parameter × 694 ÷ 1000
```
This integer conversion can differ from the mathematical half-life by one second. The admin setter `apply_new_parameters` accepts the internal exponent parameter, described in its source as `time_in_seconds / ln(2)`, rather than the decoded `ma_time()` return value.
<a id="updates-and-recentering"></a>
## Updates and recentering
The deployed pool evaluates its price-update routine after swaps and unbalanced liquidity operations, including one-coin and fixed-out withdrawals. During that routine it:
1. updates the cached EMA at most once per block;
2. records a new manipulable `last_prices` value;
3. updates profit and refuel accounting;
4. tests whether `price_scale` may move toward `price_oracle`; and
5. burns available refuel shares before using the permitted normal profit buffer.
These transitions are visible through getters and operation events, but there is no dedicated oracle-update event. Indexers should read the price fields at the block containing the pool operation when exact post-operation state matters.
<a id="safe-integration-boundary"></a>
## Safe integration boundary
- Use the getters to quote, monitor, reproduce pool calculations, or explain recentering.
- Treat values as block-sensitive and read all related fields at the same block.
- Do not assume `price_oracle` is independent of Curve trading activity.
- Do not use `last_prices` for manipulation-sensitive decisions.
- Before using any pool-derived price for lending or solvency, perform a separate oracle-security analysis covering manipulation cost, staleness, liquidity, external-market failure, and fallback behavior.
---
# FXSwap Refuels
Source: [https://docs.curve.finance/developer/amm/fxswap/pools/refuels](https://docs.curve.finance/developer/amm/fxswap/pools/refuels)
A refuel is liquidity added to a finite rebalancing buffer without giving the provider a withdrawable LP position. The pool records the resulting shares in `donation_shares`, unlocks them over time, and burns the available portion as it subsidizes price-scale recentering. This is why **refuel** is the product term: the buffer is supplied for a specific job and can be depleted as the pool performs that job.
Product term and contract term
Use **refuel** in interfaces and explanations. The immutable deployed ABI uses the earlier `donation_*` names, the `Donation` event, and a `donation` flag; those names appear here only when documenting the contract.
The accounting consequences are:
| Question | Answer |
| --- | --- |
| Who owns refuel shares? | No account. They are tracked in aggregate by `donation_shares()` |
| Can they be transferred or withdrawn? | No |
| Why does `totalSupply()` increase? | Refuel shares participate in the pool's virtual-price and recentering accounting |
| What is `user_supply()`? | `totalSupply() - donation_shares()` |
| Can public getters reveal the exact amount burnable now? | No; the deployed interface does not expose every internal release/protection component |
| What happens when the budget is exhausted? | Recentering can use the permitted normal profit buffer, but receives no further subsidy from refuel shares |
<a id="why-a-protocol-refuels"></a>
## Why a protocol refuels
A refuel is a spendable liquidity budget, not recoverable principal. The provider receives no LP balance or direct claim on the tokens. Instead, the pool uses the buffer to help pay for recentering, which can support tighter execution and routing as the external market price moves.
The economic benefit is indirect and not guaranteed: better-centered liquidity may attract more volume or improve the market for the provider's asset, while the refuel balance can decline to zero. Protocol teams should therefore model refuels as an operating cost, monitor their rate of depletion, and choose a schedule they can sustain.
Use [Mechanism and Parameter Design](https://docs.curve.finance/developer/amm/fxswap/pools/mechanism.md) to evaluate refuel demand together with concentration, fees, oracle smoothing, volatility, and external market depth.
<a id="refuel-lifecycle"></a>
## Refuel lifecycle
<a id="1-create-a-refuel"></a>
## 1\. Create a refuel
Call the four-argument overload:
```solidity
add_liquidity(
uint256[2] amounts,
uint256 min_mint_amount,
address receiver,
bool donation
) external returns (uint256 minted_shares);
```
Set `donation = true` and `receiver = address(0)`. The pool pulls both tokens from the caller, so approve each non-zero token amount first. At least one amount must be non-zero.
<a id="2-mint-refuel-shares"></a>
## 2\. Mint refuel shares
The return value is the number of refuel shares created. Those shares increase `totalSupply()` and `donation_shares()` but are not assigned to an address. `user_supply()` returns:
```text
totalSupply() - donation_shares()
```
Use a meaningful `min_mint_amount`; a refuel is still exposed to pool-state changes before inclusion. This path charges the contract's minimal noise fee rather than the ordinary imbalance fee.
<a id="3-lock-and-unlock"></a>
## 3\. Lock and unlock
New shares begin locked and release linearly over `donation_duration()` seconds. The contract records the release schedule with `last_donation_release_ts()`.
There is no public getter for the exact internal “available now” bucket. Consumers should display the public schedule and protection state without pretending that `donation_shares()` is immediately burnable.
<a id="4-apply-protection-rules"></a>
## 4\. Apply protection rules
Liquidity additions can open or extend a protection window. During that window, the amount of unlocked refuel liquidity available to recentering is damped. This reduces the value of depositing liquidity immediately before a state change and extracting the refuel subsidy.
Read these values from each pool:
| Getter | Unit | Meaning |
| --- | --- | --- |
| `donation_protection_expiry_ts()` | Unix seconds | End of the active protection window |
| `donation_protection_period()` | seconds | Configured window length |
| `donation_protection_lp_threshold()` | 1e18 ratio | LP-addition threshold used by protection |
| `donation_shares_max_ratio()` | 1e18 ratio | Maximum refuel-share ratio |
These are governance parameters, not universal constants. For example, reviewed live pools used different protection periods and thresholds while both used a seven-day refuel duration.
<a id="5-determine-availability"></a>
## 5\. Determine availability
Internally, the pool first calculates time-unlocked shares, then applies a linear protection damping factor while the protection window is active. The resulting value is the maximum refuel amount available to the current recentering evaluation.
`donation_shares()` reports the total outstanding shares, including locked or protected shares. `last_donation_release_ts()` and the protection getters let an observer describe the schedule, but the public ABI does not expose the exact internal burnable value. Indexers should not manufacture an “available now” field without reproducing the deployed version's state transition logic and block timestamp.
<a id="6-burn-and-deplete-refuels"></a>
## 6\. Burn and deplete refuels
State-changing pool operations may update the oracle and attempt to move `price_scale` toward it. When a move would otherwise reduce LP virtual price:
1. the pool determines how many refuel shares are unlocked and available after protection;
2. available refuel shares are burned first;
3. the ordinary profit buffer covers any remaining permitted cost;
4. the recentering step is limited by configured profit and adjustment parameters.
Burning decreases both `donation_shares()` and `totalSupply()`. It does not debit an LP's `balanceOf`. Refuels subsidize recentering; they do not guarantee a fixed price, a specific rebalance time, or loss-free LP returns.
When no available refuel shares remain, the pool can only accept a recentering move that satisfies its normal profit constraints. The pool continues to quote and trade; an exhausted refuel budget does not itself pause swaps.
<a id="7-combine-overlapping-refuels"></a>
## 7\. Combine overlapping refuels
When a second refuel arrives before the first has fully unlocked, the pool:
1. calculates how much of the prior total has already unlocked without protection;
2. adds the newly minted shares to the outstanding total;
3. shifts `last_donation_release_ts` so the previously unlocked amount remains unlocked; and
4. releases the combined remainder over `donation_duration()`.
A new refuel does not relock shares that were already released. Because the schedule is merged, the public state does not preserve a separate unlock record for each direct refuel.
<a id="8-enforce-caps-and-failure-conditions"></a>
## 8\. Enforce caps and failure conditions
A refuel reverts when:
- neither token amount is positive;
- token transfer/allowance fails;
- the minted refuel shares would exceed `donation_shares_max_ratio`;
- the result is below `min_mint_amount`;
- coin indices, receiver, or other inputs violate the deployed method's guards.
Admin setters additionally require factory-admin authorization. Duration, period, threshold, and maximum-share ratio must be positive; `admin_fee` cannot exceed the contract maximum.
<a id="9-inspect-state"></a>
## 9\. Inspect state
```ts
const refuelAbi = parseAbi([
'function donation_shares() view returns (uint256)',
'function user_supply() view returns (uint256)',
'function totalSupply() view returns (uint256)',
'function donation_duration() view returns (uint256)',
'function last_donation_release_ts() view returns (uint256)',
'function donation_protection_expiry_ts() view returns (uint256)',
'function donation_protection_period() view returns (uint256)',
'function donation_protection_lp_threshold() view returns (uint256)',
'function donation_shares_max_ratio() view returns (uint256)',
])
```
Label `donation_shares` as **refuel shares**, not token value. Convert it to a value only with a clearly stated valuation method and block number.
<a id="10-index-events-and-accounting"></a>
## 10\. Index events and accounting
Creating a refuel emits the immutable `Donation(address indexed donor, uint256[2] token_amounts)` event and also emits `AddLiquidity`. Use **refuel provider** in product displays while decoding the indexed `donor` field exactly.
Track refuel accounting as transitions rather than token custody owned by `donor`:
- creation increases `donation_shares()` and `totalSupply()`;
- time and protection change internal availability without transferring LP tokens;
- recentering burns shares and reduces both aggregate values;
- no `Transfer` event assigns refuel shares to the provider;
- pool events do not expose the exact number of shares burned by each recentering.
For recurring funding, continue to [Automation](https://docs.curve.finance/developer/amm/fxswap/automation/overview.md). Automation adds custody, schedule, cancellation, and executor-reward behavior but does not bypass the pool's cap, unlock schedule, or protection rules.
## Diagram definitions
```mermaid
flowchart LR
A["Refuel added"] --> B["Locked refuel shares"]
B -->|"linear release"| C["Unlocked shares"]
C --> D["Protection damping"]
D --> E["Available refuel shares"]
E -->|"recentering needs subsidy"| F["Shares burned"]
F --> G["Lower refuel reserve"]
G --> H["Regular LP balances unchanged"]
```
---
# FXSwap Math Contract
Source: [https://docs.curve.finance/developer/amm/fxswap/utility-contracts/math](https://docs.curve.finance/developer/amm/fxswap/utility-contracts/math)
# Math Contract
The FXSwap Math contract implements the two-coin StableSwap-style invariant used by deployed FXSwap pools. It is not the `TwocryptoMath.vy` contract used by ordinary Twocrypto-NG pools.
Contract Source & Deployment
The deployed FXSwap pool returns its Math address from `MATH()`. The verified source is closest to [`StableswapMath.vy` at commit `387fbe5`](https://github.com/curvefi/twocrypto-ng/blob/387fbe5f12473ef0e1f0c6a76bc38f1ca0da669d/contracts/main/StableswapMath.vy), compiled with Vyper `0.4.3`.
Read `MATH()` from the target pool. The reviewed contract reports `version() == "v0.1.0"`.
The pool normalizes its two balances to common precision before calling these methods. Unless reproducing the invariant for research or simulation, integrations should use pool and Views methods rather than call Math directly.
<a id="amm-math-functions"></a>
## AMM Math Functions
<a id="get_y"></a>
### `get_y`
`Math.get_y(_amp: uint256, _gamma: uint256, xp: uint256[2], D: uint256, i: uint256) -> uint256[2]: pure`
Solves the StableSwap invariant for normalized balance `xp[i]` while holding `D` and the other balance constant.
| Input | Meaning |
| --- | --- |
| `_amp` | Amplification value in the pool's contract precision |
| `_gamma` | Unused compatibility argument |
| `xp` | Two normalized balances in common precision |
| `D` | Current invariant |
| `i` | Balance index to solve; must be `0` or `1` |
The first return element is the solved balance. The second is always `0` and exists for Twocrypto interface compatibility. The function iterates up to 255 times and reverts with `Did not converge` if it does not reach one-unit precision.
<a id="newton_d"></a>
### `newton_D`
`Math.newton_D(_amp: uint256, gamma: uint256, _xp: uint256[2], K0_prev: uint256 = 0) -> uint256: pure`
Calculates invariant `D` for two normalized balances and the supplied amplification.
`gamma` and `K0_prev` are unused compatibility arguments. The function returns `0` when both balances sum to zero. For non-zero supply it iterates up to 255 times and reverts with `Did not converge` if convergence fails.
<a id="get_p"></a>
### `get_p`
`Math.get_p(_xp: uint256[2], _D: uint256, _A_gamma: uint256[2]) -> uint256: pure`
Returns the normalized derivative `dx₀/dx₁` with 1e18 precision. `_A_gamma[0]` supplies amplification; the compatibility gamma value is not used by this StableSwap-style calculation.
The pool multiplies the result by `price_scale` and divides by 1e18 to store `last_prices`.
<a id="wad_exp"></a>
### `wad_exp`
`Math.wad_exp(x: int256) -> uint256: pure`
Returns `eˣ` where `x` and the result use 1e18 fixed-point precision. The pool uses it to calculate the EMA decay factor for `price_oracle`.
<a id="version"></a>
### `version`
`Math.version() -> String[8]: view`
Returns `"v0.1.0"` for the reviewed deployed Math contract.
<a id="compatibility-boundary"></a>
## Compatibility boundary
FXSwap retains the Twocrypto-compatible Math call shape so the pool can use shared periphery interfaces. That compatibility does not make the algorithms interchangeable:
- `gamma` does not shape the deployed FXSwap invariant;
- `get_y` returns `[y, 0]` rather than a Cryptoswap solver result;
- `newton_D` ignores `gamma` and `K0_prev`; and
- the invariant concentrates around a variable `price_scale` using StableSwap-style math.
Allowlist the pool version together with its `MATH()` and `VIEW()` addresses. Do not substitute an ordinary Twocrypto-NG Math contract because the ABI appears compatible.
---
# FXSwap Views Contract
Source: [https://docs.curve.finance/developer/amm/fxswap/utility-contracts/views](https://docs.curve.finance/developer/amm/fxswap/utility-contracts/views)
# Views Contract
The FXSwap Views contract supplies quote and liquidity-calculation methods used by the pool. These methods are useful for offchain search, routing, and simulation, but some are too expensive to call repeatedly from another contract.
Contract Source & Deployment
The deployed FXSwap pool returns its Views address from `VIEW()`. The verified source is closest to [`TwocryptoView.vy` at commit `387fbe5`](https://github.com/curvefi/twocrypto-ng/blob/387fbe5f12473ef0e1f0c6a76bc38f1ca0da669d/contracts/main/TwocryptoView.vy), compiled with Vyper `0.4.3`.
Read `VIEW()` from the target pool instead of hardcoding a periphery address. The pool's own quote methods forward to its configured Views contract.
All coin and token amounts are raw token units. `i` and `j` are pool coin indices and must be `0` or `1`.
<a id="exchange-methods"></a>
## Exchange Methods
<a id="get_dy"></a>
### `get_dy`
`Views.get_dy(i: uint256, j: uint256, dx: uint256, swap: address) -> uint256: view`
Returns the amount of `coins(j)` expected for an exact input of `dx` raw units of `coins(i)`, including the dynamic swap fee.
| Input | Description |
| --- | --- |
| `i` | Input coin index |
| `j` | Output coin index; must differ from `i` |
| `dx` | Positive input amount in raw `coins(i)` units |
| `swap` | FXSwap pool address |
The call reverts for equal or out-of-range indices or a zero input. For ordinary quoting, prefer `pool.get_dy(i, j, dx)`, which routes through the pool's current `VIEW()` address.
<a id="get_dx"></a>
### `get_dx`
`Views.get_dx(i: uint256, j: uint256, dy: uint256, swap: address, n_iter: uint256 = 5) -> uint256: view`
Estimates the raw `coins(i)` input required to receive `dy` raw units of `coins(j)`, including fees. The calculation iteratively adds the estimated output fee and is not an exact-output execution method.
`n_iter` defaults to `5` and is bounded by the contract at `100`. More iterations cost more gas and do not turn the result into an execution guarantee. The call reverts for equal or out-of-range indices or zero `dy`.
Prefer `pool.get_dx(i, j, dy)` for the default iteration count. Apply an input buffer, simulate the final transaction, and execute through an exact-input swap with a protected `min_dy`.
<a id="프로젝트로 돌아가기