# Introduction

Welcome to Swipe Network's Documentation hub where you will find all the details pertaining to the Swipe Network and how to use the protocol.

![Swipe Network](/files/-MGoD1F-JjZSGz_uaTbh)

### **Important Links**

[**Swipe Product Manual**](https://swipe.io/ProductManual.pdf)\
[**Swipe.io Website**](https://swipe.io)\
[**Swipe DeFi App** ](https://app.swipe.org)\
[**Github Repository**](https://github.com/SwipeWallet)\
[**Swipe Network Smart Contract ABI’s.**](https://etherscan.io/address/0xee03e3d55d52a35ee364fce45cd1373e0f53f8d9#code)\
&#x20;


# SXP

Swipe Token (SXP) is the native cryptourrency that powers the Swipe Network. It is used for staking, payments, governance, and more.

## More Details coming soon.


# Staking

Swipe Network staking details and information.

The Swipe Network is a decentralized finance application that enables users to bond Swipe Token (SXP) to a smart contract to guarantee the conversion rates between crypto-to-fiat. The way this is performed is that each conversion that occurs on the Swipe Payment rails occurs in real-time. SXP is then held as a bond between the conversion to guarantee the conversion from crypto to fiat on the payment networks.&#x20;

Users who stake SXP and bond it to the Swipe Network will receive their proportionate share of the Network Rewards currently set at 20,000 `SXP` per day. This number is dynamic and can be controlled later through the Swipe Governance protocol.&#x20;

Swipe Network collateral bonded is controlled only by the supplier as the smart-contract has no administrative control over your funds. Users are able to supply and withdraw SXP collateral on-demand.<br>


# Governance

Swipe Governance is a protocol that enables the Swipe community to make changes to the Swipe Network directly on-chain with SXP as the governance token.

## Introduction

The Swipe Governance protocol is operated by a series of smart contracts that are [publicly available](https://github.com/SwipeWallet/Swipe-Network/tree/master/contracts/governance) which control certain improvements and changes to the Swipe Network. All of the Swipe Governance proposals and voting weight will be determined by how much the user's address has staked in `SXP` on the Swipe staking contract.

{% hint style="warning" %}
Please note: SXP that is not staked on the on-chain Swipe Staking contract **will not** be eligible for Swipe Governance. Only SXP that is staked on-chain will count towards Swipe Governance.&#x20;
{% endhint %}

The core functions of Swipe Governance will include `Proposals` , `Voting Periods` , `End Proposals`, `Execution Time`, and `Vote` . These functions will enable users to deploy **Swipe Improvement Proposals  (`SIP`)** which users can vote on during certain time periods. &#x20;

## Current Governance Requirements

| Type                                                     | SXP Amount |
| -------------------------------------------------------- | ---------- |
| [Proposals](https://docs.swipe.org/governance/proposals) | 300,000\*  |
| [Vote](https://docs.swipe.org/governance/overview)       | 1          |

{% hint style="info" %}
\*Users may delegate their staked SXP to others for voting power in proposals or general voting in a future upgrade.
{% endhint %}


# API

A public set of API's to get data from the Swipe Network.

## &#x20;Total Staked

<mark style="color:blue;">`GET`</mark> `https://api.swipe.org/api?module=stats&action=totalStaked`

This endpoint allows you to retrieve the total amount of SXP staked on the Swipe Network.

{% tabs %}
{% tab title="200 Total Staked SXP successfully retrieved." %}

```
{"status":true,"data":"29855685667325892439200000"}
```

{% endtab %}
{% endtabs %}

## &#x20;Reward Amount

<mark style="color:blue;">`GET`</mark> `https://api.swipe.org/api?module=stats&action=rewardAmount`

This endpoint allows you to retrieve the total amount of SXP earned daily on the Swipe Network.

{% tabs %}
{% tab title="200 Total SXP daily reward successfully retrieved." %}

```
{"status":true,"data":"20000000000000000000000"}
```

{% endtab %}

{% tab title="404 Unsuccessful attempt to retrieve the daily SXP reward amount." %}

```
{"status":false,"message":"Invalid action"}
```

{% endtab %}
{% endtabs %}

## Reward Cycle

<mark style="color:blue;">`GET`</mark> `https://api.swipe.org/api?module=stats&action=rewardCycle`

This endpoint allows you to retrieve the SXP rewards distribution cycle in seconds.

{% tabs %}
{% tab title="200 SXP rewards distribution cycle successfully retrieved." %}

```
{"status":true,"data":"86400"}
```

{% endtab %}

{% tab title="404 Unsuccessful attempt to retrieve the daily SXP reward amount." %}

```
{"status":false,"message":"Invalid action"}
```

{% endtab %}
{% endtabs %}

## Minimum Stake

<mark style="color:blue;">`GET`</mark> `https://api.swipe.org/api?module=stats&action=minimumStakeAmount`

This endpoint allows you to retrieve the minimum SXP required to stake on the Swipe Network.

{% tabs %}
{% tab title="200 Total Staked SXP successfully retrieved." %}

```
{"status":true,"data":"1000000000000000000000"}
```

{% endtab %}
{% endtabs %}


# Smart Contract

{% content-ref url="/pages/-MUOZYbUQb\_L9iyPIDn6" %}
[Implement a Swap](/swap/smart-contract/implement-a-swap)
{% endcontent-ref %}

{% content-ref url="/pages/-MUPf0dZxIraEXoPsIUv" %}
[Providing Liquidity](/swap/smart-contract/providing-liquidity)
{% endcontent-ref %}

{% content-ref url="/pages/-MUPfE2Hdqb03rupEPHF" %}
[Building an Oracle](/swap/smart-contract/building-an-oracle)
{% endcontent-ref %}

{% content-ref url="/pages/-MUPwQOKwkyiPVNsd5wj" %}
[Flash Swaps](/swap/smart-contract/flash-swaps)
{% endcontent-ref %}

{% content-ref url="/pages/-MUPxw9TxjUp3BD4e3kh" %}
[Pair Addresses](/swap/smart-contract/pair-addresses)
{% endcontent-ref %}

{% content-ref url="/pages/-MUPyO1tez4euCZI5Swk" %}
[Supporting meta transactions](/swap/smart-contract/supporting-meta-transactions)
{% endcontent-ref %}


# Implement a Swap

When trading from a smart contract, the most important thing to keep in mind is that access to an external price source is *required*. Without this, trades can be frontrun for considerable loss.

## Using the Router <a href="#using-the-router" id="using-the-router"></a>

The easiest way to safely swap tokens is to use the route&#x72;*,* which provides a variety of methods to safely swap to and from different assets. You’ll notice that there is a function for each permutation of swapping to/from an exact amount of ETH/tokens.

First you must use an external price source to calculate the safety parameters for the function you’d like to call. This is either a minimum amount received when selling an exact input or the maximum amount you are willing to pay when a buying an exact output amount

It is also important to ensure that your contract controls enough ETH/tokens to make the swap, and has granted approval to the router to withdraw this many tokens.

## Example <a href="#example" id="example"></a>

Imagine you want to swap 50 DAI for as much ETH as possible from your smart contract.

### transferFrom <a href="#transferfrom" id="transferfrom"></a>

Before swapping, our smart contracts needs to be in control of 50 DAI. The easiest way to accomplish this is by calling `transferFrom` on DAI with the owner set to `msg.sender`:

```
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
```

### approve <a href="#approve" id="approve"></a>

Now that our contract owns 50 DAI, we need to approve to the router to withdraw this DAI:

```
require(DAI.approve(address(UniswapV2Router02), amountIn), 'approve failed.');
```

### swapExactTokensForETH <a href="#swapexacttokensforeth" id="swapexacttokensforeth"></a>

Now we’re ready to swap:

```
// amountOutMin must be retrieved from an oracle of some kind
address[] memory path = new address[](2);
path[0] = address(DAI);
path[1] = UniswapV2Router02.WETH();
UniswapV2Router02.swapExactTokensForETH(amountIn, amountOutMin, path, msg.sender, block.timestamp);
```

## Safety Considerations <a href="#safety-considerations" id="safety-considerations"></a>

Because Ethereum transactions occur in an adversarial environment, smart contracts that do not perform safety checks *can be exploited for profit*. If a smart contract assumes that the current price on Swipeswap is a “fair” price without performing safety checks, *it is vulnerable to manipulation*. A bad actor could e.g. easily insert transactions before and after the swap (a “sandwich” attack) causing the smart contract to trade at a much worse price, profit from this at the trader’s expense, and then return the contracts to their original state. (One important caveat is that these types of attacks are mitigated by trading in extremely liquid pools, and/or at low values.)

The best way to protect against these attacks is to use an external price feed or “price oracle”. The best “oracle” is simply *traders’ off-chain observation of the current price*, which can be passed into the trade as a safety check. This strategy is best for situations *where users initiate trades on their own behalf*.

However, when an off-chain price can’t be used, an on-chain oracle should be used instead. Determining the best oracle for a given situation is a not part of this guide, but for more details on the Swipeswap approach to oracles.


# Providing Liquidity

## Introduction <a href="#introduction" id="introduction"></a>

When providing liquidity from a smart contract, the most important thing to keep in mind is that tokens deposited into a pool at any rate other than the current reserve ratio *are vulnerable to being arbitraged*. As an example, if the ratio of x:y in a pair is 10:2 (i.e. the price is 5), and someone naively adds liquidity at 5:2 (a price of 2.5), the contract will simply accept all tokens (changing the price to 3.75 and opening up the market to arbitrage), but only issue pool tokens entitling the sender to the amount of assets sent at the proper ratio, in this case 5:1. To avoid donating to arbitrageurs, it is imperative to add liquidity at the current price. Luckily, it’s easy to ensure that this condition is met!

## Using the Router <a href="#using-the-router" id="using-the-router"></a>

The easiest way to safely add liquidity to a pool is to use the router, which provides simple methods to safely add liquidity to a pool. If the liquidity is to be added to an ERC-20/ERC-20 pair, use addLiquidity. If WETH is involved, use addLiquidityETH.

These methods both require the caller to commit to a *belief about the current price*, which is encoded in the `amount*Desired` parameters. Typically, it’s fairly safe to assume that the current fair market price is around what the current reserve ratio is for a pair (because of arbitrage). So, if a user wants to add 1 ETH to a pool, and the current DAI/WETH ratio of the pool is 200/1, it’s reasonable to calculate that 200 DAI must be sent along with the ETH, which is an implicit commitment to the price of 200 DAI/1 WETH. However, it’s important to note that this must be calculated *before the transaction is submitted*. It is *not safe* to look up the reserve ratio from within a transaction and rely on it as a price belief, as this ratio can be cheaply manipulated to your detriment.

However, it is still possible to submit a transaction which encodes a belief about the price which ends up being wrong because of a larger change in the true market price before the transaction is confirmed. For that reason, it’s necessary to pass an additional set of parameters which encode the caller’s tolerance to price changes. These `amount*Min` parameters should typically be set to percentages of the calculated desired price. So, at a 1% tolerance level, if our user sends a transaction with 1 ETH and 200 DAI, `amountETHMin` should be set to e.g. .99 ETH, and `amountTokenMin` should be set to 198 DAI. This means that, at worst, liquidity will be added at a rate between 198 DAI/1 ETH and 202.02 DAI/1 ETH (200 DAI/.99 ETH).

Once the price calculations have been made, it’s important to ensure that your contract a) controls at least as many tokens/ETH as were passed as `amount*Desired` parameters, and b) has granted approval to the router to withdraw this many tokens.


# Building an Oracle

To build a price oracle on Swipeswap, you must first understand the requirements for your use case. Once you understand the kind of price average you require, it is a matter of storing the cumulative price variable from the pair as often as necessary, and computing the average price using two or more observations of the cumulative price variables.

## Understanding requirements <a href="#understanding-requirements" id="understanding-requirements"></a>

To understand your requirements, you should first research the answer to the following questions:

* Is data freshness important? I.e.: must the price average include the current price?
* Are recent prices more important than historical prices? I.e.: is the current price given more weight than historical prices?

Note your answers for the following discussion.

## Oracle Strategies <a href="#oracle-strategies" id="oracle-strategies"></a>

### Fixed windows <a href="#fixed-windows" id="fixed-windows"></a>

In the case where data freshness is not important and recent prices are weighted equally with historical prices, it is enough to store the cumulative price once per period (e.g. once per 24 hours.)

Computing the average price over these data points gives you ‘fixed windows’, which can be updated after the lapse of each period..

This example does not limit the maximum size of the fixed window, i.e. it only requires that the window size is greater than 1 period (e.g. 24 hours).

### Moving averages <a href="#moving-averages" id="moving-averages"></a>

In the case where data freshness is important, you can use a sliding window in which the cumulative price variable is measured more often than once per period.

There are at least [two kinds of moving averages](https://www.investopedia.com/terms/m/movingaverage.asp#types-of-moving-averages) that you can compute using the Swipeswap cumulative price variable.

[Simple moving averages](https://www.investopedia.com/terms/s/sma.asp) give equal weight to each price measurement. We have built an example of a sliding window oracle [here](https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol).

[Exponential moving averages](https://www.investopedia.com/terms/e/ema.asp) give more weight to the most recent price measurements. We do not yet have an example written for this type of oracle.

You may wish to use exponential moving averages where recent prices are more important than historical prices, e.g. in case of liquidations. However, note that putting more weight on recent prices makes the oracle cheaper to manipulate than weighting all price measurements equally.

### Computing average prices <a href="#computing-average-prices" id="computing-average-prices"></a>

To compute the average price given two cumulative price observations, take the difference between the cumulative price at the beginning and end of the period, and divide by the elapsed time between them in seconds. This will produce a [fixed point unsigned Q112x112](https://en.wikipedia.org/wiki/Fixed-point_arithmetic#Notation) number that represents the price of one asset relative to the other. This number is represented as a `uint224` where the upper 112 bits represent the integer amount, and the lower 112 bits represent the fractional amount.

Pairs contain both `price0CumulativeLast` and `price1CumulativeLast`, which are ratios of reserves of `token1`/`token0` and `token0`/`token1` respectively. I.e. the price of `token0` is expressed in terms of `token1`/`token0`, while the price of `token1` is expressed in terms of `token0`/`token1`.

## Getting the latest cumulative price <a href="#getting-the-latest-cumulative-price" id="getting-the-latest-cumulative-price"></a>

If you wish to compute the average price between a historical price cumulative observation and the current cumulative price, you should use the cumulative price values from the current block. If the cumulative price has not been updated in the current block, e.g. because there has not been any liquidity event (`mint`/`burn`/`swap`) on the pair in the current block, you can compute the cumulative price counterfactually.

We provide a library for use in oracle contracts that has the method  [`UniswapV2OracleLibrary#currentCumulativePrices`](https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2OracleLibrary.sol#L16) for getting the cumulative price as of the current block. The current cumulative price returned by this method is computed *counterfactually*, meaning it requires no call to the relative gas-expensive `#sync` method on the pair. It is correct regardless of whether a swap has already executed in the current block.

## Notes on overflow <a href="#notes-on-overflow" id="notes-on-overflow"></a>

The `UniswapV2Pair` cumulative price variables are designed to eventually overflow, i.e. `price0CumulativeLast` and `price1CumulativeLast` and `blockTimestampLast` will overflow through 0.

This should not pose an issue to your oracle design, as the price average computation is concerned with differences (i.e. subtraction) between two separate observations of a cumulative price variable. Subtracting between two cumulative price values will result in a number that fits within the range of `uint256` as long as the observations are made for periods of max `2^32` seconds, or \~136 years.

`blockTimestampLast` is stored only in a `uint32`. For the same reason as described above, the pair can save a storage slot, and many SSTORES over the life of the pair, by storing only `block.timestamp % uint32(-1)`. This is feasible because the pair is only concerned with the time that elapses between each liquidity event when updating the cumulative prices, which is always expected to be less than `2^32` seconds.

When computing time elapsed within your own oracle, you can simply store the `block.timestamp` of your observations as `uint256`, and avoid dealing with overflow math for computing the time elapsed between observations. This is how the [ExampleSlidingWindowOracle](https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol) handles observation timestamps.[ExampleSlidingWindowOracle](https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol)

### Integrating the oracle <a href="#integrating-the-oracle" id="integrating-the-oracle"></a>

To integrate an oracle into your contracts, you must ensure the oracle’s observations of the cumulative price variable are kept up to date. As long as your oracle is up to date, you can depend on it to produce average prices. The process of keeping your oracle up to date is called ‘maintenance’.

### Oracle maintenance <a href="#oracle-maintenance" id="oracle-maintenance"></a>

In order to measure average prices over a period, the oracle must have a way of referencing the cumulative price at the start and end of a period. The recommended way of doing this is by storing these prices in the oracle contract, and calling the oracle frequently enough to store the latest cumulative price.

Reliable oracle maintenance is a difficult task, and can become a point of failure in times of congestion. Instead, consider building this functionality directly into the critical calls of your own smart contracts, or incentivize oracle maintenance calls by other parties.

### No-maintenance option <a href="#no-maintenance-option" id="no-maintenance-option"></a>

It is possible to avoid regularly storing this cumulative price at the start of the period by utilizing storage proofs. However, this approach has limitations, especially in regard to gas cost and maximum length of the time period over which the average price can be measured. If you wish to try this approach, you can follow [this repository by Keydonix](https://github.com/Keydonix/uniswap-oracle/).[Keydonix: on-chain trustless and censorship resistant oracle](https://github.com/Keydonix/uniswap-oracle)

Keydonix has developed a general purpose price feed oracle built on Swipeswap v2 that supports arbitrary time windows (up to 256 blocks) and doesn’t require any active maintenance.


# Flash Swaps

Flash swaps are an integral feature of Swipeswap. In fact, under the hood, all swaps are actually flash swaps! This simply means that pair contracts send output tokens to the recipient *before* enforcing that enough input tokens have been received. This is slightly atypical, as one might expect a pair to ensure it’s received payment before delivery. However, because Ethereum transactions are *atomic*, we can roll back the entire swap if it turns out that the contract hasn’t received enough tokens to make itself whole by the end of the transaction.

To see how this all works, let’s start by examining the interface of the `swap` function:

```
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data);
```

For the sake of example, let’s assume that we’re dealing with a DAI/WETH pair, where DAI is `token0` and WETH is `token1`. `amount0Out` and `amount1Out` specify the amount of DAI and WETH that the `msg.sender` wants the pair to send to the `to` address (one of these amounts may be 0). At this point you may be wondering how the contract *receives* tokens. For a typical (non-flash) swap, it’s actually the responsibility of `msg.sender` to ensure that enough WETH or DAI has *already been sent* to the pair before `swap` is called (in the context of trading, this is all handled neatly by a router contract). But when executing a flash swap, *tokens do not need to be sent to the contract before calling `swap`*. Instead, they must be sent from within a *callback function* that the pair triggers on the `to` address.

## Triggering a Flash Swap <a href="#triggering-a-flash-swap" id="triggering-a-flash-swap"></a>

To differentiate between the “typical” trading case and the flash swap case, pairs use the `data` parameter. Specifically, if `data.length` equals 0, the contract assumes that payment has already been received, and simply transfers the tokens to the `to` address. But, if `data.length` is greater than 0, the contract transfers the tokens and then calls the following function on the `to` address:

```
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data);
```

The logic behind this identification strategy is simple: the vast majority of valid flash swap use cases involve interactions with external protocols. The best way to pass information dictating how these interactions happen (function arguments, safety parameters, addresses, etc.) is via the `data` parameter. It’s expected that `data` will be `abi.decode`d from within `uniswapV2Call`. In the rare case where no data is required, callers should ensure that `data.length` equals 1 (i.e. encode a single junk byte as `bytes`), and then ignore this argument in `uniswapV2Call`.

Pairs call `uniswapV2Call` with the `sender` argument set to the `msg.sender` of the `swap`. `amount0` and `amount1` are simply `amount0Out` and `amount1Out`.

## Using uniswapV2Call <a href="#using-uniswapv2call" id="using-uniswapv2call"></a>

There are several conditions that should be checked in all `uniswapV2Call` functions:

```
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) {
  address token0 = IUniswapV2Pair(msg.sender).token0(); // fetch the address of token0
  address token1 = IUniswapV2Pair(msg.sender).token1(); // fetch the address of token1
  assert(msg.sender == IUniswapV2Factory(factoryV2).getPair(token0, token1)); // ensure that msg.sender is a V2 pair
  // rest of the function goes here!
}
```

The first 2 lines simply fetch the token addresses from the pair, and the 3rd ensures that the `msg.sender` is an actual Swipeswap pair address.

## Repayment <a href="#repayment" id="repayment"></a>

At the end of `uniswapV2Call`, contracts must return enough tokens to the pair to make it whole. Specifically, this means that the product of the pair reserves after the swap, discounting all token amounts sent by 0.3% LP fee, must be greater than before.

### Multi-Token <a href="#multi-token" id="multi-token"></a>

In the case where the token withdrawn is *not* the token returned (i.e. DAI was requested in the flash swap, and WETH was returned, or vice versa), the fee simplifies to the simple swap case. This means that the standard `getAmountIn` pricing function should be used to calculate e.g., the amount of WETH that must be returned in exchange for the amount of DAI that was requested out.

This type of fee calculation gives a slight advantage to the caller, as the fee derived from repayment in a corresponding token will always be slightly less than the fee derived from a direct token repayment, as a result of the difference between the amount required to pay back a swap, versus the amount withdrawn and then directly returned. The approximate comparison of fees is \~ 30 bps for a swap fee vs. 30.09 bps for a direct repayment.

### Single-Token <a href="#single-token" id="single-token"></a>

In the case where the token withdrawn is the *same* as the token returned (i.e. DAI was requested in the flash swap, used, then returned, or vice versa with WETH), the following condition must be satisfied:

`DAIReservePre - DAIWithdrawn + (DAIReturned * .997) >= DAIReservePre`

It may be more intuitive to rewrite this formula in terms of a “fee” levied on the *withdrawn* amount (despite the fact that Swipeswap always levies fees on input amounts, in this case the *returned* amount, here we can simplify to an effective fee on the *withdrawn* amount). If we rearrange, the formula looks like:

`(DAIReturned * .997) - DAIWithdrawn >= 0`

`DAIReturned >= DAIWithdrawn / .997`

So, the effective fee on the withdrawn amount is `.003 / .997 ≈ 0.3009027%`.

## Interface <a href="#interface" id="interface"></a>

```
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Callee.sol';
```

```
pragma solidity >=0.5.0;

interface IUniswapV2Callee {
  function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
```


# Pair Addresses

## getPair <a href="#getpair" id="getpair"></a>

The most obvious way to get the address for a pair is to call getPair on the factory. If the pair exists, this function will return its address, else `address(0)` (`0x0000000000000000000000000000000000000000`).

* The “canonical” way to determine whether or not a pair exists.
* Requires an on-chain lookup.

## CREATE2 <a href="#create2" id="create2"></a>

Thanks to some [fancy footwork in the factory](https://github.com/SwipeWallet/swipe-swap/blob/master/contracts/uniswapv2/UniswapV2Factory.sol#L30), we can also compute pair addresses *without any on-chain lookups* because of [CREATE2](https://eips.ethereum.org/EIPS/eip-1014). The following values are required for this technique:

|                        |                                                                                     |
| ---------------------- | ----------------------------------------------------------------------------------- |
| `address`              | The [factory address](https://uniswap.org/docs/v2/smart-contracts/factory/#address) |
| `salt`                 | `keccak256(abi.encodePacked(token0, token1))`                                       |
| `keccak256(init_code)` | `0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f`                |

* `token0` must be strictly less than `token1` by sort order.
* Can be computed offline.
* Requires the ability to perform `keccak256`.

### Examples <a href="#examples" id="examples"></a>

#### Solidity <a href="#solidity" id="solidity"></a>

```
address factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address token0 = 0xCAFE000000000000000000000000000000000000; // change me!
address token1 = 0xF00D000000000000000000000000000000000000; // change me!

address pair = address(uint(keccak256(abi.encodePacked(
  hex'ff',
  factory,
  keccak256(abi.encodePacked(token0, token1)),
  hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
```


# Supporting meta transactions

All Swipeswap pool tokens support meta-transaction approvals via the permit function. This obviates the need for a blocking approve transaction before programmatic interactions with pool tokens can occur.

## ERC-712 <a href="#erc-712" id="erc-712"></a>

In vanilla ERC-20 token contracts, owners may only register approvals by directly calling a function which uses `msg.sender` to permission itself. With meta-approvals, ownership and permissioning are derived from a signature passed into the function by the caller (sometimes referred to as the relayer). Because signing data with Ethereum private keys can be a tricky endeavor, Swipeswap relies on [ERC-712](https://eips.ethereum.org/EIPS/eip-712), a signature standard with widespread community support, to ensure user safety and wallet compatibility.

### Domain Separator <a href="#domain-separator" id="domain-separator"></a>

```
keccak256(
  abi.encode(
    keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
    keccak256(bytes(name)),
    keccak256(bytes('1')),
    chainId,
    address(this)
  )
);
```

* `name` is always `Uniswap V2`.
* `chainId` is determined from the [ERC-1344](https://ethereum-magicians.org/t/eip-1344-add-chain-id-opcode/1131) `chainid` opcode.
* `address(this)` is the address of the pair, see [Pair Addresses](/swap/smart-contract/pair-addresses#getpair).

```
keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');`
```


# Subgraph API

This section explains the Swipe Subgraph and how to interact with it. The Swipe subgraph indexes data from the Swipe contracts over time.

### Resources <a href="#resources" id="resources"></a>

### **Mainnet**

Coming soon

### **Testnet**

[Exchange Explorer](https://thegraph.com/explorer/subgraph/techstreamp/ropsten-swipeswap) - Testnet for querying data and endpoints of Swipe Exchange.

[MasterChef Explorer ](https://thegraph.com/explorer/subgraph/techstreamp/ropsten-masterchef)- Testnet for querying data and endpoints of Swipe .

[SwipeSwap Subgraph](https://github.com/SwipeWallet/swipeswap-subgraph) - source code for deployed subgraph.

### Usage <a href="#usage" id="usage"></a>

The subgraph provides a snapshot of the current state of [SwipeSwap](https://testnet.swipe.org/swap) and also tracks historical data. **It is not intended to be used as a data source for structuring transactions (contracts should be referenced directly for the most reliable live data).**

### Making Queries <a href="#making-queries" id="making-queries"></a>

To learn more about querying a subgraph refer to [The Graph’s documentation](https://thegraph.com/docs/introduction).


# Exchange

{% content-ref url="/pages/-MUOEOSta-rpyDJUKMab" %}
[Entities](/swap/subgraph-api/exchange/entities)
{% endcontent-ref %}

{% content-ref url="/pages/-MUOEUoseLYZ7nhk2HEI" %}
[Queries](/swap/subgraph-api/exchange/queries)
{% endcontent-ref %}


# Entities

Entities define the schema of the subgraph, and represent the data that can be queried. Within each entity are sets of fields that store useful information related to the entity. Below is a list of the available entities within the SwipeSwap Subgraph, and descriptions for the available fields.

To see an interactive sandbox of all entities see the [Graph Explorer](https://thegraph.com/explorer/subgraph/techstreamp/ropsten-swipeswap).

Each entity is defined with a value type, which will always be a base AssemblyScript type, or a custom type provided by The Graph’s custom TypeScript library. For more information on value types see [here](https://thegraph.com/docs/assemblyscript-api#api-reference).

#### Factory <a href="#uniswap-factory" id="uniswap-factory"></a>

The Factory entity is responsible for storing aggregate information across all SwipeSwap pairs. It can be used to view stats about total liquidity, volume, amount of pairs and more. There is only one Factory entity in the subgraph.

| Field Name        | Value Type | Description                                                     |
| ----------------- | ---------- | --------------------------------------------------------------- |
| id                | ID         | factory address                                                 |
| pairCount         | Int        | amount of pairs created by the factory                          |
| totalVolumeUSD    | BigDecimal | all time USD volume across all pairs (USD is derived)           |
| totalVolumeETH    | BigDecimal | all time volume in ETH across all pairs (ETH is derived)        |
| totalLiquidityUSD | BigDecimal | total liquidity across all pairs stored as a derived USD amount |
| totalLiquidityETH | BigDecimal | total liquidity across all pairs stored as a derived ETH amount |
| txCount           | BigInt     | all time amount of transactions across all pairs                |

#### Token <a href="#token" id="token"></a>

Stores aggregated information for a specific token across all pairs that token is included in.

| Field Name         | Value Type | Description                                                                                                  |
| ------------------ | ---------- | ------------------------------------------------------------------------------------------------------------ |
| id                 | ID         | token address                                                                                                |
| symbol             | String     | token symbol                                                                                                 |
| name               | String     | token name                                                                                                   |
| decimals           | BigInt     | token decimals                                                                                               |
| tradeVolume        | BigDecimal | amount of token traded all time across all pairs                                                             |
| tradeVolumeUSD     | BigDecimal | amount of token in USD traded all time across pairs (only for tokens with liquidity above minimum threshold) |
| untrackedVolumeUSD | BigDecimal | amount of token in USD traded all time across pairs (no minimum liquidity threshold)                         |
| txCount            | BigInt     | amount of transactions all time in pairs including token                                                     |
| totalLiquidity     | BigDecimal | total amount of token provided as liquidity across all pairs                                                 |
| derivedETH         | BigDecimal | ETH per token                                                                                                |

#### Pair <a href="#pair" id="pair"></a>

Information about a pair. Includes references to each token within the pair, volume information, liquidity information, and more. The pair entity mirrors the pair smart contract, and also contains aggregated information about use.

| Field Name           | Value Type           | Description                                                                                                         |
| -------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| id                   | ID                   | pair contract address                                                                                               |
| factory              | Factory              | reference to factory entity                                                                                         |
| token0               | Token                | reference to token0 as stored in pair contract                                                                      |
| token1               | Token                | reference to token1 as stored in pair contract                                                                      |
| reserve0             | BigDecimal           | reserve of token0                                                                                                   |
| reserve1             | BigDecimal           | reserve of token1                                                                                                   |
| totalSupply          | BigDecimal           | total supply of liquidity token distributed to LPs                                                                  |
| reserveETH           | BigDecimal           | total liquidity in pair stored as an amount of ETH                                                                  |
| reserveUSD           | BigDecimal           | total liquidity amount in pair stored as an amount of USD                                                           |
| trackedReserveETH    | BigDecimal           | total liquidity with only tracked amount (see tracked amounts)                                                      |
| token0Price          | BigDecimal           | token0 per token1                                                                                                   |
| token1Price          | BigDecimal           | token1 per token0                                                                                                   |
| volumeToken0         | BigDecimal           | amount of token0 swapped on this pair                                                                               |
| volumeToken1         | BigDecimal           | amount of token1 swapped on this pair                                                                               |
| volumeUSD            | BigDecimal           | total amount swapped all time in this pair stored in USD (only tracked if USD liquidity is above minimum threshold) |
| untrackedVolumeUSD   | BigDecimal           | total amount swapped all time in this pair stored in USD, no minimum liquidity threshold                            |
| txCount              | BigInt               | all time amount of transactions on this pair                                                                        |
| createdAtTimestamp   | BigInt               | timestamp contract was created                                                                                      |
| createdAtBlockNumber | BigInt               | Ethereum block contract was created                                                                                 |
| liquidityPositions   | \[LiquidityPosition] | array of liquidity providers, used as a reference to LP entities                                                    |

#### User <a href="#user" id="user"></a>

A user entity is created for any address that provides liquidity to a pool on SwipeSwap. This entity can be used to track open positions for users. LiquidyPosition entities can be referenced to get specific data about each position.

| Field Name         | Value Type           | Description                                    |
| ------------------ | -------------------- | ---------------------------------------------- |
| id                 | ID                   | user address                                   |
| liquidityPositions | \[LiquidityPosition] | array of all liquidity positions user has open |
| usdSwapped         | BigDecimal           | total USD value swapped                        |

#### LiquidityPositiion <a href="#liquiditypositiion" id="liquiditypositiion"></a>

This entity is used to store data about a user’s liquidity position. This information, along with information from the pair itself can be used to provide position sizes, token deposits, and more.

| Field Name            | Value Type | Description                                            |
| --------------------- | ---------- | ------------------------------------------------------ |
| id                    | ID         | user address and pair address concatenated with a dash |
| user                  | User       | reference to user                                      |
| pair                  | Pair       | reference to the pair liquidity is being provided on   |
| liquidityTokenBalance | BigDecimal | amount of LP tokens minted for this position           |

#### Transaction <a href="#transaction" id="transaction"></a>

Transaction entities are created for each Ethereum transaction that contains an interaction within SwipeSwap contracts. This subgraph tracks Mint, Burn, and Swap events on the SwipeSwap core contracts. Each transaction contains 3 arrays, and at least one of these arrays has a length of 1.

| Field Name  | Value Type | Description                                               |
| ----------- | ---------- | --------------------------------------------------------- |
| id          | ID         | Ethereum transaction hash                                 |
| blockNumber | BigInt     | block transaction was mined in                            |
| timestamp   | BigInt     | timestamp for transaction                                 |
| mints       | \[Mint]    | array of Mint events within the transaction, 0 or greater |
| burns       | \[Burn]    | array of Burn events within transaction, 0 or greater     |
| swaps       | \[Swap]    | array of Swap events within transaction, 0 or greater     |

#### Mint <a href="#mint" id="mint"></a>

Mint entities are created for every emitted Mint event on the SwipeSwap core contracts. The Mint entity stores key data about the event like token amounts, who sent the transaction, who received the liquidity, and more. This entity can be used to track liquidity provisions on pairs.

| Field Name   | Value Type  | Description                                                 |
| ------------ | ----------- | ----------------------------------------------------------- |
| id           | ID          | Transaction hash plus index in the transaction mint array   |
| transaction  | Transaction | reference to the transaction Mint was included in           |
| timestamp    | BigInt      | timestamp of Mint, used to sort recent liquidity provisions |
| pair         | Pair        | reference to pair                                           |
| to           | Bytes       | recipient of liquidity tokens                               |
| liquidity    | BigDecimal  | amount of liquidity tokens minted                           |
| sender       | Bytes       | address that initiated the liquidity provision              |
| amount0      | BigDecimal  | amount of token0 provided                                   |
| amount1      | BigDecimal  | amount of token1 provided                                   |
| logIndex     | BigInt      | index in the transaction event was emitted                  |
| amountUSD    | BigDecimal  | derived USD value of token0 amount plus token1 amount       |
| feeTo        | Bytes       | address of fee recipient (if fee is on)                     |
| feeLiquidity | BigDecimal  | amount of liquidity sent to fee recipient (if fee is on)    |

#### Burn <a href="#burn" id="burn"></a>

Burn entities are created for every emitted Burn event on the SwipeSwap core contracts. The Burn entity stores key data about the event like token amounts, who burned LP tokens, who received tokens, and more. This entity can be used to track liquidity removals on pairs.

| Field Name   | Value Type  | Description                                               |
| ------------ | ----------- | --------------------------------------------------------- |
| id           | ID          | Transaction hash plus index in the transaction burn array |
| transaction  | Transaction | reference to the transaction Burn was included in         |
| timestamp    | BigInt      | timestamp of Burn, used to sort recent liquidity removals |
| pair         | Pair        | reference to pair                                         |
| to           | Bytes       | recipient of tokens                                       |
| liquidity    | BigDecimal  | amount of liquidity tokens burned                         |
| sender       | Bytes       | address that initiated the liquidity removal              |
| amount0      | BigDecimal  | amount of token0 removed                                  |
| amount1      | BigDecimal  | amount of token1 removed                                  |
| logIndex     | BigInt      | index in the transaction event was emitted                |
| amountUSD    | BigDecimal  | derived USD value of token0 amount plus token1 amount     |
| feeTo        | Bytes       | address of fee recipient (if fee is on)                   |
| feeLiquidity | BigDecimal  | amount of tokens sent to fee recipient (if fee is on)     |

#### Swap <a href="#swap" id="swap"></a>

Swap entities are created for each token swap within a pair. The Swap entity can be used to get things like swap size (in tokens and USD), sender, recipient and more. See the Swap overview page for more information on amounts.

| Field Name  | Value Type  | Description                                           |
| ----------- | ----------- | ----------------------------------------------------- |
| id          | ID          | transaction hash plus index in Transaction swap array |
| transaction | Transaction | reference to transaction swap was included in         |
| timestamp   | BigInt      | timestamp of swap, used for sorted lookups            |
| pair        | Pair        | reference to pair                                     |
| sender      | Bytes       | address that initiated the swap                       |
| amount0In   | BigDecimal  | amount of token0 sold                                 |
| amount1In   | BigDecimal  | amount of token1 sold                                 |
| amount0Out  | BigDecimal  | amount of token0 received                             |
| amount1Out  | BigDecimal  | amount of token1 received                             |
| to          | Bytes       | recipient of output tokens                            |
| logIndex    | BigInt      | event index within transaction                        |
| amountUSD   | BigDecimal  | derived amount of tokens sold in USD                  |

#### Bundle <a href="#bundle" id="bundle"></a>

The Bundle is used as a global store of derived ETH price in USD. Because there is no guaranteed common base token across pairs, a global reference of USD price is useful for deriving other USD values. The Bundle entity stores an updated weighted average of ETH<->Stablecoin pair prices. This provides a strong estimate for the USD price of ETH that can be used in other places in the subgraph.

| Field Name | Value Type | Description                                           |
| ---------- | ---------- | ----------------------------------------------------- |
| id         | ID         | constant 1                                            |
| ethPrice   | BigDecimal | derived price of ETH in USD based on stablecoin pairs |

### Historical Entities <a href="#historical-entities" id="historical-entities"></a>

The subgraph tracks aggregated information grouped by days to provide insights to daily activity on SwipeSwap. While [time travel queries](https://blocklytics.org/blog/ethereum-blocks-subgraph-made-for-time-travel/) can be used for direct comparison against values in the past, it is much more expensive to query grouped data. For this reason the subgraph tracks information grouped in daily buckets, using timestamps provided by contract events. These entities can be used to query things like total volume on a given day, price of a token on a given day, etc.

For each DayData type, a new entity is created each day.

#### PairDayData <a href="#uniswapdaydata" id="uniswapdaydata"></a>

Tracks data across all pairs aggregated into a daily bucket.

| Field Name        | Value Type       | Description                                                                      |
| ----------------- | ---------------- | -------------------------------------------------------------------------------- |
| id                | ID               | unix timestamp for start of day / 86400 giving a unique day index                |
| date              | Int              | unix timestamp for start of day                                                  |
| dailyVolumeETH    | BigDecimal       | total volume across all pairs on this day, stored as a derived amount of ETH     |
| dailyVolumeUSD    | BigDecimal       | total volume across all pairs on this day, stored as a derived amount of USD     |
| totalVolumeETH    | BigDecimal       | all time volume across all pairs in ETH up to and including this day             |
| totalLiquidityETH | BigDecimal       | total liquidity across all pairs in ETH up to and including this day             |
| totalVolumeUSD    | BigDecimal       | all time volume across all pairs in USD up to and including this day             |
| totalLiquidityUSD | BigDecimal       | total liquidity across all pairs in USD up to and including this day             |
| maxStored         | Int              | reference used to store most liquid tokens, used for historical liquidity charts |
| mostLiquidTokens  | \[TokenDayData!] | tokens with most liquidity in SwipeSwap                                          |
| txCount           | BigInt           | number of transactions throughout this day                                       |

#### Pair Day Data <a href="#pair-day-data" id="pair-day-data"></a>

Tracks pair data across each day.

| Field Name        | Value Type | Description                                                                                     |
| ----------------- | ---------- | ----------------------------------------------------------------------------------------------- |
| id                | ID         | pair contract address and day id (day start timestamp in unix / 86400) concatenated with a dash |
| date              | Int        | unix timestamp for start of day                                                                 |
| pairAddress       | Bytes      | address for pair contract                                                                       |
| token0            | Token      | reference to token0                                                                             |
| token1            | Token      | reference to token1                                                                             |
| reserve0          | BigDecimal | reserve of token0 (updated during each transaction on pair)                                     |
| reserve1          | BigDecimal | reserve of token1 (updated during each transaction on pair)                                     |
| totalSupply       | BigDecimal | total supply of liquidity token distributed to LPs                                              |
| reserveUSD        | BigDecimal | reserve of token0 plus token1 stored as a derived USD amount                                    |
| dailyVolumeToken0 | BigDecimal | total amount of token0 swapped throughout day                                                   |
| dailyVolumeToken1 | BigDecimal | total amount of token1 swapped throughout day                                                   |
| dailyVolumeUSD    | BigDecimal | total volume within pair throughout day                                                         |
| dailyTxns         | BigInt     | amount of transactions on pair throughout day                                                   |

#### TokenDayData <a href="#tokendaydata" id="tokendaydata"></a>

Tracks token data aggregated across all pairs that include token.

| Field Name          | Value Type     | Description                                                                                                                            |
| ------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| id                  | ID             | token address and day id (day start timestamp in unix / 86400) concatenated with a dash                                                |
| date                | Int            | unix timestamp for start of day                                                                                                        |
| token               | Token          | reference to token entity                                                                                                              |
| dailyVolumeToken    | BigDecimal     | amount of token swapped across all pairs throughout day                                                                                |
| dailyVolumeETH      | BigDecimal     | amount of token swapped across all pairs throughout day stored as a derived amount of ETH                                              |
| dailyVolumeUSD      | BigDecimal     | amount of token swapped across all pairs throughout day stored as a derived amount of USD                                              |
| dailyTxns           | BigInt         | amount of transactions with this token across all pairs                                                                                |
| totalLiquidityToken | BigDecimal     | token amount of token deposited across all pairs                                                                                       |
| totalLiquidityETH   | BigDecimal     | token amount of token deposited across all pairs stored as amount of ETH                                                               |
| totalLiquidityUSD   | BigDecimal     | token amount of token deposited across all pairs stored as amount of USD                                                               |
| priceUSD            | BigDecimal     | price of token in derived USD                                                                                                          |
| maxStored           | Int            | amount of token deposited in pair with highest token liquidity - used only as a reference for storing most liquid pairs for this token |
| mostLiquidPairs     | \[PairDayData] | pairs with most liquidity for this token                                                                                               |

* [<br>](https://uniswap.org/docs/v2/API/overview/)


# Queries

The subgraph can be queried to retrieve important information about SwipeSwap, pairs, tokens, transactions, users, and more. This page will provide examples for common queries.

To try these queries and run your own visit the [Exchange subgraph sandbox](https://thegraph.com/explorer/subgraph/techstreamp/ropsten-swipeswap).

#### Global Data <a href="#global-data" id="global-data"></a>

To query global data you can pass in the SwipSwap Factory address and select from available fields.

**Global Stats**

All time volume in USD, total liquidity in USD, all time transaction count.

```graphql
{
    swipeswapFactory(id: "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f") {
        totalVolumeUSD
        totalLiquidityUSD
        txCount
    }
}
```

**Global Historical lookup**

To get a snapshot of past state, use The Graph’s block query feature and query at a previous block. See this post to get more information about [fetching block numbers from timestamps](https://blocklytics.org/blog/ethereum-blocks-subgraph-made-for-time-travel/). This can be used to calculate things like 24hr volume.

```graphql
{
    swipeswapFactory(
        id: "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f",
        block: {number: 10291203}
    ) {
        totalVolumeUSD
        totalLiquidityUSD
        txCount
    }
}
```

#### Pair Data <a href="#pair-data" id="pair-data"></a>

**Pair Overview**

Fetch a snapshot of the current state of the pair with common values. This example fetches the DAI/WETH pair.

```graphql
{
    pair(id: "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11") {
        token0 {
            id
            symbol
            name
            derivedETH
        }
        token1 {
            id
            symbol
            name
            derivedETH
        }
        reserve0
        reserve1
        reserveUSD
        trackedReserveETH
        token0Price
        token1Price
        volumeUSD
        txCount
    }
}
```

**All pairs in SwipeSwap**

The Graph limits entity return amounts to 1000 per query as of now. To get all pairs on SwipeSwap use a loop and graphql skip query to fetch multiple chunks of 1000 pairs. The query would look like this (where skip is some incrementing variable passed into your query).

```graphql
{
    query pairs($skip: Int!) {
        pairs(first: 1000, skip: $skip) {
            id
        }
    }
}
```

**Most liquid pairs**

Order by liquidity to get the most liquid pairs in SwipeSwap.

```graphql
{
    pairs(first: 1000, orderBy: reserveUSD, orderDirection: desc) {
        id
    }
}
```

**Recent Swaps within a Pair**

Get the last 100 swaps on a pair by fetching Swap events and passing in the pair address. You’ll often want token information as well.

```graphql
{
    swaps(orderBy: timestamp, orderDirection: desc, where: {pair: "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11" }) {
        pair {
            token0 { symbol }
            token1 { symbol }
        }
        amount0In
        amount0Out
        amount1In
        amount1Out
        amountUSD
        to
    }
}
```

**Pair Daily Aggregated**

Day data is useful for building charts and historical views around entities. To get stats about a pair in daily buckets query for day entities bounded by timestamps. This query gets the first 100 days after the given unix timestamp on the DAI/WETH pair.

```graphql
{
    pairDayDatas(
        first: 100, orderBy: date, orderDirection: asc,
        where: {
            pairAddress: "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11",
            date_gt: 1592505859
        }
    ) {
        date
        dailyVolumeToken0
        dailyVolumeToken1
        dailyVolumeUSD
        reserveUSD
    }
}
```

#### Token Data <a href="#token-data" id="token-data"></a>

Token data can be fetched using the token contract address as an ID. Token data is aggregated across all pairs the token is included in. Any token that is included in some pair in SwipeSwap can be queried.

**Token Overview**

Get a snapshot of the current stats on a token in SwipeSwap. This query fetches current stats on DAI. The allPairs field gets the first 200 pairs DAI is included in sorted by liquidity in derived USD.

```graphql
{
    token(id: "0x6b175474e89094c44da98b954eedeac495271d0f") {
        name
        symbol
        decimals
        derivedETH
        tradeVolumeUSD
        totalLiquidity
    }
}
```

**All Tokens in SwipeSwap**

Similar to fetching all pairs (see above), you can query all tokens in SwipeSwap. Because The Graph service limits return size to 1000 entities use graphql skip query. (Note this query will not work in the graph sandbox and more resembles the structure of a query you’d pass to some graphql middleware like [Apollo](https://www.apollographql.com/)).

```graphql
{
    query tokens($skip: Int!) {
        tokens(first: 1000, skip: $skip) {
            id
            name
            symbol
        }
    }
}
```

**Token Transactions**

To get transactions that include a token you’ll need to first fetch an array of pairs that the token is included in (this can be done with the allPairs field on the Token entity.) Once you have an array of pairs the token is included in, filter on that in the transaction lookup.

This query fetches the latest 30 mints, swaps, and burns involving DAI. The allPairs array could look something like this where we include the DAI/WETH pair address and the DAI/USDC pair address.

```graphql
allPairs = [
    "0xa478c2975ab1ea89e8196811f51a7b7ade33eb11",
    "0xae461ca67b15dc8dc81ce7615e0320da1a9ab8d5"
]
```

```graphql
query($allPairs: [String!]) {
    mints(first: 30, where: { pair_in: $allPairs }, orderBy: timestamp, orderDirection: desc) {
        transaction {
            id
            timestamp
        }
        to
        liquidity
        amount0
        amount1
        amountUSD
    }
    burns(first: 30, where: { pair_in: $allPairs }, orderBy: timestamp, orderDirection: desc) {
        transaction {
            id
            timestamp
        }
        to
        liquidity
        amount0
        amount1
        amountUSD
    }
    swaps(first: 30, where: { pair_in: $allPairs }, orderBy: timestamp, orderDirection: desc) {
        transaction {
            id
            timestamp
        }
        amount0In
        amount0Out
        amount1In
        amount1Out
        amountUSD
        to
    }
}
```

**Token Daily Aggregated**

Like pair and global daily lookups, tokens have daily entities that can be queries as well. This query gets daily information for DAI. Note that you may want to sort in ascending order to receive your days from oldest to most recent in the return array.

```graphql
{
    tokenDayDatas(orderBy: date, orderDirection: asc,  where: {
        token: "0x6b175474e89094c44da98b954eedeac495271d0f"
    }) {
        id
        date
        priceUSD
        totalLiquidityToken
        totalLiquidityUSD
        totalLiquidityETH
        dailyVolumeETH
        dailyVolumeToken
        dailyVolumeUSD
    }
}
```

#### ETH Price <a href="#eth-price" id="eth-price"></a>

You can use the Bundle entity to query current USD price of ETH in SwipeSwap based on a weighted average of stablecoins.

```graphql
{
    bundle(id: "1" ) {
        ethPrice
    }
}
```


# MasterChef

{% content-ref url="/pages/-MUOZhvnz1w0Y3Kyp3Wu" %}
[Entities](/swap/subgraph-api/masterchef/entities)
{% endcontent-ref %}

{% content-ref url="/pages/-MUOZhAqEKZ6UEyfdQON" %}
[Queries](/swap/subgraph-api/masterchef/queries)
{% endcontent-ref %}


# Entities

**Masterchef**

| Field           | Type       | Description            |
| --------------- | ---------- | ---------------------- |
| id              | ID         | chef address           |
| bonusMultiplier | BigInt     | bonus multiplier       |
| devaddr         | Bytes      | dev address            |
| migrator        | Bytes      | migrator address       |
| owner           | Bytes      | owner address          |
| startBlock      | BigInt     | start block            |
| swipe           | Bytes      | swipe token address    |
| swipePerBlock   | BigInt     | swipe per block        |
| totalAllocPoint | BigInt     | total allocation point |
| pools           | \[Pools]   | array of pools         |
| poolCount       | BigInt     | pool count             |
| slpBalance      | BigDecimal | slp balance            |
| slpAge          | BigDecimal | slp age                |
| slpAgeRemoved   | BigDecimal | slp age removed        |
| slpDeposited    | BigDecimal | slp deposited          |
| slpWithdrawn    | BigDecimal | slp withdrawn          |
| history         | \[History] | array of history       |
| updatedAt       | BigInt     | updated at             |

**History**

| Field         | Type       | Description                                     |
| ------------- | ---------- | ----------------------------------------------- |
| id            | ID         | unix timestamp for the start of the day / 86400 |
| owner         | Bytes      | owner address                                   |
| slpBalance    | BigDecimal | slp balance                                     |
| slpAge        | BigDecimal | slp age                                         |
| slpAgeRemoved | BigDecimal | slp age removed                                 |
| slpDeposited  | BigDecimal | slp deposited                                   |
| slpWithdrawn  | BigDecimal | slp withdrawn                                   |
| timestamp     | BigInt     | timestamp                                       |
| block         | BigInt     | block                                           |

**Pool**

| Field             | Type       | Description                 |
| ----------------- | ---------- | --------------------------- |
| id                | ID         | id                          |
| owner             | Bytes      | owner address               |
| pair              | Bytes      | pair address                |
| allocPoint        | BigInt     | allocation point            |
| lastRewardBlock   | BigInt     | last reward block           |
| accSwipePerShare  | BigInt     | accumulated swipe per share |
| users             | \[User]    | array of users              |
| userCount         | BigInt     | user count                  |
| slpBalance        | BigDecimal | slp balance                 |
| slpAge            | BigDecimal | slp age                     |
| slpAgeRemoved     | BigDecimal | slp age removed             |
| slpDeposited      | BigDecimal | slp deposited               |
| slpWithdrawn      | BigDecimal | slp withdrawn               |
| swipeHarvested    | BigDecimal | swipe harvested             |
| swipeHarvestedUSD | BigDecimal | swipe harvested usd         |
| entryUSD          | BigDecimal | all-time entries in USD     |
| exitUSD           | BigDecimal | all-time exits in USD       |
| timestamp         | BigInt     | timestamp                   |
| block             | BigInt     | block                       |
| updatedAt         | BigInt     | updated at timestamp        |

**Pool History**

| Field             | Type       | Description                                                               |
| ----------------- | ---------- | ------------------------------------------------------------------------- |
| id                | ID         | pool id concatenated with unix timestamp for the start of the day / 86400 |
| pool              | Pool       | pool                                                                      |
| pair              | Bytes      | pair address                                                              |
| users             | \[User]    | array of users                                                            |
| userCount         | BigInt     | user count                                                                |
| slpBalance        | BigDecimal | slp balance                                                               |
| slpAge            | BigDecimal | slp age                                                                   |
| slpAgeRemoved     | BigDecimal | slp age removed                                                           |
| slpDeposited      | BigDecimal | slp deposited                                                             |
| slpWithdrawn      | BigDecimal | slp withdrawn                                                             |
| swipeHarvested    | BigDecimal | swipe harvested                                                           |
| swipeHarvestedUSD | BigDecimal | swipe harvested usd                                                       |
| entryUSD          | BigDecimal | all-time entries in usd                                                   |
| exitUSD           | BigDecimal | all-time exits in usd                                                     |
| timestamp         | BigInt     | timestamp                                                                 |
| block             | BigInt     | block                                                                     |
| updatedAt         | BigInt     | updated at timestamp                                                      |

**User**

| Field                        | Type       | Description                      |
| ---------------------------- | ---------- | -------------------------------- |
| id                           | ID         | user address                     |
| pool                         | Pool       | pool                             |
| amount                       | BigInt     | amount                           |
| rewardDebt                   | BigInt     | reward debt                      |
| entryUSD                     | BigDecimal | all-time entries in usd          |
| exitUSD                      | BigDecimal | all-time exits in usd            |
| swipeHarvested               | BigDecimal | swipe harvested                  |
| swipeHarvestedUSD            | BigDecimal | swipe harvested usd              |
| swipeHarvestedSinceLockup    | BigDecimal | swipe harvested since lockup     |
| swipeHarvestedSinceLockupUSD | BigDecimal | swipe harvested since lockup usd |
| timestamp                    | BigInt     | timestamp                        |
| block                        | BigInt     | block                            |


# Queries

The subgraph can be queried to retrieve important information about MasterChef, pools, pool histories, users, and more. This page will provide examples for common queries.

To try these queries and run your own visit the [MasterChef subgraph sandbox](https://thegraph.com/explorer/subgraph/techstreamp/ropsten-masterchef).

**MasterChef**

All time Swipe rewards, total rewards in USD, all time pool count.

```graphql
{
  masterChef(id: "0x267748fe0db99863e1d5448ef5b9442230c24789") {
    id
    bonusMultiplier
    bonusEndBlock
    swipe
    swipePerBlock
    totalAllocPoint
    poolCount
  }
}
```

**Pool**

Current Pool balance, all time swipe harvested, harvested Swipe in USD

```graphql
{
  pool(id: 2) {
    id
    pair
    balance
    entryUSD
    exitUSD
    swipeHarvested
    swipeHarvestedUSD
    block
    slpBalance
    slpAge
    slpAgeRemoved
    slpDeposited
    slpWithdrawn
    userCount
  }
}

```

**Pool History**

Snapshot of a pool state at every block generation time

```graphql
{
  poolHistory(id: "118682") {
    id
    entryUSD
    exitUSD
    swipeHarvested
    swipeHarvestedUSD
    block
    slpBalance
    slpAge
    slpAgeRemoved
    slpDeposited
    slpWithdrawn
    userCount
    block
  }
}

```

**History**

Snapshot of the whole MasterChef pools at every event generation time

```graphql
{
  history(id: "0x267748fe0db99863e1d5448ef5b9442230c2478918682") {
    id
    block
    slpBalance
    slpAge
    slpAgeRemoved
    slpDeposited
    slpWithdrawn
    block
  }
}
```

**User**

User reward status in each pools

```graphql
{
  users(where: { address: "0x1d85ddeb7f73c33802d4e2545ee65a579781e0b6" }) {
    id
		address
    amount
    rewardDebt
    entryUSD
    exitUSD
    swipeHarvested
    swipeHarvestedUSD
  }
}
```


# Reference

Swipe Swap References

Swipe Swap Reference provides Smart Contract address, SDK utilities and API


# Smart Contracts

Swipe Swap Smart Contract Address in Ethereum Mainnet, Binance Smart Chain Mainnet and Ethereum Ropsten

## Ethereum Mainnet

| Name               | Address                                    |
| ------------------ | ------------------------------------------ |
| Swipe Swap Factory | 0x8a93B6865C4492fF17252219B87eA6920848EdC0 |
| Swipe Swap Router  | 0xCB0cb2d22C529FdC9F6EFff2ED21086104b21a79 |
| Swipe Swap Farm    | 0x252dD6a11Ef272A438A36d1A2370eEd820099547 |
| SXP-USDT Pair      | 0x1FddF803FAb50935dc5103e706143323Dc9b0635 |
| SXP-WETH Pair      | 0xAd31ff64f5DB3dEF8166DaEce0B3E41d0DCCe76c |
| WBTC-SXP Pair      | 0xc295FB99814Aee1a29A425734FCD131e8a9B687E |
| USDC-WETH Pair     | 0x53B7420C59a4721cE621283f137E2eadFf26Fa3d |
| DAI-WETH Pair      | 0x1bCd6B0E97B51D76FD1752111a1fe2b473F655eE |
| WETH-USDT Pair     | 0x6e7AE922140efed0c7DBc9066B50B9F933Fd755A |

## Binance Smart Chain Mainnet

| Contract Name      | Address                                    |
| ------------------ | ------------------------------------------ |
| Swipe Swap Factory | 0x7810D4B7bC4F7faee9deec3242238a39c4f1197d |
| Swipe Swap Router  | 0x816278BbBCc529f8cdEE8CC72C226fb01def6E6C |
| Swipe Swap Farm    | 0xe6421c0CC2d647be51c11AE952927aB38Dd6f753 |
| SXP-BUSD Pair      | 0xF570d6e751976D0d10aa64ACfa829A5ea4a51727 |
| SXP-WBNB Pair      | 0xB450606703743D557a1c8384Fffe6b941F8f60F4 |
| SXP-BTCB Pair      | 0x70b31Abf9Be826eDc188A15fC35cc6037103a58F |
| USDC-WBNB Pair     | 0x3F97Fa8420d67D2b778C2b3318dd8c59fa0cC2Ec |
| DAI-WBNB Pair      | 0xDAeAB56550ee42bb5B094511bcfCD92844527126 |
| USDT-WBNB Pair     | 0xa14dD52106ABC9fB12Ada0e8D7BDEBe95943F831 |

## Ethereum Ropsten Testnet

| Contract Name      | Address                                    |
| ------------------ | ------------------------------------------ |
| Swipe Swap Factory | 0xc3aBe5dA15d89C3C13CfC4d4Ae4f55B0e408e53e |
| Swipe Swap Router  | 0xe0C80E9c542588969cf5c772E187DeB9C994a1E7 |
| Swipe Swap Farm    | 0x9B8a6f5A3631b144551006B1044737c6Dd538F05 |
| SXP                | 0xd57022d5cb065505093e2c4bbf7d683d2335ab6a |
| USDT               | 0xb421716a0A1feeD58bAC7e0bBad54cb0D37c382E |
| USDC               | 0x005A31b9b305b8e63E3991cfb9943193432ec89B |
| DAI                | 0xA1a38B5E0daD12C4af73C6abfB8B3FD8AD621733 |
| WETH               | 0xc778417E063141139Fce010982780140Aa0cD5Ab |
| WETH/SXP Pair      | 0x45e151e476784f889572252030168E45ec21Fc53 |
| WETH/USDT Pair     | 0xa58d9d47ff70EcD186D0F32e448E4ECF7f0d3Cdd |
| USDT/SXP Pair      | 0xf4fA90F0Bc7e767E283eB79f45CdE7D0E2318F7e |
| USDC/SXP Pair      | 0x9189050D11CB18d576c483BecBaDEa1EFD3CD711 |
| DAI/SXP Pair       | 0x4FCB2c2bc1F911abF6C722F282cc64EC1A4c8aC6 |
| DAI/USDT Pair      | 0x5e03E0c1cD80618A3E0696B577102c7221c458c2 |
| USDC/WETH Pair     | 0x650213faa833B518DE00BAE7239159Fa1239aE2b |
| DAI/WETH Pair      | 0xe9fe018e38723ae72261ab32d3edcddc74934c5e |
| DAI/USDC Pair      | 0x0DE3311df58f5026AE81A8Bbf40A54514E619d62 |
| USDT/USDC Pair     | 0x7032e9857463B51Eb5Bf7dA45B89EC359096e0b2 |


# Introduction

SwipeChain is a decentralised liquidity network built with CosmosSDK.

SwipeChain comes to consensus about events observed on external networks via witness transactions from nodes. Swap and stake logic is then applied to these finalised events. Each event causes a state change in SwipeChain, and some events generate an output transaction which require assets to be moved (outgoing swaps or bond/liquidity withdrawals). These output transactions are then batched, signed by a threshold signature scheme protocol and broadcast back to the respective external network. The final gas fee on the network is then accounted for and the transaction complete.


# Swipe Nodes

The SwipeNode software allows a node to join and service the network, which will run with a minimum of four nodes. The only limitation to the number of nodes that can participate is set by the minimumBondAmount, which is the minimum amount of capital required to join. Nodes are not permissioned; any node that can bond the required amount of capital can be scheduled to churn in.

SwipeChain comes to consensus about events observed on external networks via witness transactions from nodes. Swap and stake logic is then applied to these finalised events. Each event causes a state change in SwipeChain, and some events generate an output transaction which require assets to be moved (outgoing swaps or bond/liquidity withdrawals). These output transactions are then batched, signed by a threshold signature scheme protocol and broadcast back to the respective external network. The final gas fee on the network is then accounted for and the transaction complete.

This is described as a "1-way state peg", where only state enters the system, derived from external networks. There are no pegged tokens or 2-way pegs, because they are not necessary. On-chain Bitcoin can be swapped with on-chain Ethereum in the time it takes to finalise the confirmed event.

All funds in the system are fully accounted for and can be audited. All logic is fully transparent.


# Churn

SwipeChain actively churns its validator set to prevent stagnation and capture, and ensure liveness in signing committees. Churning is also the mechanism by which the SwipeNode software can safely facilitate non-contentious upgrades.

Every 50000 blocks (3 days) SwipeChain will schedule the oldest and the most unreliable node to leave, and rotate in two new nodes. The next two nodes chosen are simply the nodes with the highest bond.

During a churn event the following happens:

* The incoming nodes participate in a TSS key-generation event to create new Asgard vault addresses
* When successful, the new vault is tested with a on-chain challenge-response.&#x20;
* If successful, the vaults are rolled forward, moving all assets from the old vault to the new vault.&#x20;
* The outgoing nodes are refunded their bond and removed from the system.&#x20;


# Bitfrost

The Bifröst faciliates connections with external networks, such as Binance Chain, Ethereum and Bitcoin. The Bifröst is generally well-abstracted, needing only minor changes between different chains. The Bifröst handles observations of incoming transactions, which are passed into SwipeChain via special witness transactions. The Bifröst also handles multi-party computation to sign outgoing transactions via a Genarro-Goldfeder TSS scheme. Only 2/3rds of nodes are required to be in each signing ceremony on a first-come-first-serve basis, and there is no log of who is present. In this way, each node maintains plausible deniabilty around involvement with every transaction.

To add a new chain, adapt one of the existing modules to the new chain, and submit a merge request to be tested and validated. Once merged, new nodes can start signalling support for the new chain. Once a super-majority (67%) of nodes support the new chain it will be added to the network.

To remove a chain, nodes can stop witnessing it. If a super-majority of nodes do not promptly follow suit, the non-witnessing nodes will attract penalties during the time they do not witness it. If a super-majority of nodes stop witnessing a chain it will invoke a chain-specific Ragnörok, where all funds attributed to that chain will be returned and the chain delisted.


# Transactions

The SwipeChain facilitates the following transactions, which are made on external networks and replayed into the SwipeChain via witness transactions:

* **STAKE**: Anyone can stake assets in pools. If the asset hasn't been seen before, a new pool is created.&#x20;
* **WITHDRAW**: Anyone who is staking can withdraw their claim on the pool.
* **SWAP**: Anyone can send in assets and swap to another, including sending to a destination address, and including optional price protection.&#x20;
* **BOND**: Anyone can bond assets and attempt to become a Node. Bonds must be greater than the `minimumBondAmount`, else they will be refunded.&#x20;
* **LEAVE**: Nodes can voluntarily leave the system and their bond and rewards will be paid out. Leaving takes 6 hours.&#x20;
* **RESERVE**: Anyone can add assets to the Protocol Reserve, which pays out to Nodes and Stakers. 220,447,472 SXP will be funded in this way.&#x20;


# Continuous Liquidity Pools

The algorithm for processing assets swaps is given by: `y = (x * Y * X) / (x + X)^2`, where `x = input, X = Input Asset, Y = Output Asset, y = output`

The fee paid by the trader is given by: `fee = ( x^2 * Y ) / ( x + X )^2`

The slip-based fee model has the following benefits:

* Resistant to manipulation
* A proxy for demand of liquidity
* Asymptotes to zero over time, ensuring pool prices match reference prices
* Prevents Impermanent Loss to liquidity providers

**Staking** The stake units awarded to a liquidity provider is given by: `stakeUnits = ((R + T) * (r * T + R * t))/(4 * R * T)`, where `r = SXP Staked, R = SXP Balance, T = Token Balance, t = Token Staked`

This allows them to stake asymmetrically since it has no opinion on price.


# Incentivizes

The system is safest and most capital-efficient when 67% of SXP is bonded and 33% is staked in pools. At this point, nodes will be paid 67% of the System Income, and liquidity providers will be paid 33% of the income. The Sytem Income is the block rewards (`blockReward = totalReserve / 6 / 6311390`) plus the liquidity fees collected in that block.

An Incentive Pendulum ensures that liquidity providers receive 100% of the income when 0% is staked (inefficent), and 0% of the income when `totalStaked >= totalBonded` (unsafe). The Total Reserve accumulates the `transactionFee`, which pays for outgoing gas fees and stabilises long-term value accrual.


# Governance

There is strictly minimal goverance possible through SwipeNode software. Each SwipeNode can only generate valid blocks that is fully-compliant with the binary run by the super-majority.

The best way to apply changes to the system is to submit a SwipeChain Improvement Proposal (TIP) for testing, validation and discussion among the SwipeChain developer community. If the change is beneficial to the network, it can be merged into the binary. New nodes may opt to run this updated binary, signalling via a `semver` versioning scheme. Once the super-majority are on the same binary, the system will update automatically. Schema and logic changes can be applied via this approach.

Changes to the Bifröst may not need coordination, as long as the changes don't impact SwipeChain schema or logic, such as adding new chains.

Emergency changes to the protocol may be difficult to coordinate, since there is no ability to communicate with any of the nodes. The best way to handle an emergency is to invoke Ragnarök, simply by leaving the system. When the system falls below 4 nodes all funds are paid out and the system can be shut-down.


# Run SwipeChain

Guide to set up SwipeChain Node on source code and script.

Ensure you have a recent version of go (ie `1.15`) and enabled go modules And have `GOBIN` in your `PATH`

```
export GOBIN=$GOPATH/bin
```

#### Automated Install Locally

Install via this `make` command.

```bash
make install
```

Once you've installed `swipecli` and `swiped`, check that they are there {GOBIN} folder swipecli and swiped generated.

```bash
swipecli help
swiped help
```

#### Start Standalone Full Stack

For development and running a full chain locally (your own separate network), use the following `make` command.

```bash
make -C build/docker reset-mocknet-standalone
```

#### Format code

```bash
make format
```

#### Build all

```bash
make all
```

#### Test

Run tests

```bash
make test
# test with NATIVE SXP
NATIVE=true make test
```

To run test live when you change a file, use...

```
go get -u github.com/mitranim/gow
make test-watch
```


# Build on Source Code

Download SwipeNode source code from Github

```bash
sudo apt-get update
sudo apt-get -y upgrade
sudo apt install -y curl vim git build-essential jq

wget https://dl.google.com/go/go1.15.5.linux-amd64.tar.gz
tar -xvf go1.15.5.linux-amd64.tar.gz
mv go /usr/local
rm go1.15.5.linux-amd64.tar.gz # cleanup

export GOROOT=/usr/local/go
export GOPATH=~/go
export GOBIN=$GOPATH/bin
export PATH=$GOBIN:$GOROOT/bin:$PATH

git clone https://github.com/SwipeWallet/swipechain-node.git

cd swipechain-node
make install tools
```

Ensure you have a recent version of go (ie `1.15`) and enabled go modules And have `GOBIN` in your `PATH`

```
export GOBIN=$GOPATH/bin
```

#### Automated Install Locally

Install via this `make` command.

```bash
make install
```

Once you've installed `swipecli` and `swiped`, check that they are there {GOBIN} folder swipecli and swiped generated.

```bash
swipecli help
swiped help
```

#### Start Standalone Full Stack

For development and running a full chain locally (your own separate network), use the following `make` command.

```bash
make -C build/docker reset-mocknet-standalone
```

#### Format code

```bash
make format
```

#### Build all

```bash
make all
```

#### Test

Run tests

```bash
make test
# test with NATIVE SXP
NATIVE=true make test
```

To run test live when you change a file, use...

```
go get -u github.com/mitranim/gow
make test-watch
```


# Build with Script

Guide to set up SwipeChain Node with shell script on Ubuntu.

## Ubuntu Installation

This repo contains a script to install SwipeNode

```bash
wget https://github.com/SwipeWallet/swipechain-node/build/linux/ubuntu/swipenode.bash
sudo chmod u+x swipenode.bash
./swipenode.bash
```

Once this runs and thornode is installed, you'll need to configure it.

```bash
PEER=<SEED IP ADDRESS> ../../scripts/validator.sh
```

For more documentation, read...

```bash
../../../docs/validator.md
```


# Developers

Developers community instructions for SwipeChain Development

#### Read Only Applications

Dashboards, explorers etc

1. Connect to Midgard to get rich data about the system, included time-series graphs and aggregated values like TotalVolume etc.&#x20;
2. Connect to SwipeNode (or proxied via Midgard) to drill into the state-machine and access the current state (or historical just by adding a `?height=1234` to specify a certain height.&#x20;
3. Connect to RPC to get information about the Ledger, which is not specific to SwipeChain, such as `/genesis` or account/transaction information

#### Write Applications

Wallets, interfaces etc.

These applications require first-principle thinking and excellent understanding of how the system works.

1. Connect to a trusted SwipeNode or connect to several public SwipeNodes and ensure they all agree
2. Get the `/inbound_addresses`
3. Compose the transaction with the correct memo and correct gas price.&#x20;
4. Send the vault the transaction and wait for execution

**Connecting**

First, you need to connect to SwipeChain. You can use the official clients which have SSL, or run your own node, host it on SSL.

{% hint style="info" %}
If you don't need SSL, you can connect to any of the non-SSL public nodes (ie, just their IP address). Web applications need SSL, but mobile and desktop apps don't.
{% endhint %}


# How to contribute

* Create an issue or find an existing issue on <https://github.com/SwipeWallet/swipechain-node/issues>
* Assign the issue to yourself
* Create a branch using the issue id, for example if the issue you are working on is 600, then create a branch call `600-issue` , this way , github will link your PR with the issue
* Raise a PR , and submit it for the team to review
* Make sure the pipeline is green
* Once PR get approved, you can merge it to master

#### the semantic version and release

SwipeNode manage changelog entry the same way like github, refer to (<https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/creating-a-pull-request-template-for-your-repository>) for more detail. Once a merge request get merged into master branch, if the merge request upgrade the [version](https://github.com/SwipeWallet/swipechain-node/-/blob/master/version), then a new release will be created automatically, and the repository will be tagged with the new version by the release tool.

#### How to generate a changelog entry

A scripts/changelog is available to generate the changelog entry file automatically.

Its simplest usage is to provide the value for title:

```
./scripts/changelog "my super amazing change"
```

At this point the script would ask you to select the category of the change (mapped to the type field in the entry):

```bash
>> Please specify the category of your change:
1. New feature
2. Bug fix
3. Feature change
4. New deprecation
5. Feature removal
6. Security fix
7. Performance improvement
8. Other
```

The entry filename is based on the name of the current Git branch. If you run the command above on a branch called feature/hey-dz, it will generate a changelogs/unreleased/feature-hey-dz.yml file.

The command will output the path of the generated file and its contents:

```
create changelogs/unreleased/my-feature.yml
---
title: Hey DZ, I added a feature to GitLab!
merge_request:
author:
type:
```

**Arguments**

| Argument        | Shorthand | Purpose                                                                                                                 |
| --------------- | --------- | ----------------------------------------------------------------------------------------------------------------------- |
| --amend         |           | Amend the previous commit                                                                                               |
| --force         | -f        | Overwrite an existing entry                                                                                             |
| --merge-request | -m        | Set merge request ID                                                                                                    |
| --dry-run       | -n        | Don’t actually write anything, just print                                                                               |
| --git-username  | -u        | Use Git user.name configuration as the author                                                                           |
| --type          | -t        | The category of the change, valid options are: added, fixed, changed, deprecated, removed, security, performance, other |
| --help          | -h        | Print help message                                                                                                      |

**--amend**

You can pass the --amend argument to automatically stage the generated file and amend it to the previous commit.

If you use --amend and don’t provide a title, it will automatically use the “subject” of the previous commit, which is the first line of the commit message:

```
$ git show --oneline
ab88683 Added an awesome new feature to GitLab

$ scripts/changelog --amend
create changelogs/unreleased/feature-hey-dz.yml
---
title: Added an awesome new feature to GitLab
merge_request:
author:
type:
```

**--force or -f**

Use --force or -f to overwrite an existing changelog entry if it already exists.

```
$ scripts/changelog 'Hey DZ, I added a feature to GitLab!'
error changelogs/unreleased/feature-hey-dz.yml already exists! Use `--force` to overwrite.

$ scripts/changelog 'Hey DZ, I added a feature to GitLab!' --force
create changelogs/unreleased/feature-hey-dz.yml
---
title: Hey DZ, I added a feature to GitLab!
merge_request: 1983
author:
type:
```

**--merge-request or -m**

Use the --merge-request or -m argument to provide the merge\_request value:

```
$ scripts/changelog 'Hey DZ, I added a feature to GitLab!' -m 1983
create changelogs/unreleased/feature-hey-dz.yml
---
title: Hey DZ, I added a feature to GitLab!
merge_request: 1983
author:
type:
```

**--dry-run or -n**

Use the --dry-run or -n argument to prevent actually writing or committing anything:

```
$ scripts/changelog --amend --dry-run
create changelogs/unreleased/feature-hey-dz.yml
---
title: Added an awesome new feature to GitLab
merge_request:
author:
type:

$ ls changelogs/unreleased/
```

**--git-username or -u**

Use the --git-username or -u argument to automatically fill in the author value with your configured Git user.name value:

```
$ git config user.name
Jane Doe

$ scripts/changelog -u 'Hey DZ, I added a feature to GitLab!'
create changelogs/unreleased/feature-hey-dz.yml
---
title: Hey DZ, I added a feature to GitLab!
merge_request:
author: Jane Doe
type:
```

**--type or -t**

Use the --type or -t argument to provide the type value:

```
$ bin/changelog 'Hey DZ, I added a feature to GitLab!' -t added
create changelogs/unreleased/feature-hey-dz.yml
---
title: Hey DZ, I added a feature to GitLab!
merge_request:
author:
type: added
```


# Connecting to SwipeNode

The active node IP addresses can be queried from this endpoint:

{% tabs %}
{% tab title="TESTNET" %}
Seed1 - 3.9.252.243

* RPC - <http://3.9.252.243:26657/>
* Genesis - <http://3.9.252.243:26657/genesis>
* Rest API - <http://3.9.252.243:1317/>

Seed2 - 3.11.165.158

* RPC - <http://3.9.252.243:26657/>
* Genesis - <http://3.9.252.243:26657/genesis>
* Rest API - <http://3.9.252.243:1317/>

{% endtab %}
{% endtabs %}

The Network Information comes from three sources:

1. **MIDGARD**: Consumer information relating to swaps, pools, volume. DeFi dashboards, Wallets, Exchanges will primarily interact with Midgard.&#x20;
2. **SwipeNODE**: Raw blockchain data relating to the SwipeChain state machine. SwipeChain block explorers will query SwipeChain-specific information here.&#x20;
3. **TENDERMINT**: Tendermint standard data, used by all block explorers to query for base information.&#x20;

Midgard returns time-series information regarding the SwipeChain network, such as volume, pool information, users, liquidity providers and more.

**Any Node**

Port: `8080`

RPC Guide:\
http\://\<host>:8080/v2/doc

**Official**

SwipeNode returns application-specific information regarding the SwipeChain state machine, such as balances, transactions and more.

**Any Node**

Port: `1317`

**Official**

RPC allows base blockchain information to be returned.

**Any Node**

TESTNET Port: `26657`

MAINNET Port: `Coming Soon`

RPC Guide:\
<https://v1.cosmos.network/rpc/v0.41.4>

**Official**

MAINNET: Coming Soon

TESTNET: <http://3.9.252.243:26657/genesis>

### **P2P**

P2P is the network layer between nodes, useful for network debugging.

TESTNET Port: `26656`

MAINNET Port: `Coming Soon`


# Staking Details

See how to stake and bond SXP.

To bond SXP to the Swipe Network smart contracts users can do it in the following ways:

* Directly Interacting with the ABI (See how to do this via MyEtherWallet.com or Etherscan.io)
* MetaMask and [app.swipe.org ](https://app.swipe.org)
* Trust Wallet and [app.swipe.org](https://app.swipe.org)

We will explain with a step by step guide on the next few pages how to use each method to stake.<br>


# Swipe Network

Swipe Network processes cryptocurrency to fiat conversions on-demand through various components that enable these flows to work asynchronously with merchant payment networks.

Swipe Network enables users to participate in securing the payment network by bonding and collateralizing `SXP` to the blockchain.&#x20;

Swipe enables consumers and companies to deposit cryptocurrency, which is held via a custodial wallet, that can be converted to fiat currencies for the merchants initiating the transactions directly at point-of-sale. Swipe achieves this by guaranteeing the merchant the fiat currency that they are charging while converting the users cryptocurrencies via the Swipe Network. Swipe guarantees these payments from its own reserves of `SXP` as a collateral that is staked off-chain at the moment to ensure that the merchant receives the amount they are charging. This process is 100% guaranteed as Swipe is in possession of the collateral necessary prior to the transaction and doesn't rely on on-chain confirmations to process the exchange rate.&#x20;

Users are now able to participate in this collateralizing by supplying `SXP` to the Swipe Network  Ethereum Smart Contract while remaining in full control of their funds at all times through the interactions directly on-chain. Users whom stake `SXP` will receive their proportional rewards from the daily `SXP` allocation for bonding and securing the network.&#x20;


# SXP Bonding

SXP token bonded to the Swipe Network provides collaterized security.

Swipe Token holders are able to bond their `SXP` to the main network at any time by calling the Swipe staking smart contract or using the decentralized application user interface.&#x20;

There is a `1,000 SXP` minimum staking requirement to participate in the protocol.&#x20;


# Unbond SXP

Unbonding SXP from the Swipe Network removes your collateral from the protocol and removes any future SXP rewards until re-bonding occurs.

Swipe Token holders are able to unbond their `SXP` to the main network at any time by calling the Swipe staking smart contract or using the decentralized application user interface.&#x20;

Currently there is a 3 day time period requires to unstake `SXP`


# Metamask

Learn how to stake on the Swipe Network with Metamask.


# Add Swipe Token

See how to add SXP to MetaMask by following the steps instructed below.

Users can utilize the Swipe Network Decentralized Finance App (DeFi DApp) through a Chrome browser and a Metamask chrome extension by following the steps below.

**First - Add the SXP Token Contract**<br>

1. Navigate and click the fox icon to your MetaMask chrome extension<br>

![](/files/-MFlqVSNzEWb2tCpgWpo)

2\. Then when your MetaMask is open click the `Assets` tab, then the `Add Token` button

![](/files/-MFlrycStsJQGAexs2-g)

3\. You will now select `Custom Token` and enter the Swipe Token details in the boxes below:

![](/files/-MFlsxyZBX0KvqmG6OvH)

Token Contract: `0x8ce9137d39326ad0cd6491fb5cc0cba0e089b6a9`\
Token Symbol: `SXP`\
Decimal Positions: `18`&#x20;

4\. Once you are done, press the `Next` button to complete the process to add `SXP` to MetaMask.<br>

![](/files/-MFlvhf4c6Nl_sxHq_H2)


# Deposit SXP

See the instructions below to learn how to deposit SXP to your MetaMask non-custodial wallet.

Users will be able to deposit `SXP` from other wallets and/or exchanges to their MetaMask non-custodial wallet by following the steps below:

1. Get your SXP deposit address (which is the same address as your Metamask `ETH` Address) by clicking the address as shown below:

{% hint style="warning" %}
&#x20;Please note: You must have Ether in your Wallet to properly utilize SXP tokens
{% endhint %}

![](/files/-MFlxjV3Co4LXr_BaeVW)

2\. Now that the SXP deposit address is copied, we will give you an example of how to withdraw `SXP` from Binance.com. You will now login to Binance.com with your credentials and navigate to the Spot Wallet as shown below:

![](/files/-MFlyPiQEWq9Xy-kS7yf)

\
3\. Once you are in the Binance Spot Wallet, you will press `Withdraw` on the SXP asset line as shown below:

![](/files/-MFlyitHEWtgznzGZK1F)

4\. You will now see the withdraw page where you will paste the address you previously copied from step 1, select `ERC20` Transfer Network, and enter the `Amount` you want to withdraw to Meta Mask as shown below:

![](/files/-MFm9MywyIa4iR9wip2j)

5\. Once you have entered the relevant details as identified in Step 4, you will press the `Submit` button to complete your withdrawal (which may follow up with 2FA security prompts if enabled):

![](/files/-MFmA6PcN68g7kOGiQEn)

6\. You will see a Success message as shown below if you have completed your `SXP` Withdrawal properly:<br>

![](/files/-MFmAXrR4rszRrctiBff)

7\. Once the withdrawn `SXP` arrives to your Metamask wallet, you will now see your `SXP` balance reflected with this change as shown below: <br>

![](/files/-MFmBLijMyKh7pkCEjcp)


# Connect MetaMask

See how to connect your MetaMask non-custodial wallet to the Swipe DeFi App.

To start staking your `SXP` tokens, you will need to connect your Metamask wallet to the DeFi Application. With the same browser that you have your Metamask non-custodial wallet (ie: Chrome or Brave) please navigate to [https://app.swipe.org ](<https://app.swipe.org >)and follow the instructions below.

1. Once the Decentralized Finance Application loads on your web browser, you will see a `Connect Wallet` button on the right hand side of the browser which will enable you to connect your Metamask Wallet as shown below:

![](/files/-MFmDMHmAk0cLBfi9fiT)

2\. The Metamask wallet will now pop-up and prompt you to connect the Wallet you want to interact with the dApp as shown below:<br>

![](/files/-MFmG_Seyzbpfm7qbZxz)

3\. You will continue by pressing the `Next` button followed by the `Connect` button as shown below:<br>

![](/files/-MFmHH_NznkZzjY7u9Di)


# Stake SXP

Learn how to stake your SXP to bond and collateralize it with the Swipe Network with your Metamask non-custodial wallet.

Once you have successfully connected your Metamask non-custodial wallet to the Swipe DeFi Application you will now see the main staking page as shown below where you can `Supply` your `SXP` to the protocol.&#x20;

![](/files/-MFmIe3vM6hSFr9b-qBa)

For first time users will first be required to enable Metamask and their Ethereum account to interact with the Swipe Staking Smart Contract. You  start but authorizing your Metamask account to interact with the smart contract by pressing the `Supply` button which will prompt a pop-up displaying your available balance and asking to authorize the smart contract with your account. You will start the process by pressing the `Approve` button as shown below:

![](/files/-MGPK0Zfa4HeCyjZZhWj)

This will now prompt a pop-up from your Metamask to approve the spending of this contract as shown below:

{% hint style="info" %}
Please Note: You will need ETH in this wallet for gas. Without ETH the button will be gray.
{% endhint %}

![](/files/-MGPMuThFPizz23-PXFc)

{% hint style="warning" %}
Please note: Even though you authorize this application with the message above, you will still be required to sign each message (interaction). Without your signature, their can be no additional interactions.&#x20;
{% endhint %}

Once this transaction confirms on-chain, you are now able to proceed with staking by pressing the `Supply` button one more time. This will prompt a pop-up for you to input the amount you want to stake on chain.

![](/files/-MGPOUryG08pM5EznneK)

Once you have entered the amount the `Supply` button will now turn orange and will enable you to press it to continue. This will prompt a pop-up on your Metamask wallet to confirm(sign) this transaction and broadcast it to the network as shown below:

![](/files/-MGPOpTtw6S6TU5K_ss_)

Once this transaction confirms on-chain, your `SXP` balance on the staking side will be updated and you will begin earning your portion of the staking rewards.

![](/files/-MGPPt-2KctLlAiEW6wP)


# Trust Wallet

Learn how to stake on the Swipe Network with Trust Wallet.


# Add Swipe Token

See how to add SXP to Trust Wallet by following the steps instructed below.

Users can utilize the Swipe Network Decentralized Finance App (DeFi DApp) through their Trust Wallet mobile application by following the steps below.

**First add Swipe SXP to Trust Wallet (ERC-20)**

**Op** Open your Trust Wallet app and navigate to the `Wallet` screen by press the first tab bar followed by pressing the `Coin Setting` icon on the top left as highlighted in red below:

![](/files/-MGiktiekle0p2sJ5ALP)

Thereafter you will add the Swipe SXP Token (**ERC-20**) by typing in the words `Swipe` and toggling the token as shown in image as shown below:

![](/files/-MGilc0Z4NTNogLxD5Qi)

You have now enabled Swipe on Trust Wallet and can navigate to the Swipe `SXP` Wallet by tapping the Swipe icon above.&#x20;


# Deposit SXP

See the instructions below to learn how to deposit SXP to your Trust Wallet application.

Users will be able to deposit `SXP` from other wallets and/or exchanges to their MetaMask non-custodial wallet by following the steps below:

1. Get your SXP deposit address (which is the same address as your Trust Wallet `ETH` Address) by clicking the address as shown below:

{% hint style="warning" %}
&#x20;Please note: You must have Ether in your Wallet to properly utilize SXP tokens
{% endhint %}

2\. To fetch your `SXP` Wallet address on Trust Wallet you will need to tap on the `Receive` button as shown below.

![](/files/-MGimSfvgFMZCJxB0ppp)

This will now open a popup where it will display a QR code and your `SXP` Wallet address. You can now copy or scan this address from this popup.&#x20;

2\. Now that the SXP deposit address is copied, we will give you an example of how to withdraw `SXP` from Binance.com. You will now login to Binance.com with your credentials and navigate to the Spot Wallet as shown below:

![](/files/-MFlyPiQEWq9Xy-kS7yf)

\
3\. Once you are in the Binance Spot Wallet, you will press `Withdraw` on the SXP asset line as shown below:

![](/files/-MFlyitHEWtgznzGZK1F)

4\. You will now see the withdraw page where you will paste the address you previously copied from step 1, select `ERC20` Transfer Network, and enter the `Amount` you want to withdraw to Meta Mask as shown below:

![](/files/-MFm9MywyIa4iR9wip2j)

5\. Once you have entered the relevant details as identified in Step 4, you will press the `Submit` button to complete your withdrawal (which may follow up with 2FA security prompts if enabled):

![](/files/-MFmA6PcN68g7kOGiQEn)

6\. You will see a Success message as shown below if you have completed your `SXP` Withdrawal properly:<br>

![](/files/-MFmAXrR4rszRrctiBff)

7\. Once the withdrawn `SXP` arrives to your Trust Wallet wallet, you will now see your `SXP` balance reflected with this deposit <br>


# Connect Trust Wallet

See how to connect your Trust Wallet mobile application to the Swipe DeFi App.

To start staking your `SXP` tokens, you will need to connect your Trust Wallet mobile application to the DeFi Application. Open a new browser tab and please navigate to [https://app.swipe.org ](<https://app.swipe.org >)and follow the instructions below.

1. Once the Decentralized Finance Application loads on your web browser, you will see a `Connect Wallet` button on the right hand side of the browser which will enable you to connect your Trust Wallet via `Wallet Connect` as shown below:

![](/files/-MGirFW2eaDTEO2SY_PK)

2\. Once you press `Wallet Connect` it will display a popup with the `Wallet Connect` QR code which you must scan from the Trust Wallet App as shown below:

![](/files/-MGisHU25ZkV6nmjEmnu)

3\. You will now open your Trust Wallet mobile application and navigate to the settings tab and press `Wallet Connect` as shown below:

![](/files/-MGiseFYP3I3ayuVFEbn)

4\. Once you press `Wallet Connect` it will open up your camera via the Trust Wallet app to scan the QR code. Once scanned a new popup will display on your Trust Wallet app which you must press `Connect` to continue as shown below:

![](/files/-MGitblfdnsTb2TybQ6a)

You will now be connected to the Swipe DeFi App and you will a message in your Trust Wallet app that says `You can go back to your browser.` as show below:

![](/files/-MGiwF_w9j9DAusS3ha_)

And your browser will now display the main staking/dashboard page for the Swipe Network as shown below which means you have successfully connected your Trust Wallet to the Swipe Network DeFi App.

![](/files/-MGiwc4Uj5aWHaMSRaSC)


# Stake SXP

Learn how to stake your SXP to bond and collateralize it with the Swipe Network with your Trust Wallet non-custodial mobile application.

Once you have successfully connected your Trust Wallet mobile application to the Swipe DeFi Application you will now see the main staking page as shown below where you can `Supply` your `SXP` to the protocol.&#x20;

![](/files/-MGix9uZ8H4woQxFM-4Q)

For first time users will first be required to enabling the staking protocol by pressing `Enable Stake`  which will allow your Ethereum account in the Trust Wallet application to interact with the Swipe Staking Smart Contract. Once `Enable Stake` is pressed it will prompt a pop-up displaying your available balance and asking to authorize the smart contract with your account. You will start the process by pressing the `Approve` button as shown below:

![](/files/-MGixmOfeiawrO3pBpXL)

This will now prompt a pop-up from your Trust Wallet to approve the use of this contract as shown below:

{% hint style="info" %}
Please Note: You must have ETH in your wallet in order to continue for on-chain Ethereum gas fees. If you do not have/have sufficient ETH the "Send" button will be grayed out.
{% endhint %}

![](/files/-MGiyeMPWgryrY-PjMnW)

{% hint style="success" %}
Once this transaction confirms on-chain, you are now able to proceed with staking by pressing the `Supply` button one more time. This will prompt a pop-up for you to input the amount you want to stake on chain.
{% endhint %}

![](/files/-MGPOUryG08pM5EznneK)

Once you have entered the amount the `Supply` button will now turn orange and will enable you to press it to continue. This will prompt a pop-up on your Trust Wallet  to confirm(sign) this transaction and broadcast it to the network as shown below:

![](/files/-MGizjOHk2fvqxI06uSA)

Once this transaction confirms on-chain, your `SXP` balance on the staking side will be updated and you will begin earning your portion of the staking rewards.

![](/files/-MGizsN6O6tvyNDJ-FBy)


# Ledger

Learn how to stake on the Swipe Network with a Ledger hardware device and Metamask.


# Connect Ledger

Connect your Ledger hardware wallet with Metamask

Users can utilize the Swipe Network Decentralized Finance App (DeFi DApp) through a Chrome browser and a Metamask chrome extension and their Ledger hardware wallet by following the steps below.

**First - Connect your Ledger hardware wallet to your computer**

1. Plug your Ledger hardware wallet to your your computer via the USB cable which you normally use to connect your Ledger to your Ledger Live application to access your accounts.

**Second - Add the Ledger hardware wallet to Metamask**

1. Navigate and click the fox icon to your MetaMask chrome extension:<br>

![](/files/-MFlqVSNzEWb2tCpgWpo)

2\. Then when your MetaMask is open press the top corner icon as shown below:

![](/files/-MGjmmvdTGpgkLXOR1ZO)

3\. Then you will press `Connect Hardware Wallet` as shown below:

![](/files/-MGjnZYn13vMv5pfN0Sf)

4\. There will be a new tab that opens up from Metamask which will then instruct you to follow the directions on the screen. Select `Ledger` then click `Connect`.

![](/files/-MGjoIUFRMc8znsAfsA0)

5\. Next you will select `Ledger Live` as the the "Select HD Path" followed by selecting your Ethereum wallet account that you want to use for `SXP` staking. Once you select the ETH Wallet that has your `SXP` on it, press `Unlock`

![](/files/-MGjodfPyeYsdrhmIZ3p)

6\. After you press `Unlock` your Ledger hardware wallet is now connected to Metamask and you are ready to continue your staking process.&#x20;


# Add Swipe Token

See how to add SXP to Ledger hardware wallet via Metamask by following the steps instructed below.

Follow the instructions below to add the Swipe Token contract to the Ledger based Metamask wallet.

**First - Add the SXP Token Contract**<br>

1. Navigate and click the fox icon to your MetaMask chrome extension<br>

![](/files/-MFlqVSNzEWb2tCpgWpo)

2\. Then when your MetaMask is open click the `Assets` tab, then the `Add Token` button

![](/files/-MGjqCL4xo65hQ0J3Rl0)

3\. You will now select `Custom Token` and enter the Swipe Token details in the boxes below:

![](/files/-MFlsxyZBX0KvqmG6OvH)

Token Contract: `0x8ce9137d39326ad0cd6491fb5cc0cba0e089b6a9`\
Token Symbol: `SXP`\
Decimal Positions: `18`&#x20;

4\. Once you are done, press the `Next` button to complete the process to add `SXP` to MetaMask.<br>

![](/files/-MFlvhf4c6Nl_sxHq_H2)


# Deposit SXP

See the instructions below to learn how to deposit SXP to your Ledger hardware wallet via Metamask

Users will be able to deposit `SXP` from other wallets and/or exchanges to their Ledger Wallet connected to t by following the steps below:

1. Get your SXP deposit address (which is the same address as your Ledger Live based Metamask `ETH` Address) by clicking the address as shown below:

{% hint style="warning" %}
&#x20;Please note: You must have Ether in your Wallet to properly utilize SXP tokens
{% endhint %}

![](/files/-MGjr0yGGEppCsagFjSZ)

2\. Now that the SXP deposit address is copied, we will give you an example of how to withdraw `SXP` from Binance.com. You will now login to Binance.com with your credentials and navigate to the Spot Wallet as shown below:

![](/files/-MFlyPiQEWq9Xy-kS7yf)

\
3\. Once you are in the Binance Spot Wallet, you will press `Withdraw` on the SXP asset line as shown below:

![](/files/-MFlyitHEWtgznzGZK1F)

4\. You will now see the withdraw page where you will paste the address you previously copied from step 1, select `ERC20` Transfer Network, and enter the `Amount` you want to withdraw to Meta Mask as shown below:

![](/files/-MFm9MywyIa4iR9wip2j)

5\. Once you have entered the relevant details as identified in Step 4, you will press the `Submit` button to complete your withdrawal (which may follow up with 2FA security prompts if enabled):

![](/files/-MFmA6PcN68g7kOGiQEn)

6\. You will see a Success message as shown below if you have completed your `SXP` Withdrawal properly:<br>

![](/files/-MFmAXrR4rszRrctiBff)

7\. Once the withdrawn `SXP` arrives to your Metamask wallet, you will now see your `SXP` balance reflected with this change as shown below: <br>

![](/files/-MGjrB_Yfu81y4LRRVcM)


# Connect to Swipe

See how to connect your Ledger hardware wallet via Metamask to the Swipe DeFi App and to enable contract interactions on the Ledger hardware device.

To start staking your `SXP` tokens, you will need to connect your Ledger hardware wallet via Metamask  to the DeFi Application. With the same browser that you have your Metamask (ie: Chrome or Brave) please navigate to [https://app.swipe.org ](<https://app.swipe.org >)and follow the instructions below.

1. Once the Decentralized Finance Application loads on your web browser, you will see a `Connect Wallet` button on the right hand side of the browser which will enable you to connect your Metamask Wallet as shown below:

![](/files/-MFmDMHmAk0cLBfi9fiT)

2\. The Metamask wallet will now pop-up and prompt you to connect the Ledger Wallet you want to interact with the dApp as shown below:<br>

![](/files/-MGjtovVI-ZD7PTuN_Aj)

3\. You will continue by pressing the `Next` button followed by the `Connect` button as shown below:<br>

![](/files/-MGjtvKm1oSG7NCS8TvI)

4\. Next, you will need to go back to your Ledger hardware wallet and physically enable Contracts by navigating to the `Ethereum` app, then press the right directional button to `Settings` . You will see the first option being `Contract data` which you will notice the last line says `NOT Allowed` .  Once you are here, press both directional buttons at the same time to change the status. If done successfully you will now notice that the `NOT Allowed` text has changed to `Allowed`. Now press the right directional button to to the `<- Back` option and press both keys again. You should now see the message `Application is ready` on your Ledger hardware wallet device.&#x20;


# Stake SXP

Learn how to stake your SXP to bond and collateralize it with the Swipe Network with your Ledger hardware non-custodial wallet via Metamask.

Once you have successfully connected your Ledger hardware wallet via Metamask  to the Swipe DeFi Application, you will now see the main staking page as shown below where you can `Supply` your `SXP` to the protocol. &#x20;

![](/files/-MGjw0o3t9RmpE3WnQIi)

For first time users will first be required to enabling the staking protocol by pressing `Enable Stake`  which will allow your Ethereum account in the Ledger hardware wallet via Metamask to interact with the Swipe Staking Smart Contract. Once `Enable Stake` is pressed it will prompt a pop-up displaying your available balance and asking to authorize the smart contract with your account. You will start the process by pressing the `Approve` button as shown below:

![](/files/-MGixmOfeiawrO3pBpXL)

This will now prompt a pop-up from your Metamask to approve the spending of this contract as shown below:

{% hint style="info" %}
Please Note: You will need ETH in this wallet for gas. Without ETH the button will be gray.
{% endhint %}

![](/files/-MGPMuThFPizz23-PXFc)

{% hint style="warning" %}
Please note: Even though you authorize this application with the message above, you will still be required to sign each message (interaction). Without your signature, their can be no additional interactions.&#x20;
{% endhint %}

You will then be required to go to the Ledger hardware wallet and physically approve the transaction **after** you have pressed the `Confirm` button above. It will ask you to `Review Transaction` which you will press the right directional button to review, until you see the `Accept and Send` prompt which you will then press both directional buttons on the Ledger to broadcast. Once this transaction confirms on-chain, you are now able to proceed with staking by pressing the `Supply` button one more time. This will prompt a pop-up for you to input the amount you want to stake on chain.

![](/files/-MGPOUryG08pM5EznneK)

Once you have entered the amount the `Supply` button will now turn orange and will enable you to press it to continue. This will prompt a pop-up on your Metamask wallet to confirm(sign) this transaction and broadcast it to the network as shown below:

![](/files/-MGPOpTtw6S6TU5K_ss_)

You will then be required to go to the Ledger hardware wallet and physically approve the transaction **after** you have pressed the `Confirm` button above. It will ask you to `Review Transaction` which you will press the right directional button to review, until you see the `Accept and Send` prompt which you will then press both directional buttons on the Ledger to broadcast. Once this transaction confirms on-chain, your `SXP` balance on the staking side will be updated and you will begin earning your portion of the staking rewards.

![](/files/-MGjx8sW17VAM6aPq6SI)


# View your Rewards

Learn how to view tour Swipe Network staking pending rewards.

Users are able to view their pending rewards through the Swipe staking smart contract or front-end UI.&#x20;

![](/files/-MFw3QJr0EVV_KnlaV3E)

{% hint style="warning" %}
Staking rewards are updated at 00:00 UTC daily.&#x20;
{% endhint %}


# Claim Your Rewards

Learn how to claim your Swipe Network Staking Rewards

Users are able to claim their rewards after 7 days in each cycle by pressing `Claim Rewards` on the top right hand corner of the decentralized application as shown below:

![](/files/-MFw4ARAZzZc_a3NjIZU)

Then follow the prompts below to claim your `SXP`&#x20;

![](/files/-MFw44PtIGGJYwh7JFMm)


# Vote

See how to vote on Swipe Governance

Swipe Governance gives the protocols control to `SXP` token holders who will be able to propose improvements and changes and vote on them .&#x20;

{% hint style="warning" %}
Users can only access Swipe Governance with SXP that they have staked on the protocol. Unstaked SXP does not qualify for Swipe Governance votes or proposals.
{% endhint %}

Once you are in the `Vote` Dashboard you will see the voting dashboard as shown below:

![](/files/-MIPHJSm9w6R3-j_p0jy)

Under the `Votes` box you will see the amount you have staked which will correlate to your `Voting Weight`.&#x20;


# Proposals

Learn how to create a proposal on Swipe Governance

Users who have the requires `SXP` staked on the Swipe Network or proper amount of `SXP` delegated to their address have the ability to create `Swipe Improvement Proposals` (SIPs)

To view the Governance main dashboard where you can click the `Dashboard` menu item as shown below which is where you may begin the process to `Create Proposals`.

![](/files/-MISAtI82OpUdmtbr95-)

Once you have entered the Governance `Dashboard` screen you can start a new proposal if you have enough `SXP` to create one either through units staked or units delegated from other stakers. To start press `Create Proposal` as shown below:

![](/files/-MISC8Nvg1xwaaaWVgS0)

You will now see a proposal popup which you can use the interface to fill in the address and signatures required for the changes as shown below:&#x20;

![](/files/-MISCz4rKr8R2wMJCsTs)

{% hint style="warning" %}
Please note: The Swipe Improvement Proposal can have up to 10 actions (based on proposalMaxOperations()). The proposer cannot create another proposal if they currently have a pending or active proposal. It is not possible to queue two identical actions in the same block (due to a restriction in the Timelock), therefore actions in a single proposal must be unique, and unique proposals that share an identical action must be queued in different blocks.
{% endhint %}

## Please see the details below if you are using the smart contracts directly

**Governor**&#x20;

```
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) returns (uint)
```

* `targets`: The ordered list of target addresses for calls to be made during proposal execution. This array must be the same length as all other array parameters in this function.
* `values`: The ordered list of values (i.e. msg.value) to be passed to the calls made during proposal execution. This array must be the same length as all other array parameters in this function.
* `signatures`: The ordered list of function signatures to be passed during execution. This array must be the same length as all other array parameters in this function.
* `calldatas`: The ordered list of data to be passed to each individual function call during proposal execution. This array must be the same length as all other array parameters in this function.
* `description`: A human readable description of the proposal and the changes it will enact.
* `RETURN`: The ID of the newly created proposal.


# Frequently Asked Questions

See some of the most frequently asked questions for Swipe Network below.

## What is the minimum number of SXP required for staking?

Currently the protocol is set to 1,000 `SXP` required for staking.

## How long are my tokens locked for?

Currently there is a 3 day stake period on any new `SXP` staked. This means you must wait 3 days from the time you staked any `SXP` to unstake/unbond and withdraw it.&#x20;

**MORE COMING SOON.**


