# vPair

## Events

#### event Mint

```solidity
event Mint(
    address indexed sender, 
    uint256 amount0, 
    uint256 amount1,
    uint lpTokens,
    uint poolLPTokens
);
```

Emitted every time liquidity tokens are created in [mint](#function-mint) function.

#### event  Burn

```solidity
event Burn(
    address indexed sender, 
    uint256 amount0, 
    uint256 amount1, 
    address indexed to,
    uint256 totalSupply
);
```

Emitted every time liquidity tokens are destroyed in [burn](#function-burn) function.

#### event Swap

```solidity
event Swap(
        address indexed sender,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOut,
        address indexed to
    );
```

Emitted every time a native token swap happens in [swapNative](#function-swapnative) function.

#### event  SwapReserve

```solidity
event SwapReserve(
        address indexed sender,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOut,
        address ikPool,
        address indexed to
    );
```

Emitted every time a reserve-powered token swap happens in [swapNativeToReserve](#function-swapnativetoreserve) or [swapReserveToNative](#function-swapreservetonative) function.

`ikPool` is the address of the pool that composes the virtual pool together with the pool that emits the event.

#### event AllowListChanged

```solidity
event AllowListChanged(address[] tokens);
```

Emitted every time a the list of tokens accepted as reserves is updated in [setAllowList](#function-setallowlist) function.

#### event AllowListCountChanged

```solidity
event AllowListCountChanged(uint24 _maxAllowListCount);
```

Emitted every time the maximum number of tokens accepted as reserves is updated in [setAllowListCount](#function-setallowlistcount) function.

#### event Sync

```solidity
event Sync(
        uint112 balance0, 
        uint112 balance1
        )
```

Emitted every time the balances of native tokens change in [swapNative](#function-swapnative), [swapReserveToNative](#function-swapreservetonative), [swapNativeToReserve](#function-swapnativetoreserve), [mint](#function-mint) or [burn](#function-burn) functions.

#### event ReserveSync

```solidity
event ReserveSync(
    address asset, 
    uint256 balance, 
    uint256 rRatio
    );
```

Emitted every time the balance of a reserve token is updated in [swapReserveToNative](#function-swapreservetonative) or [swapNativeToReserve](#function-swapnativetoreserve)

#### event FeeChanged

```solidity
event FeeChanged(uint16 fee, uint16 vFee);
```

Emitted when fee is changed in [setFee](#function-setfee) function.

#### event ReserveThresholdChanged

```solidity
event ReserveThresholdChanged(uint256 newThreshold);
```

Emitted when reserve threshold is changed in [setMaxReserveThreshold](#function-setmaxreservethreshold) function.

#### event BlocksDelayChanged

```solidity
 event BlocksDelayChanged(uint256 _newBlocksDelay);
```

Emitted when block delay is changed inside setBlocksDelay function.

#### event ReserveRatioWarningThresholdChanged

```solidity
event ReserveRatioWarningThresholdChanged(
     uint256 _newReserveRatioWarningThreshold
);
```

Emitted when reserve ratio warning parameter is changed in setReserveRatioWarningThreshold function.

## State-Changing Functions

#### function swapNative

```solidity
function swapNative( 
        uint256 amountOut, 
        address tokenOut, 
        address to, 
        bytes memory data
 ) external override lock returns (uint256 _amountIn)
```

Performs a swap between the two native assets of the pool, getting the specified amount of a native asset. Sufficient amount of the input token must be transferred to the contract before the call, or can be transferred during the call using `IvFhashSwapCallback` interface.

emits [Sync](#event-sync) and [Swap](#event-swap) events&#x20;

✏️To safely use the `swapNative` function, it must be called from a periphery  smart contract to ensure the operation is atomic. Calling `swapNative` method directly after transferring input tokens to the `vPair` contract is not safe because the sent tokens would be exposed to arbitrage.

Parameters:

<table><thead><tr><th width="164">Name</th><th width="115">Type</th><th>Description</th></tr></thead><tbody><tr><td>amountOut</td><td><code>uint256</code></td><td>Amount of output tokens to receive</td></tr><tr><td>tokenOut</td><td><code>address</code></td><td>Address of the token contract of the token to be received</td></tr><tr><td>to</td><td><code>address</code></td><td>Recipient of the output tokens</td></tr><tr><td>data</td><td><code>byte memory</code></td><td>if populated, the flash swap will be invoked. The <code>data</code> will be passed back to the caller via <code>vFlashSwapCallback</code> method of  <code>IvFlashSwapCallback</code> interface</td></tr></tbody></table>

#### function swapReserveToNative

```solidity
function swapReserveToNative( 
    uint256 amountOut,
    address ikPair,
    address to,
    bytes calldata data
) external override lock returns (uint256 amountIn)
```

Performs a swap between a reserve token of the pool and the native token using a virtual pool. The virtual pool is constructed from the called instance as *Active Pool* and the `ikPair` as *Reference Pool.*  Sufficient amount of the reserve token must be transferred to the `vPair`contract before the call, or can be transferred during the call using `IvFhashSwapCallback` interface. The output asset is determined automatically from the virtual pool.&#x20;

emits [Sync](#event-sync) and [SwapReserve](#event-swapreserve) event

✏️To safely use the `swapReserveToNative` function, it must be called from a periphery  smart contract to ensure the operation is atomic. Calling the method directly after transferring input tokens to the `vPair` contract is not safe because the sent tokens would be exposed to arbitrage.

<table><thead><tr><th width="139">Name</th><th width="187">Type</th><th>Description</th></tr></thead><tbody><tr><td>amountOut</td><td><code>uint256</code></td><td>Amount of output token to receive</td></tr><tr><td>ikPair</td><td><code>address</code></td><td>Address of the VirtuSwap pool to be used as reference pool for creating the virtual pool</td></tr><tr><td>to</td><td><code>address</code></td><td>Recipient of the output tokens</td></tr><tr><td>data</td><td><code>bytes calldata</code> </td><td>if populated, the flash swap will be invoked. The <code>data</code> will be passed back to the caller via <code>vFlashSwapCallback</code> method of  <code>IvFlashSwapCallback</code> interface</td></tr></tbody></table>

#### function swapNativeToReserve

```solidity
function swapNativeToReserve(
    uint256 amountOut,
    address ikPair,
    address to,
    uint256 incentivesLimitPct,
    bytes calldata data
)
    external
    override
    nonReentrant
    returns (address _leftoverToken, uint256 _leftoverAmount)
```

Performs a swap of one of the pool's reserve assets to the pool's native asset. The method can be called as part of the [Exchange of Reserves](https://docs.virtuswap.io/virtuswap-documentation/virtuswap-basics/virtuswap-technology/exchange-of-reserves) process between VirtuSwap pools, or as part of forced liquidation of reserves by the Admin or Emergency Admin. The called `vPair` sends its reserve token to the target pool or to the Admin/Emergency Admin (specified as `to` parameter), and receives its own native token in exchange.

The necessary amount of input tokens must be sent to the `vPair` prior to the call.&#x20;

The exchange rate *R* between the two tokens is calculated using a virtual pool constructed between the `vPair` instance used as *Active Pool* and the given `ikPair` as *Reference Pool*. The method validates that the amount of input tokens passed to the the vPair instance is greater or equal to `amountOut` \* *R.* When two pools are exchanging reserves, each of them calculates the *R* differently, thus one of the pools sends an amount that is larger than the recipient pool needs, thus creating leftovers.

A certain percentage of the leftovers, specified by the`incentivesLimitPct` parameter is sent to the caller as a reward for running the transaction. Initially, the Reserve Exchange routine will be called by the VirtuSwap DAO, and incentivesLimitPct will be set to 0, i.e. all the leftovers will remain in the pools. See [vEchangeReserves](https://docs.virtuswap.io/virtuswap-documentation/technical-reference/smart-contracts-v1/dex-contracts/vexchangereserves).

In case of liquidation of reserves (only callable by Admin or Emergency Admin), the `vPair` instance will agree to receive a lower amount of native token than the amount calculated using the virtual pool. The discount from that amount that the vPair  is willing to accept is defined by the `emergencyDiscount` variable

See [`vExchangeReserves`](https://docs.virtuswap.io/virtuswap-documentation/technical-reference/smart-contracts-v1/dex-contracts/vexchangereserves) for more detail on the reserve exchange routine.

✏️ The method can only be called by the `vExchangeReserves` contract or by the Admin or EmergencyAdmin wallets

✏️ The identity of the two tokens is determined from the virtual pool defined by the called `vPair` and the `ikPair`

emits [`Sync`](#sync) and [`SwapReserve`](#swapreserve) event

<table><thead><tr><th width="213">Name</th><th width="187">Type</th><th>Description</th></tr></thead><tbody><tr><td>amountOut</td><td><code>uint256</code></td><td>Requested amount of reserve asset </td></tr><tr><td>ikPair</td><td><code>address</code></td><td>Address of the <code>vPair</code> to be used as <em>Reference Pool</em> in the Virtual Pool used to determine the token price</td></tr><tr><td>to</td><td><code>address</code></td><td>Address of the target pool that will receive reserve tokens</td></tr><tr><td>incentivesLimitPct</td><td><code>uint256</code></td><td>The maximum percentage of the leftovers that the caller can receive from calling the method</td></tr><tr><td>data</td><td><code>bytes calldata</code> </td><td>If populated, the flash swap will be invoked. The <code>data</code> will be passed back to the caller via <code>vFlashSwapCallback</code> method of  <code>IvFlashSwapCallback</code> interface</td></tr></tbody></table>

#### function liquidateReserve

```solidity
   function liquidateReserve(
        address reserveToken,
        address nativePool
    ) external override nonReentrant
```

Called by the admin or emergencyAdmin in cases where a reserve asset in a pool cannot be exchanged normally during reserve exchange procedure.

✏️Can only be called by the  admin or emergency admin

<table><thead><tr><th width="177">Name</th><th width="187">Type</th><th>Description</th></tr></thead><tbody><tr><td>reserveToken</td><td><code>address</code></td><td>Address of the reserve token to be liquidated</td></tr><tr><td>nativePool</td><td><code>address</code></td><td>Address of the pool that will be used for liquidation</td></tr></tbody></table>

#### function mint

```solidity
 function mint(
    address to
 ) external override lock returns (uint256 liquidity)
```

Mints LP tokens representing the caller's share in the pool. Both pool tokens must to be transferred to the `vPair` contract prior to calling `mint`.

If successful, the sender receives LP tokens corresponding to the transferred amount. The sender's share of LP tokens is calculated taking into account the total value of reserve tokens present in the pool. The method returns the number of LP tokens minted.

emits [`Sync`](#sync) and [`Mint`](#mint) events

✏️The method should be called from a periphery smart contract to avoid exposure to arbitrage.

Parameters:

<table><thead><tr><th width="200">Name</th><th width="162">Type</th><th>Description</th></tr></thead><tbody><tr><td>to</td><td><code>address</code></td><td>Recipient of the LP tokens</td></tr></tbody></table>

#### function burn

```solidity
function burn(
    address to
) external override lock returns (uint256 amount0, uint256 amount1)
```

Burns the LP tokens transferred by the user and transfers the caller's share of the native and reserve tokens to the caller. Returns the amount of native token0 and native token1 transferred.

emits [`Sync`](#sync) and [`Burn`](#burn) events

Parameters:

<table><thead><tr><th width="200">Name</th><th width="162">Type</th><th>Description</th></tr></thead><tbody><tr><td>to</td><td><code>address</code></td><td>Recipient of the native and reserve tokens</td></tr></tbody></table>

#### function setAllowList

```solidity
function setAllowList(
    address[] memory _allowList
) external override onlyFactoryAdmin
```

Updates the list of tokens that can be accepted as reserves in the pool.

Emits [`AllowListChanged`](#event-allowlistchanged) event.

✏️ The addresses in the address\[] array must be sorted ascending and they must be unique

✏️ Can only be called by the Factory Admin

#### function setMaxAllowListCount

```solidity
function setMaxAllowListCount(
    uint24 _maxAllowListCount
) external override onlyFactoryAdmin
```

Updates the maximum number of tokens hat can be accepted as reserves in the pool.

Emits [`AllowListCountChanged`](#event-allowlistchanged) event.

✏️Can only be called by the Factory Admin

#### function setMaxReserveThreshold

```solidity
function setMaxReserveThreshold(
    uint256 threshold
) external override onlyFactoryAdmin
```

Sets the maximum allowed value of reserve threshold. Reserve threshold is the ratio between the total value of reserve tokens in the pools and the value of native tokens. The value should be passed as desired percent \* 1000, e.g. for 1.9% reserve threshold, pass 1900. Normally, the ratio is very low, e.g. 2%.

Emits [`ReserveThresholdChanged`](#event-reservethresholdchanged) event.

✏️Can only be called by the factory admin.

Parameters:

<table><thead><tr><th width="161.01465201465203">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>threshold</td><td><code>uint256</code></td><td>Updated value of the threshold</td></tr></tbody></table>

#### function setFee

```solidity
function setFee(
    uint16 _fee, 
    uint16 _vFee
) external override onlyFactoryAdmin
```

Sets the trading fees for the pool. A separate fee can be set for the native token swap (swapNative) and for swap using virtual pools (swapReserveToNative).

The fee applied to each trade is calculated as follows: (1000 - \_fee)/1000, so in order to set the trading fee at 0.3%, the caller needs to pass 997 as the parameter.&#x20;

Emits [`FeeChanged`](#event-feechanged) event.

✏️Can only be called by the  admin.

Parameters:

<table><thead><tr><th width="161.01465201465203">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>_fee</td><td><code>uint16</code></td><td>value for native to native token swaps</td></tr><tr><td>_vFee</td><td><code>uint16</code></td><td>value for reserve to native token swaps</td></tr></tbody></table>

#### function setBlocksDelay

```solidity
function setBlocksDelay(uint128 _newBlocksDelay) 
```

Sets the delay in blocks that needs to expire before a trade performed on a reference pool can influence the price in a virtual pool using that reference pool. &#x20;

✏️Can only be called by the admin or emergency admin

#### function setReserveRatioWarningThreshold

```solidity
function setReserveRatioWarningThreshold(
        uint256 _reserveRatioWarningThreshold
    ) external override onlyEmergencyAdmin
```

Sets the threshold above which the emergencyAdmin can call the liquidateReserve method.

✏️Can only be called by the Emergency Admin

#### function emergencyToggle

```solidity
function emergencyToggle() external;
```

Stops all trading on a pool, leaving only [`burn`](#function-burn)  available for use. `emergencyToggle` can be used in extreme cases to protect LPs.&#x20;

✏️Can only be called by the emergency admin

## Read-only Functions

#### function getBalances

```solidity
function getBalances(
) external view override 
returns ( 
    uint112 _balance0, 
    uint112 _balance1 )
```

Returns the state of liquidity balances for native tokens.

#### function pairBalance0

```solidity
function balance0(
) external view returns (uint112);
```

Returns the amount of liquidity for the first native token in the pool.

#### function pairBalance1

```solidity
function balance1(
) external view returns (uint112);
```

Returns the amount of liquidity for the second  native token in the pool.

#### function calculateReserveRatio

```solidity
function calculateReserveRatio(
    ) public view override returns (uint256 rRatio)
```

Calculates the ratio between the total value of reserve tokens currently present in the pool and total value of the native tokens.&#x20;

Returns the per mille ratio of total value of all reserves divided by the total value locked in the pool. The value of the reserves is calculated relative to the first native asset in the pool.

See also [`setMaxReserveThreshold`](#function-setmaxreservethreshold)

#### function reservesBaseValue

```solidity
function reservesBaseValue(
    address reserveAddress
) external view override returns (uint256 rRatio)
```

Calculates the value of the given reserve asset in terms of the token0 native token.&#x20;

#### function getTokens

```solidity
function getTokens(
) external view  
returns ( 
    address token0, 
    address token1
)
```

Returns addresses of the native tokens in the pool.

#### function token0

<pre class="language-solidity"><code class="lang-solidity">function token0(
<strong>) external view returns (address);
</strong></code></pre>

Returns address of the first native token in the pool.

#### function token1

```solidity
function token1(
) external view returns (address);
```

Returns address of the second native token in the pool.

#### function lastSwapBlock

```solidity
function lastSwapBlock() external view returns (uint128);
```

Returns the number of the last block in which a swap was performed in the `vPair` instance.

#### function blocksDelay

```solidity
function blocksDelay() external view returns (uint128);
```

Returns the current value of `blocksDelay`.

#### function reserves

```solidity
function reserves(address reserveAddress) external view returns (uint256);
```

Returns the amount of a given reserve asset currently present in the pool

#### function reservesBaseValueSum

```solidity
function reservesBaseValueSum() external view returns (uint256);
```

Returns the value of reserve in units of token0 in the pool.

#### function reserveRatioFactor

```solidity
function reserveRatioFactor() external pure returns (uint256);
```

Returns the factor used to convert Reserve Ratio into percentage. The default factor is 100,000, i.e. 2000 means 0.02.

#### function maxAllowListCount

```solidity
function maxAllowListCount() external view returns (uint24);
```

returns the current length of the allow list.

#### function maxReserveRatio

```solidity
function maxReserveRatio() external view returns (uint256);
```

Returns the maximum allowed reserve ratio for the pool

#### function fee

```solidity
function fee() external view returns (uint16);
```

returns the native asset swap fee in the pool

#### function vFee

```solidity
function vFee()  external view returns (uint16);
```

returns the fee for reserve to native swaps

#### function allowLisMap

```solidity
function allowListMap(address _token) external view returns (bool allowed);
```

Returns `true` if a given token address is in the Reserve Allow List, and `false` otherwise.&#x20;
