# Geminon Protocol

A fourth generation stablecoins protocol.

{% hint style="info" %}
Geminon protocol is deprecated. All smart contracts have been paused and the collateral has been moved into vaults. GEX holders can redeem their tokens against the native coin of the blockchain where they are held at constant price. The team is working on the development of Geminon v2. Check <https://geminonprotocol.medium.com/> for more info.
{% endhint %}

### What is Geminon?

Geminon is a multi-chain stablecoin protocol. It is currently deployed on the Ethereum, BNB Chain and Avalanche networks. It allows users to mint, trade and redeem both deflationary currencies linked to the CPI of different countries as well as stablecoins linked to a wide range of fiat currencies. The first version of the protocol includes various DeFi services associated with stablecoins, such as a zero slippage Foreign Decentralized Exchange (ForDEX), lending and borrowing of crypto assets and stablecoins, and also a multi-chain bridge. Geminon's stablecoin protocol has a unique design that combines collateralization with an algorithmic middle layer that buffers collateral volatility. This novel design combines the advantages of algorithmic and collateralized stablecoins while eliminating or reducing their drawbacks.

### How does it work?

Geminon has 4 main modules:&#x20;

#### Genesis Liquidity Pools (GLP)&#x20;

GLPs are the main entry point to the Geminon protocol. They allow users to obtain GEX tokens in exchange for depositing other crypto assets as collateral. To learn more about which assets are accepted as collateral and how GLP works in detail, visit the following sections:

{% content-ref url="/pages/kDjc63cl5B7Oxa3JPkhL" %}
[Collateral](/geminon-protocol/collateral)
{% endcontent-ref %}

{% content-ref url="/pages/3JHqVL3XWHWk1hqwUb08" %}
[Genesis Liquidity Pools](/modules/genesis-liquidity-pools)
{% endcontent-ref %}

#### Stable Coin Minter (SC Minter)&#x20;

It is the main access point to the Geminon stablecoins. It is an algorithmic module that allows GEX tokens to be exchanged for stablecoins at their exact peg price and vice versa.

{% content-ref url="/pages/BzWQuGCDOtWxsoDeItq6" %}
[Stablecoins Minter](/modules/stablecoins-minter)
{% endcontent-ref %}

#### Stablecoin Exchange (StableSwap)&#x20;

It allows you to directly trade any stablecoin or inflation-indexed pair of the Geminon protocol without slippage.

{% content-ref url="/pages/fcYyj0JPiZHaeTQjTha8" %}
[Decentralized Forex](/modules/decentralized-forex)
{% endcontent-ref %}

#### Lending / borrowing

Using this module users can deposit crypto assets to earn interest or borrow them by depositing collateral and paying interest. This module is currently under development.

{% content-ref url="/pages/cgzrfNyUGwHZiqxWh3K8" %}
[Lending / borrowing](/modules/lending-borrowing)
{% endcontent-ref %}


# Introduction

{% hint style="info" %}
Geminon protocol is deprecated. All smart contracts have been paused and the collateral has been moved into vaults. GEX holders can redeem their tokens against the native coin of the blockchain where they are held at constant price. The team is working on the development of Geminon v2. Check <https://geminonprotocol.medium.com/> for more info.
{% endhint %}

## Introduction

Bitcoin was designed in 2008 as an electronic payment system to allow people to transact directly with each other without the need for a trusted third party, i.e., a decentralized money for the internet.&#x20;

The economic design of Bitcoin with a fixed supply makes it a good store of value for the long term. However, this inelastic supply causes its price to be extremely volatile in the short term, making its use as a currency inappropriate. This has led to the creation of so-called stablecoins, designed to maintain a peg with some fiat currency, the most common being the US Dollar.

### Stablecoin types

The first attempts to create stablecoins date back to 2012 (Mastercoin). Tether, the largest stablecoin issuer today, was created in 2014. The number of stablecoins in existence nowadays is counted by tens.

In recent years, various taxonomies have been proposed based on the type of collateral used, peg target, and technological mechanism. Without being too strict on the classification, it is commonly accepted that there are three main types of stablecoin:

* **Centralized**: The common characteristics shared by all the currencies of this group is that they are issued by a traditional company which keeps reserves, in fiat currency and other assets of equivalent liquidity (such as treasury bills), for a value equal to or greater than the face value of the stablecoins issued, and that all are **censurable**, that is, they incorporate blacklist functions in their smart contracts that allow the issuer to seize the assets of any user at will. Examples of this type are Tether's USDT, Circle's USDC and Paxos' BUSD.&#x20;
* **Algorithmic**: Under this category are those protocols that do not use any source of value external to the protocol itself to maintain the peg of their stablecoin, which is why from a more formal perspective they are called ***endogenous collateral*** stablecoins, in the event that they use a system of ***seigniorage shares***, or ***implicit collateral*** stablecoins, if they use a ***rebase*** or ***bonding*** system. Examples of this type of stablecoins can be found in Ampleforth (AMPL), Neutrino (USDN), Haven (xUSD), Beanstalk (BEAN) and the infamous Terra UST.&#x20;
* **Collateralized**: This category includes all stablecoins that use external sources of value as collateral. These sources can be stable (usually other centralized stablecoins), floating (other cryptoassets) or mixed, and depending on the proportion of value required to mint them, they can be **overcollateralized** or **fairly collateralized**. Some are issued in the form of **debt**, whereby the issuer pays interest to the protocol for the minted currency. The best known examples of this category are Maker's DAI, FRAX, Liquity (LUSD), Magic Internet Money (MIM) and FEI.&#x20;

It is important to note that, in a broad sense, all stablecoins are collateralized, as they all need a source of value to maintain a stable price. The only real difference between them therefore lies in **the nature of that source of value**.

### The source of the Geminon stablecoins value

If the previous classification is taken strictly, the Geminon protocol would fall into the category of algorithmic, since its stablecoins are minted only from an internal asset, the GEX token. However, this would be inaccurate as the GEX token is not the actual source of value in the protocol.

The reason is that the GEX token acts as a proxy for the true source of value in the system, which is the collateral deposited in the GLPs. This setting is necessary as it would not otherwise be possible to use floating collateral for stablecoins without heavily overcollateralizing the protocol to absorb its volatility.

There is currently no other protocol that uses this stability mechanism for stablecoins, despite the fact that it combines the advantages of algorithmic and collateralized systems, eliminating or reducing their drawbacks:

* It provides GEX token holders with direct exposure to stablecoin issuance, which is the primary advantage of algorithmic protocols based on seigniorage shares.
* It has unlimited scalability. The lack of scalability is the main problem posed by overcollateralized stablecoins.
* It is more decentralized than most collateralized or over-collateralized stablecoins, as it has less need to include off-blockchain assets to hold the price anchor.
* It is able to hold the peg in any market condition as effectively as centralized stablecoins, avoiding the risk of a "death spiral" of algorithmic stablecoins.

The system proposed by the Geminon protocol therefore has a better balance between decentralization, security and scalability than any other existing stablecoin.

Some might argue that the proposed scheme is directly equivalent to the straight use of collateral for stablecoin issuance, and therefore the system would collapse the moment the total capitalization of the collateral is less than that of the issued stablecoins, making the value of the GEX token and therefore of the stablecoins issued against it fall to near zero, as happened with Terra UST.

All the simulations carried out of the long-term behavior of the protocol, however, contradict this theory: for all the stationary configurations with random trades in which the entire supply of GEX tokens is returned to the GLPs cyclically, the final price of the token after 1 million trades is always higher than the initial one by at least one order of magnitude. This effect can not be due to the fees, since the amount of residual collateral in the pools is also higher and deactivating them shows the same results. Such observed behavior would not be possible unless another source of value existed in the protocol other than collateral.

### Genesis Liquidity Pools as a source of value

GLPs constitute an algorithmic mechanism of implicit collateralization.

In all existing trading systems, whether it is a stock or futures broker, a cryptocurrency exchange or a decentralized exchange (DEX), every time a trade is made there is an impact on the price, called slippage. We can think of this slippage as the entropy created by the action of trading, and it is a loss that the trader suffers in favor of the market maker that gives him counterparty. In the case of a DEX liquidity pool, that market maker is the liquidity provider.

In Geminon's GLPs, however, there are no liquidity providers. Instead, it is the GLP itself that **generates** new **liquidity** every time someone adds collateral (hence the name Genesis Liquidity). This means that all the value that is usually captured by those liquidity providers (the entropy) is instead retained within the GLP and reflected in the long-term value of the GEX token. And this is what all the simulations of the protocol show: the more the GEX token is traded in a GLP, the higher its terminal value, regardless of the direction of the trades.

GLPs are a form of liquidity bootstrapping pools (LBP), and can also be viewed as entropy capturing machines (ECM). They are the key piece in the operation of the Geminon protocol, and very especially in its value generation system. You can read more in detail about them in the dedicated chapter.

{% content-ref url="/pages/3JHqVL3XWHWk1hqwUb08" %}
[Genesis Liquidity Pools](/modules/genesis-liquidity-pools)
{% endcontent-ref %}


# Collateral

GEX token is fully collateralized with gold, Bitcoin, Ethereum, BNB and AVAX. We have selected Paxos Gold and Tether Gold as providers for the tokenized gold, Ren Bitcoin for the wrapped version of Bitcoin in Ethereum and BSC, and Bitcoin Avalanche Bridged on Avalanche network. The weight and address of each collateral token is:

### Ethereum network (60%)

* 20% Pax Gold (PAXG): 0x45804880De22913dAFE09f4980848ECE6EcbAf78
* 20% Tether Gold (XAUT): 0x68749665FF8D2d112Fa859AA293F07A622782F38
* 10% Ren Bitcoin (RENBTC): 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D <mark style="color:red;">(deprecated)</mark>
* 10% Ethereum (ETH)

### BNB Smart Chain (20%)

* 10% Ren Bitcoin (RENBTC): 0xfCe146bF3146100cfe5dB4129cf6C82b0eF4Ad8c <mark style="color:red;">(deprecated)</mark>
* 10% BNB (BNB)

### Avalanche (20%)

* 10% Bitcoin Avalanche Bridged (BTC.B): 0x152b9d0FdC40C096757F570A51E494bd4b943E50&#x20;
* 10% Avalanche (AVAX)

{% hint style="warning" %}
Due to the fall of the REN protocol in December 2022, the Ren BTC pools on the Ethereum and BNB Chain networks have been decommissioned and the corresponding collateral transferred to other pools, so the only active BTC pool is on the Avalanche network.
{% endhint %}


# Deployment addresses

Geminon is a native multichain protocol, which means that all of its smart contracts and functionalities are available on multiple blockchains simultaneously.

The protocol has been initially deployed on Ethereum, BSC and Avalanche. The deployment has been done in such a way that the addresses of each token and modules match in all chains whenever possible. The only exception is the Pax Gold and Tether Gold Genesis Liquidity Pools, which are only available in the Ethereum network.

The code of all smart contracts listed here is public and verified.

### Deployer (owner)

The deployer of the smart contracts is the owner and therefore is the only address that can use certain functions in the contracts, some of which are critical for the safety of the protocol. See the section of safety tips for more information about this.

* 0x88d70DEBB940E0bEE526981D99B0f3000E0a3268

{% content-ref url="/pages/KJKIscdpScpUCvb0BTVR" %}
[Safety tips](/safety-tips)
{% endcontent-ref %}


# Tokens

### GEX token

The address of the Geminon token is the same on Ethereum, BSC and Avalanche:

* 0x2743Bb6962fb1D7d13C056476F3Bc331D7C3E112

## Inflation indexed stablecoins

### USDI

US dollar indexed to inflation

* 0x4C24e67DC2a00AdA5E90C1E284d2EE4260A21E05

Index beacon: contract that calculates the reference value of the inflation index

* 0x31ac1cc4f770501AdE10E252A6AE27F36D4469Fa

### EURI

Euro indexed to inflation in the Eurozone

* 0xcbB00E1f27a59735f390F3263d335A112f10Db8b

Index beacon: contract that calculates the reference value of the inflation index

* 0x842b95dc806745a2B1e0C99a39e0BcF60eC7Ecc2

## Stablecoins

### USDG

Geminon US Dollar

* 0x825B116b431c441C8f5eC19abC069adbd0a169cF

### EURG

Geminon Euro

* 0x38f8058b4dF45E8451d10f40343DBAaeCAE620cF

### CNYG

Geminon Chinese Renminbi Yuan

* 0x52644C661Bd2436C0a620Cf11b617276b8c7C2D1

### JPYG

Geminon Japanese Yen

* 0x9eCA773DE915a76D5aD25D3995F10dd5532022b2


# Modules

## Genesis Liquidity Pools

The address of the native asset and bitcoin pool on each network is the same. PAXG and XAUT pools are unique on Ethereum.

#### Ethereum

* ETH-GEX pool: 0xA4df7a003303552AcDdF550A0A65818c4A218315 <mark style="color:red;">(deprecated)</mark>
* RENBTC-GEX pool: 0x5ae76CbAedf4E0F710C2b429890B4cCC0737104D <mark style="color:red;">(deprecated)</mark>
* PAXG-GEX pool: 0x48A814C44beeFE3A1C7c165367c1Ea12eA599b48 <mark style="color:red;">(deprecated)</mark>
* XAUT-GEX pool: 0xE7e708277A03dA75186C231b5B43FcFB34BEd29B <mark style="color:red;">(deprecated)</mark>

#### BNB Smart Chain

* BNB-GEX pool: 0xA4df7a003303552AcDdF550A0A65818c4A218315 <mark style="color:red;">(deprecated)</mark>
* RENBTC-GEX pool: 0x5ae76CbAedf4E0F710C2b429890B4cCC0737104D <mark style="color:red;">(deprecated)</mark>

#### Avalanche

* AVAX-GEX pool: 0xA4df7a003303552AcDdF550A0A65818c4A218315 <mark style="color:red;">(deprecated)</mark>
* BTC.B-GEX pool: 0x5ae76CbAedf4E0F710C2b429890B4cCC0737104D <mark style="color:red;">(deprecated)</mark>

## Stablecoin minter

The minter address is the same in all networks.

* 0xeF0dfe8cF872B4dF3681Ad37A17Ef5e2D473B877 <mark style="color:red;">(deprecated)</mark>

## Oracle

The oracle address is the same on all networks. First version (deprecated):

* 0x2208C74e717df65E367A7dB03B8675627D31ac31 <mark style="color:red;">(deprecated)</mark>

Second version (currently in use):

* 0xa7d3d2bAd28fd928b72283E8a96f6E8D5c5D94e2 <mark style="color:red;">(deprecated)</mark>

## Multichain bridge

The bridge address is the same on all networks. First version (in testing, not open to the public):

* 0xC783565D32517DCC80d0aAA44580ef92dAd224e3 <mark style="color:red;">(deprecated)</mark>

### GEX Vault

The vault address is the same on all networks.

* 0x4606887be86edF5bD47eEEAa0851864d9A70B07B


# About

These are the long-term drivers of Geminon. Achieving these goals will likely require multiple iterations of the protocol.

### Objective

The objective of Geminon is to become one of the top 5 stablecoin providers for the crypto market within the next two years.&#x20;

### Mission

The mission of Geminon is to create the stablecoin with the best possible equilibrium between decentralization, safety and scalability.&#x20;

### Vision

In its final form, the Geminon protocol should have these features:

* Immutability. The dev team should be able to renounce ownership of the smart contracts with the assurance that they can work indefinitely without human intervention.
* Independence. The protocol should be able to work with little to none dependency on external oracles and protocols.
* Full decentralization. Collateral from centralized issuers should be completely removed.
* Redundancy. The number of layers of collateral and algorithmic systems to hold the peg should be as varied as possible.
* Sustainability. All protocol security primitives should hold on and even grow on their own over time.

### Team

Geminon is built by an anonymous team, following the foundational principles of Bitcoin and the lead of Satoshi Nakamoto. Privacy is one of Geminon's core values, and that begins with the team itself. A crypto project cannot be truly decentralized nor secure if the people who control the keys of the protocol can be threatened and forced to shut down the project against their will.

A public team has never been a guarantee of anything, since the biggest scams have always been committed by recognizable people precisely to gain people's trust. That is why Geminon also prefers to follow another of the fundamental principles of crypto: that a project must be trustless.

> ***Don't trust us: trust our code.***


# Fees

Detail of the fees for the use of the Geminon protocol

Geminon uses a system of variable commissions of its own design. Our contracts apply a system of progressive fees that increase with the size of the operation carried out (a higher commission is paid the larger the amount), with a double purpose:&#x20;

* Make operating costs more equitable for users. In networks like Ethereum with a high gas price, small users suffer a much greater impact on their operations due to the transaction cost of the network. Geminon's variable fee system causes small transactions (<$1000) to pay only a small base fee, while large trades pay higher fees, which partly offsets the gas cost effect without hurting protocol revenue .&#x20;
* Discourage the toxic flow of orders. In any system that carries out financial operations, large orders (in relation to available liquidity) tend to have detrimental effects on the system. The GLP liquidity algorithm penalizes this type of order and the variable commission system reinforces it and extends it to the rest of the protocol modules.&#x20;

### Variable Fees Tranches&#x20;

The total commission charged is calculated by adding the variable part (immutable) to the base fee (which is a configurable parameter of smart contracts). The latter is calculated by linear interpolation according to the following tranches:&#x20;

* Below $1,000: No variable part, just the base fee charged.&#x20;
* Between $1,000 - $10,000: from 0% to 0.05% plus the base fee.&#x20;
* Between $10,000 - $100,000: from 0.05% to 0.1% plus the base fee.&#x20;
* Between $100,000 - $1,000,000: from 0.1% to 0.2% plus the base fee.&#x20;
* More than $1,000,000: 0.2% plus the base fee.&#x20;

For example, for a base fee of 0.1%, the curve of fees based on the amount of the operation would be:

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2FdATaqsgZbnGTPwK9tqY8%2FVariable%20fees.png?alt=media&amp;token=8a84d25a-4865-4328-bd3e-63f13a385d6e" alt=""><figcaption><p>Value of the commission for minting GEX based on the amount in dollars.</p></figcaption></figure>

## Distribution of fees&#x20;

Contrary to what happens with other decentralized projects, not all the commissions generated by the Geminon protocol go to the token holders, but an important part goes to the development team. This is so for several reasons:&#x20;

* Given the characteristics of the project, the team has not reserved any percentage of the supply nor has external financing been received, so the only way to profit comes from operating margins and not from speculation, as happens in any traditional business.&#x20;
* This system provides the right financial incentives for the team to stay committed to the project for the long term.&#x20;
* It provides resources to the team that can be reinvested in the development of the project, generating sustainable, non-speculative growth.&#x20;

The proportion of the commissions that the team receives is not fixed but depends on which protocol functions are most used by the users, so it cannot be known in advance. The following points explain this distribution in detail.&#x20;

### Genesis Liquidity Pools (GLP)&#x20;

GLPs charge a commission when GEX is minted by depositing collateral and when GEX is redeemed for collateral. The full amount of the commissions generated in the GLP is for the team. The commission is made up of a basic rate, which is a parameter that can be modified by the team, and the variable part that is calculated based on the amount of the operation. The base fee is currently set at 0.1% to mint GEX and 0.2% to redeem it and can never be set above 0.5%. The variable commission ranges from 0 to 0.2%.&#x20;

### Stable Coin Minter (SC Minter)&#x20;

Charges a fee for minting and redeeming stablecoin. Unlike GLPs, SC Minter only collects for the team the base commission amount, which is 0.1% to mint stablecoin and 0.2% to trade stablecoin. The amount of the variable commission, which ranges between 0 and 0.2%, is received indirectly by the holders of the GEX token.&#x20;

### StableSwap

The Stableswap is the only module that does not collect commissions for the team. The full amount of the commissions generated is received indirectly by the holders of the GEX token. A commission is charged in each currency exchange that consists of a fixed part, which depends on the exchanged pair and that must always be greater than or equal to the sum of the minting and exchange commissions of the SC Minter (>= 0.3% ), and a variable part that depends on the amount of the operation and ranges between 0% and 0.2%. The stable coin exchange module implements a security system to prevent attacks by anticipating the oracle (front running) that charges an additional commission (Safety Fee) if it detects this type of attack to make it economically unfeasible. This commission is automatically calculated based on the attacker's expected profit to suppress it and therefore has no limit. For more information read the section about the Stableswap module:

{% content-ref url="/pages/fcYyj0JPiZHaeTQjTha8" %}
[Decentralized Forex](/modules/decentralized-forex)
{% endcontent-ref %}

### Summary table&#x20;

This table shows the current value of the protocol fees. These fees can be modified at any time by the team if market circumstances require it.

| Module     | Function         | Fee (base - max)           |
| ---------- | ---------------- | -------------------------- |
| GLP        | mintSwap         | 0,1% - 0,3%                |
| GLP        | redeemSwap       | 0,2% - 0,4%                |
| SC Minter  | mintStablecoin   | 0,1% - 0,3%                |
| SC Minter  | redeemStablecoin | 0,2% - 0,4%                |
| Stableswap | stableSwap       | 0,3% - 0,5% + Safety Fee\* |


# Quick Start

The first version of the protocol allows the core functionality to be used to mint both GEX tokens and stablecoins.

### Step 1: buy GEX

The GEX token can only be obtained by depositing collateral in one of the Genesis Liquidity Pools. Currently there are 5 types of assets that are accepted as collateral: gold, Bitcoin and the native currencies of the blockchains in which the protocol operates (Ethereum, BNB and Avalanche).

#### Choose network and collateral

Not all assets are available on all networks (for example, tokenized gold only exists on Ethereum), so depending on the network you want to operate on, the type of usable collateral will be different. To see detailed information of the tokens visit this page:

{% content-ref url="/pages/kDjc63cl5B7Oxa3JPkhL" %}
[Collateral](/geminon-protocol/collateral)
{% endcontent-ref %}

#### Buy collateral

Once you have decided what type of collateral you want to use, locate which exchanges or DEX trade the asset to acquire it.

If you don't know any, you can use an aggregator like [*Coingecko*](https://www.coingecko.com/) or [*Coin Market Cap*](https://coinmarketcap.com/) to find a place to purchase collateral.

#### Supply collateral to Geminon pools

The GEX token can be traded using the Genesis Liquidity Pools of the protocol through our app:  [https://app.geminon.fi](http://test.geminon.fi).

{% hint style="info" %}
Split your trades if they are expected to have a big price impact on the pool, this will give you a better result than a single big trade.

This tip only applies to Geminon's Genesis Liquidity Pools since they don't strictly follow an AMM constant product formula (like Uniswap pools). GLPs are technically *Entropy Capturing Machines*, so the less entropy (price impact) yor trade causes in the pool, the better result you will get.
{% endhint %}


# Safety tips

Risks in a crypto protocol can come from both outside (hackers) and inside (malicious team). External attackers can target the protocol (flash loans, reentrancy attacks...) or users (phishing, website spoofing).

As a user, you can't do anything to prevent external attacks on the protocol (that's our job), but you can do everything to prevent attacks that are directed at you and, if the protocol is well designed, you can also do a lot to help prevent internal attacks and minimize their consequences.

In this section we give you some tips to be safer when interacting with Geminon Protocol.

### Always track the actions of the deployer address

The deployer of the smart contracts is the owner and therefore is the only address that can use certain functions in the contracts, some of which are critical for the safety of the protocol since their use in a malicious way can compromise the value of the tokens.&#x20;

All critical functions of the protocol have timelocks implemented as a security measure as they facilitate public control of those actions.

For this reason, the public accountability of the owner address is very important. Always review periodically the actions of that address over the protocol smart contracts in a blockchain explorer and check that they have been publicly announced and their objectives and motivation clearly explained.

Actions that must always be announced by the owner:

* Add minter to the GEX token or the stablecoins (timelock 7 days).
* Apply price feed change of a Genesis Liquidity Pool (timelock 7 days).
* Apply Stablecoin Minter change in a Genesis Liquidity Pool (timelock 30 days).
* Apply Oracle change in a Genesis Liquidity Pool (timelock 30 days).
* Apply Treasury Lender change in a Genesis Liquidity Pool (timelock 30 days).
* Set pool weight of a Genesis Liquidity Pool, specially if it is a lower weight and this action is repeated several times.
* Request Migration of a Genesis Liquidity Pool (timelock 30 days + reduce pool weight to less than 5% previously and 2% after + mint gets paused in the pool).
* Request Remove of a Genesis Liquidity Pool (timelock 30 days+ reduce pool weight to less than 5% previously and 1% after + mint gets paused in the pool).

You can find the deployer address in the corresponding section:

{% content-ref url="/pages/astSBmKxXda9pD5Wjskt" %}
[Deployment addresses](/geminon-protocol/deployment-addresses)
{% endcontent-ref %}


# GEX

Utility token of the Geminon protocol.

The GEX token is the main entry point to Geminon applications. It is necessary to mint and redeem stablecoins and to pay fees. In the future it will have additional functionalities as the protocol grows.

Beyond its usefulness for users, the GEX token is a key piece of the Geminon protocol, since its fundamental mission is to dampen collateral volatility by creating a linear response to changes in the collateral level, which makes it easier to later create assets of null price response (stable) to collateral changes. If you like calculus you can think of GEX as the first derivative of a parabolic price function, and stablecoins as the second derivative.

### Initial supply

There is no initial supply of tokens: no one, not even the team, is assigned a supply at launch. The only way to get GEX tokens is to deposit collateral in the Genesis Liquidity Pools (collateral mining). The amount of tokens in circulation and their distribution depends exclusively on the free market, the team has no control over it.

### Supply control

In order to fulfill its mission of buffering volatility between collateral and stablecoins, the GEX token needs to have an elastic supply. The supply is controlled by the Genesis Liquidity Pools, which are allowed to mint and burn tokens. Every time collateral is added or withdrawn from a pool, a certain number of tokens are minted or burned to ensure that the supply is always proportional to the amount of collateral.&#x20;

Although the supply is not strictly limited, the token minting / burning ratio takes into account a maximum supply target of 100 million tokens, and when that value is exceeded, the minting ratio is reduced to the minimum essential to maintain the linearity of the price versus the amount of collateral.

### Collateral weight control

The initial collateral composition of the GEX token is 40% gold, 30% bitcoin, and the remaining 30% in equal parts between the native currencies of the blockchains in which it operates: 10% ETH, 10% BNB and 10% AVAX.&#x20;

Since decentralized versions of tokenized bitcoin exist on all three chains, it was further decided to allocate 10% of bitcoin to each chain. In this way, the weight of each chain in the custody of the collateral is 60% in Ethereum, 20% in BSC and 20% in Avalanche. This was a design choice, and the collateral composition could be changed in the future if necessary to improve the safety of the protocol.

{% content-ref url="/pages/kDjc63cl5B7Oxa3JPkhL" %}
[Collateral](/geminon-protocol/collateral)
{% endcontent-ref %}

This weight ratio could only stand on its own if users always traded GEX in the pools for those exact collateral ratios. Since this is unfeasible, the GLPs are also in charge of enforcing that the weight of the pools is always kept in the exact proportion.

To achieve this, a coefficient is applied to the supply ratio of each pool, which means that the amount of GEX tokens minted / burned is different depending on whether the value of the collateral of the pool is above or below its target value.

This asymmetry in the emissions of each pool creates arbitrage opportunities between the pools that give the market the necessary incentives to automatically keep the weights balanced.

### Mint limiter

One of the design hypotheses of Geminon's smart contracts is that at any time any protocol contract or the owner itself can act maliciously. Following this principle, all the critical functions of the protocol incorporate redundant protection mechanisms to protect themselves not only from external attacks, but also from internal attacks.

The most critical part of the GEX token contract is the mint function, that creates new supply of tokens. To prevent an attacker who gains access to this feature from minting an unlimited number of tokens and to reduce the probability of flash-loan attacks on the protocol, the contract incorporates an automatic supply rate limiter. This rate limiter uses an algorithm developed by Geminon that is able to track very accurately the 24 hours average of the supply without the need to store the value of all trades (which would make operations extremely expensive in gas terms).

The GEX supply is limited to a max of 5 million units per day, which is 5% of the target supply level of the token. In the worst case scenario, the impact of this type of attack on the protocol would be limited and could be stopped before significant damage were done.

For more detailed information on the operation of the algorithm see the following page:

{% content-ref url="/pages/NH0wgiBW1kglvkOswWAs" %}
[Supply limiter](/tokens/gex/supply-limiter)
{% endcontent-ref %}

### How to obtain GEX tokens

GEX is a fully collateralized token and hence its supply can only be minted adding collateral to the Genesis Liquidity Pools. You can find all the info about how to obtain GEX tokens in our quick start guide:

{% content-ref url="/pages/JfXUWh8CWYCyjEAY0hcL" %}
[Quick Start](/quick-start)
{% endcontent-ref %}


# Supply limiter

The ERC20ElasticSupply contract is an extension of the ERC20 standard that allows you to create elastic supply tokens that can be minted and burned by other contracts. As a security measure, the contract includes a mint limiter whose parameters are set by the constructor during the creation of the token contract.&#x20;

Both the GEX token and all Geminon stablecoins include this security mechanism. This system is designed for cases in which Geminon token minting permits are granted to contracts outside the protocol, specifically in the case of inter-chain bridges operated by third parties, since in the event of bridge hacking the possible damage to the protocol is limited.&#x20;

### Algorithm&#x20;

The algorithm, developed by Geminon, is based on adaptive exponential smoothing whose parameters $$w\_1$$ and $$w\_2$$ vary depending on the interval $$\Delta t$$ elapsed since the last minting or burning of the token.

$$
\Delta t = t\_n - t\_{n-1}
$$

$$
\delta = \frac{T}{\Delta t}
$$

$$
\alpha = \frac {2}{1+\delta}
$$

$$
w\_1 = \begin{cases}
\ \ \ 1 &\text{if } \Delta t = 0 \\
\alpha \cdot \delta &\text{if } \Delta t > 0
\end{cases}
$$

$$
w\_2 = \begin{cases}
\ \ \ \ 1 &\text{if } \Delta t = 0 \\
1-\alpha &\text{if } \Delta t > 0
\end{cases}
$$

$$
\lambda\_n = w\_1 v\_n + w\_2 \lambda\_{n-1}
$$

Where $$\Delta t$$ is the time interval in seconds elapsed since the last operation and $$v\_n$$ is the volume (number of tokens) that you want to mint or burn, in which last case it will have a negative value and the value of $$\lambda$$ will be reduced.&#x20;

Note that time $$t$$ is a discrete variable defined by the moment of creation of the block in which the current transaction is mined, so those transactions mined within the same block have $$\Delta t = 0$$. In these cases, the weights  $$w\_1$$ and $$w\_2$$ take the value 1 and the volume of tokens of the transaction is added directly to the accumulated volume up to that moment.

### Fundamentals&#x20;

The described algorithm is designed to approximate the value of a 24-hour period moving average calculated on a discrete time series of variable frequency by means of a minimum calculation.&#x20;

In a traditional computer application, if we want to monitor the accumulated value of a discrete variable in a certain time interval, what we would do is create a table that stores each value of the variable together with its timestamp, and use said table to calculate an average of all values that are within the desired time window, for example the last 24 hours.&#x20;

In a blockchain application however such a basic calculation would be cost prohibitive. First, because storing data on the blockchain, especially a congested one like Ethereum, is extremely expensive. And second, because in each transaction it would be necessary to iterate over the lists of values and times stored, with which the complexity of the calculation and with it the cost of the transaction would grow with the number of data stored in the period.&#x20;

This approach would not only be disproportionately expensive but also dangerous: given a high enough trading volume, the network's gas limit per block could be reached, causing the minting functions of the token in question to be temporarily blocked due to reversing transactions that exceed said gas limit. A malicious actor could exploit this vulnerability to launch denial of service attacks against the protocol.&#x20;

If we were dealing with a uniform time series, with the values separated at regular intervals in time, the period $$t$$ moving average could be easily approximated simply by using an equivalent exponential moving average with parameter $$\alpha = 2/({1+t})$$. In this case, since there is also no possibility of imputing the missing values to transform the irregular series into a regular one, the only option is to introduce a variable that compensates for the irregularity in the frequency domain, adapting the intensity of the smoothing that is applied to each new data depending on how far it is from the basic frequency defined by the period of the moving average that is being approximated (86400 seconds in our case).&#x20;

### Algorithm efficiency&#x20;

The autoregressive algorithm designed by Geminon is capable of optimally approximating the explicitly calculated moving average curve.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2FqkZLTeBwnYIDo0hnaYbN%2FSupplyLimiterEchelon.png?alt=media&amp;token=c84740a7-0e12-4503-a2bb-be05f36835c5" alt=""><figcaption><p>Response of the estimator (orange) to a constant signal (blue). Real value of the series in green.</p></figcaption></figure>

In a simple simulation entering constant amount trades at constant intervals to produce a ramp function on the moving average value, the approximator is able to follow the ramp and converges perfectly to the new level without needing to store the series values.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2FWlP3H4bvGHYOQdfobst5%2FSupplyLimiterRandom.png?alt=media&amp;token=6190d981-8841-4864-9636-259a6d667913" alt=""><figcaption><p>Response of the estimator (orange) to a random signal in amplitude and frequency (blue). Real value of the series in green.</p></figcaption></figure>

In a much more difficult test, a series of random values is entered at random time intervals. As can be seen in the figure, the algorithm designed by Geminon is capable of following the real value of the moving average at all times despite the strong randomness of the signal without the need to store the previous values.


# Deflationary currencies

Inflation-indexed currencies are the reason for the existence of the Geminon protocol. The initial design of the protocol aimed to create a fourth-generation stablecoin, with a combination of scalability, decentralization, and security superior to existing alternatives, and also resistant to loss of value due to inflation.&#x20;

### Peg value

Despite its name, Geminon's indexed coins do not track any index, but rather use the predicted value of that index for the next period as a reference value. This detail is important since it allows them to be on the inflation curve, instead of behind the curve.&#x20;

#### Monotony&#x20;

Another important difference compared to a simple inflation index is that Geminon's indexed coins are programmed so that their value can never fall against their base currency: in cases where deflation occurs, their value remains fixed to that of the base currency instead of following the decline in the inflation rate, so that in global terms a monotonically increasing value curve is obtained, that is, a purely deflationary currency.&#x20;

### Index prediction&#x20;

The PredictIndex contract implements a time series forecasting system based on the Holt-Winters non-seasonal linear trend model. In its recursive form, the model is given by two equations for the smoothing of the series and the trend:

$$
S\_n = \alpha X\_n + (1 - \alpha)(S\_{n-1} +
T\_{n-1})
$$

$$
T\_n = \gamma (S\_n - S\_{n-1}) + (1 - \gamma) T\_{n-1}
$$

Where $$X$$ is the time series, $$S$$ the smoothed value of the series, $$T$$ the trend component of the series and $$\alpha$$, $$\gamma$$ the model parameters. The prediction of the time series $$S$$ at the instant $$n+m$$ is given by the expression:

$$
\hat{X\_n}(m) = S\_n + m T\_n
$$

The $$\alpha$$ and $$\gamma$$ parameters are obtained by optimization, selecting the pair that gives the minimum prediction error for a period for the analyzed time series.&#x20;

### Target value&#x20;

The target value is the value that the currency should reach on the index prediction date. It is the conversion of the index value into monetary exchange value (expressed in USD). It is obtained by dividing the prediction value by the base value of the index.

$$
Y\_n = \dfrac {\hat{X\_n}} {X\_b}
$$

This value also expresses the percentage of inflation accumulated from the date of the period used as the base to the present.

#### Ramp function&#x20;

The time series of the consumer price index has a monthly periodicity. If the target value were used directly as a reference value for the currency, there would be sudden jumps in its value once a month, coinciding with the publication of the new inflation data. These sudden price jumps, being predictable, would allow temporary arbitrage attacks against the protocol.&#x20;

To avoid these types of attacks and generate a continuous price change curve, a linear interpolation function is used that generates a continuous ramp between the last target value and the next one:

$$
\delta\_{t,n} = \dfrac {t - t\_{n-1}} {t\_n - t\_{n-1}}
$$

$$
y\_{t,n} = Y\_{n-1} + \delta\_{t,n} (Y\_n - Y\_{n-1})
$$

### Variation limiter&#x20;

Indexed tokens incorporate a security mechanism to prevent excessive variations in their target value in a given period. Each time the token's target value is updated, the contract checks that the token's target value is within bounds:&#x20;

* Lower bound: the lower bound of variation is given by the monotonicity requirement of the price function. The new target value cannot be less than the current reference value of the coin. If the calculated target is lower, the current reference value is taken as the new target, whereby the reference value is temporarily fixed at the current price.&#x20;
* Upper limit: it is a parameter of the contract, which is established by default at 2% per month. If the new target value represents a variation from the previous target greater than 2%, the limit value is used as the target.&#x20;

### Backup value&#x20;

The ERC20Indexed contract, which serves as the basis for Geminon's inflation-indexed coins, implements a backup mechanism that allows the tokens to function autonomously, fulfilling their function of hedging against inflation even if nobody updates the values of the benchmark index through the PredictIndex contract.&#x20;

In case of a normal update, the monthly variation rate is calculated as:

$$
V\_n = \dfrac {T\_n} {S\_n}
$$

Where $$T\_n$$ and $$S\_n$$ are the trend and smoothing according to the Holt-Winters model described above. If we define a constant backup variation rate $$V\_0$$, in the event that in the following period the values of $$T\_n$$ and $$S\_n$$ are not available, a new variation rate would be calculated according to the expression:

$$
V\_n = \alpha V\_0 + (1 - \alpha)V\_{n-1}
$$

The variation rate calculated in this way slowly converges towards the default value. If the underlying index stops updating permanently, after a sufficient number of periods, $$V\_n = V\_0$$ will be obtained. The new target value would be calculated each period recursively using the backup rate of change:

$$
\hat{X}\_{n+1} = X\_n (1 +  V\_n)
$$

To prevent the backup update from being invoked by taking advantage of the window between the date of publication of the new index data and the update transaction, the PredictIndex contract makes the prediction available for the next two periods, so that it is only considered out of date if two consecutive updates fail. The token contract can start making backup updates only when the second prediction date passes without the index data being updated again, that is, when more than two months go by without updating the values.


# USDI

USDI is a currency indexed to the inflation in the US. For the value of inflation, the consumer price index for all urban consumers of all products (CPIAUCSL) is taken as a reference, which can be consulted at the following link:

{% embed url="<https://fred.stlouisfed.org/series/CPIAUCSL>" %}

The index, with a base of 100 in the years 1982-1984, is updated monthly. The percentage changes in the index measure the rate of change of inflation between any two periods. For example, in January 2010 the index had a value of 217,488, and in November 2022 it was 298,349, which means that accumulated inflation in that period has been 37,19%.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2FCTOS6Pi7CYFqIlldEoRQ%2FCPI%20pred.png?alt=media&amp;token=69a748e4-13b2-43e5-aa84-969b770f3c2c" alt=""><figcaption><p>US Consumer Price Index (CPI) (base 1982-1984). Holt-Winters model predictions.</p></figcaption></figure>

USDI does not take its value directly from the CPI, since the data is published with a month of delay. Instead, the prediction of the index that will be published in the following month is calculated, whose value corresponds to the current month, and the value of said prediction is used as the reference target value of the token.&#x20;

In cases where the new target value is below the current value (deflation), the USDI reference value remains constant, so that in no case does its value fall against the dollar. This distinction is what makes the USDI a deflationary currency per se and not just a tokenized inflation index. The figure shows how it is quite common for deflationary periods to appear, sometimes lasting several years, in which the reference value of the USDI remains constant while the target value does not recover its previous maximum.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2FWLIrIIfS9YA9hM2hb278%2FUSDI%20peg.png?alt=media&amp;token=3ebf7614-2a94-40b0-b411-ea559e98352f" alt=""><figcaption><p>USDI Reference (peg) Value vs. PredictIndex Target Value.</p></figcaption></figure>

### Target value update&#x20;

The USDI token was designed so that its peg value could be updated in a decentralized way. The system is based on the use of the Any API service of the Chainlink oracle network, which allows calls to any API from a blockchain application and receives the response data in a verifiable way. For more information consult the Chainlink documentation:

{% embed url="<https://docs.chain.link/any-api/introduction/>" %}

The operation of the update mechanism however is complex and involves four different contracts:

* Contract ChainlinkFredRelease. It allows making calls to the Federal Reserve API through the Chainlink network to obtain the date of the next publication of the data of the consumer price index (CPI).&#x20;
* Contract ChainlinkFredObservation. It allows calls to be made to the Federal Reserve API through the Chainlink network to obtain the value of the last published data of the Consumer Price Index (CPI).&#x20;
* PredictIndex contract. Reads from the two previous contracts the value of the next published data and the value of the last published data, and uses them to calculate the prediction of the next data to be published on that date and update the target value.&#x20;
* USDI contract. Reads the new target value from the PredictIndex contract, checks that it is valid, and updates its values for the target.&#x20;

The upgrade procedure is decentralized and can be carried out by anyone willing to pay the gas and Chainlink network fees. A total of five transactions are required to complete the process:&#x20;

* Two transactions to deposit LINK tokens into the ChainlinkFredRelease and ChainlinkFredObservation contracts via the depositLink() function to pay Chainlink's commission for API calls.&#x20;
* A transaction using the requestData() function of the PredictIndex contract to make the API calls via the ChainlinkFredRelease and ChainlinkFredObservation contracts.&#x20;
* A transaction using the fetchData() function of the PredictIndex contract to read from the ChainlinkFredRelease and ChainlinkFredObservation contracts the data obtained from the API calls and update the index predictions.&#x20;
* A transaction using the token's updateTarget() function to update the target value. Anyone can call this function, as the contract automatically checks if it should be updated and reverts the transaction if not. This function is also called automatically from the SCMinter contract every time a transaction involving the USDI is carried out, which guarantees that an updated reference value is always operated.&#x20;

#### Manual update&#x20;

The PredictIndex contract also has an auxiliary mechanism that allows the owner to manually update the reference inflation index and next release date values in case the main mechanism is unavailable for some reason. This procedure requires only two transactions:&#x20;

* A transaction using the provideData() function of the PredictIndex contract associated with the USDI token, providing the values of the date of the next publication of the inflation data and the date of the last published data. Only an address authorized by the contract owner can execute this action.&#x20;
* A transaction using the token's updateTarget() function to update the target value, just like in the previous section.&#x20;

#### Backup value&#x20;

The USDI token contract is prepared to work completely autonomously. Even if no one ever updates the target value of the PredictIndex contract, the updateTarget() function can perform a fallback update using a default value. This value is 0.2% per month, which is equivalent to 2.68% annualized. The monthly rate of change slowly converges towards that value if the reference index values stop updating. See the previous page on inflation-indexed currencies for more information on how this backup value is calculated.


# EURI

EURI is a currency indexed to the inflation in the Eurozone. For the value of inflation, the harmonized index of consumer prices for all products (HICP) is taken as a reference, which can be consulted at the following link:

{% embed url="<https://ec.europa.eu/eurostat/databrowser/view/PRC_HICP_MIDX__custom_4410812/default/line?lang=en>" %}

The index with base 100 in the year 1996 is used. The percentage changes in the index measure the rate of variation of inflation between any two periods. For example, in January 2010 the index had a value of 127.6, and in November 2022 it was 168.6, which means that accumulated inflation in that period was 32.13%.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2F1Nft8Gz4imfa0LF5ubn8%2FHICP%20pred.png?alt=media&amp;token=8f234047-9f38-4256-bab1-f6354867b35e" alt=""><figcaption><p>Harmonized Index of Consumer Prices (HICP) of the Eurozone (base 1996). Holt-Winters model predictions.</p></figcaption></figure>

EURI does not take its value directly from the HICP, since the data is published one month late. Instead, the prediction of the index that will be published in the following month is calculated, whose value corresponds to the current month, and the value of said prediction is used as the reference target value of the token. As can be seen in the figure, the predictions of the Holt-Winters model are quite accurate and replicate the data series with great fidelity.&#x20;

In cases where the new target value is below the current value (deflation), the reference value of the EURI remains constant, so that in no case does its value fall against the euro.

### Target value update

Although it uses the same PredictIndex contract as the USDI token, the EURI token does not currently have the option to update values via direct API calls through the Chainlink network. The only mechanism for updating the HICP values is manual, which requires two transactions:&#x20;

* A transaction using the provideData() function of the PredictIndex contract associated with the EURI token, providing the values of the date of the next publication of the inflation data and that of the last published data. Only an address authorized by the contract owner can execute this action.&#x20;
* A transaction using the token's updateTarget() function to update the target value. Anyone can call this function, as the contract automatically checks if it should be updated and reverts the transaction if not. This function is also called automatically from the SCMinter contract every time a transaction involving the EURI is carried out, which guarantees that an updated reference value is always operated.&#x20;

#### Backup value&#x20;

The EURI token contract is prepared to work completely autonomously. Even if no one ever updates the target value of the PredictIndex contract, the updateTarget() function can perform a fallback update using a default value. This value is 0.2% per month, which is equivalent to 2.68% annualized. The monthly rate of change slowly converges towards that value if the reference index values stop updating. See the page on inflation-indexed currencies for more information on how this support value is calculated.

{% content-ref url="/pages/ZEGM73MmCfRwVDJ8rvwc" %}
[Deflationary currencies](/tokens/deflationary-currencies)
{% endcontent-ref %}


# Stablecoins

Geminon stablecoins are ERC20 tokens with elastic supply. New supply can only be created via the stablecoin minter (SC minter) smart contract in exchange for GEX tokens. For more information on this system, consult the section on the limiter:

{% content-ref url="/pages/NH0wgiBW1kglvkOswWAs" %}
[Supply limiter](/tokens/gex/supply-limiter)
{% endcontent-ref %}

### Peg value

All Geminon stablecoins incorporate in their contract a connection to a price feed from the Chainlink oracle network that provides updated prices of the currency's exchange rate that replicate against the dollar. The last price value of the coin can be obtained by calling the getPegValue() function. Chainlink oracles use real Forex market values as their data source, making them extremely secure against any type of attack.&#x20;

All Geminon contracts use this value provided by the oracle as a reference to calculate the amounts of currency to be exchanged. As the price of the coins is fixed algorithmically, users are assured that their stablecoins can always be exchanged for their peg price using Geminon contracts. In the event that the coins are used in other protocols or external exchanges, the price would remain close to its peg value thanks to arbitrage between the market in question and the contracts of our protocol.

### Available currencies

Geminon offers a wide variety of stablecoins from different regions of the world, and the list keeps growing:

<table><thead><tr><th width="121" align="center">Symbol</th><th width="216" align="center">Name</th><th width="158" align="center">Country / region</th><th align="center">Networks</th></tr></thead><tbody><tr><td align="center">USDG</td><td align="center">Geminon US Dollar</td><td align="center">USA</td><td align="center">Ethereum, BNB, Avalanche</td></tr><tr><td align="center">EURG</td><td align="center">Geminon Euro</td><td align="center">Europe</td><td align="center">Ethereum, BNB, Avalanche</td></tr><tr><td align="center">CNYG</td><td align="center">Geminon Renminbi</td><td align="center">China</td><td align="center">Ethereum</td></tr><tr><td align="center">JPYG</td><td align="center">Geminon Japanese Yen</td><td align="center">Japan</td><td align="center">Ethereum, BNB, Avalanche</td></tr></tbody></table>


# Genesis Liquidity Pools

The GLPs are the entry point for users to the Geminon protocol, and constitute the basis of its operation. They allow users to obtain GEX tokens, which are required to access other features of the protocol, in exchange for depositing other tokens as collateral.&#x20;

Despite their name, they are not liquidity pools; this naming is used for convenience, as it helps users to recognize the purpose of this module. A GLP presents several differences compared to a Uniswap-type liquidity pool:&#x20;

* There are no liquidity providers: instead, it is the pool itself that creates and destroys liquidity each time the asset used as collateral is deposited or withdrawn from the pool.&#x20;
* You cannot exchange any pair of assets: one of the two tokens in the exchange must always be the GEX token.&#x20;
* They are not isolated: they use information from the state of the other GLPs for their operations.&#x20;
* They allow a portion of the pool's assets to be lent on a term basis.&#x20;
* They can mint and burn the GEX token.&#x20;

A GLP is a type of LBP (Liquidity Bootstrapping Pool), a variant of liquidity pools specialized in launching new tokens to the market with very low liquidity. LBPs were first described in 2020 by the Balancer protocol. The main difference with respect to a Uniswap-type liquidity pool is that an LBP does not follow a constant product liquidity curve, but uses a parametric curve that allows, for example, to execute a Dutch Auction (with a descending price) to launch a new token to the market, ensuring a fair distribution of it.&#x20;

Given their characteristics, the GLP developed by Geminon have several advantages over a Uniswap-type liquidity pool:&#x20;

* Higher returns for GEX token holders: as there are no liquidity providers, all benefits from slippage of operations in a GLP are received by token holders.&#x20;
* Like an LBP, they allow tokens to be launched on the market without the need to provide a large initial liquidity, since it is the pool itself that creates the liquidity dynamically.&#x20;
* Control of the supply of the token, which in turn allows precise control of the price curve that helps to avoid exponential regimes at the extremes of the curve.&#x20;
* It allows to balance the weights of the collateral between different pools.&#x20;
* Greater security for users: the liquidity they contain cannot be withdrawn instantly: they do not allow "rug pulls".&#x20;
* Increased security for the protocol: The entropy capture feature of GLP makes operations that generate large price slippage in a pool, such as manipulations using flash loans, economically unfeasible for the attacker.


# Automated Market Maker

Every liquidity pool is based on an automatic market making (AMM) algorithm that determines the prices and amounts of tokens in each trade. Geminon's GLPs use a proprietary algorithm derived from the constant product AMM that gives them the liquidity creation capabilities of an LBP.

### Constant product AMM

Practically all of the decentralized exchange (DEX) protocols that exist today use the so-called constant product formula for their liquidity pools:

$$
x \cdot y = k
$$

Where $$x$$ and $$y$$ are the amounts of the pair of tokens in the pool and $$k$$ is a constant that is fixed when the initial liquidity is added during its creation. The liquidity pool creates an automatic market for the token pair simply by imposing the condition that, after every trade, the product of the amounts of both tokens cannot be less than the liquidity constant:

$$
(x + \Delta x)(y + \Delta y ) \nless k
$$

Given an amount of tokens $$\Delta x$$ that you want to exchange using the liquidity pool, the amount of the exchanged token to receive $$- \Delta y$$ is calculated as:

$$

* \Delta y = y - \frac {k}{x + \Delta x}
  $$

### Generalized constant product AMM

The constant product AMM formula can be generalized for a pool consisting of n tokens with weights $$w\_n$$ such that $$\sum\_n w\_n = 1$$:

$$
\prod\_n B\_n^{w\_n} = k
$$

Where $$B\_n$$ is the balance of the nth token in the pool. Developing the previous formula, it is obtained that for an exchange of any pair of tokens in the pool, given the input amount of one token $$\Delta x$$, the received amount of the second token is given by:

$$
-\Delta y = y \Bigg(1 - \bigg(\frac {x} {x + \Delta x}\bigg)^{\frac{w\_x}{w\_y}}\Bigg)
$$

From the previous equations it is derived that the quote or relative price of one token based on another in the pool depends exclusively on the balances and relative weights of both tokens in the pool:

$$
P\_x^y = \frac {\frac {x}{w\_x}} {\frac {y}{w\_y}}
$$

It can be easily shown that these equations are transformed into the equations for a pool of two tokens seen in the previous point by doing $$w\_x = w\_y$$.

### Geminon AMM

The generalized AMM equations from the previous point are the ones used by the Balancer protocol for its pools. In Balancer LBPs it is possible to alter the relative weights of the tokens in the pool, which changes the relative price of both tokens and also the value of the pool's liquidity constant $$k$$.&#x20;

The AMM algorithm developed for the Geminon GLPs also alters the value of the pool invariant, although it employs a completely different mechanism. The main differences are:&#x20;

* The variation of the liquidity constant is completely automatic in GLP: it is not possible to manually alter the weights of the tokens in the pool, and therefore the prices.&#x20;
* The parameterization of liquidity in a GLP varies depending on the operations carried out, not depending on time as it happens in LBPs.&#x20;
* The GLP algorithm does not vary the weights of the tokens in the pool, but rather the balance of the GEX token.&#x20;

#### Algorithm description&#x20;

The Geminon AMM works in two steps:&#x20;

1. The amount of the output token is calculated using the constant product AMM formula with the liquidity available at that moment in the pool, that is, in this step the LPG behaves exactly the same as a Uniswap-type liquidity pool.&#x20;
2. In the second step, the balance of the GEX token in the pool is modified by minting or burning tokens. The variation of the supply of the GEX token is calculated from the number of tokens that the user has received or delivered to the pool, depending on the operation carried out.&#x20;

To help reduce trade slippage, which negatively impacts user output, the pool automatically splits the input amount in half and runs the above steps twice, so that on the second iteration the user benefits from the increase in liquidity that he himself has generated. This mechanism is especially effective when the liquidity of the pool is very low.&#x20;

#### Mint GEX tokens (mintSwap)&#x20;

For a GEX token purchase (mint) operation, the amount of GEX tokens to be received is initially calculated as if it were a Uniswap-type liquidity pool. If $$c\_0$$ is the balance of collateral in the pool, and $$g\_0$$ the balance of GEX tokens in the pool, the pool invariant is:

$$
k\_0 = c\_0 \cdot g\_0 = (c\_0 + c\_{in})(g\_0 - g\_{out})
$$

And the amount of tokens received by the user, $$g\_{out}$$, when he delivers an amount of collateral, $$c\_{in}$$, is calculated by isolating the invariant in the previous equation:

$$
g\_{out} = g\_0 \bigg( 1 - \frac {c\_0}{c\_0 + c\_{in}} \bigg)
$$

After calculating the number of output GEX tokens, the mint coefficient $$\mu$$ is applied, which increases the balance of GEX tokens in the pool:

$$
g\_1 = g\_0 - g\_{out}(1 - \mu)
$$

$$
c\_1 = c\_0 + c\_{in}
$$

$$
k\_1 = c\_1 \cdot g\_1
$$

Finally, the commissions for minting the protocol are deducted from the number of GEX tokens to be sent to the user.&#x20;

The minting coefficient takes its values in the interval $$\[1,2]$$, which makes it possible to deduce the behavior of GLP in GEX token mint operations:

1\. In a minting operation, liquidity always increases: since the values of the minting coefficient are restricted ($$\mu \in \[1,2]$$) the difference $$1-\mu$$ is always less than or equal to 0, which implies that $$g\_1 \ge g\_0$$, the final balance of GEX in the pool will always be equal to or greater than the initial. Also, since $$c\_1 > c\_0$$ because it is a minting operation, $$k\_1 > k\_0$$, then the liquidity product of the pool after the operation will always be strictly greater than the initial one.

2\. The result of an operation in GLP is closer to that obtained in a Uniswap-type liquidity pool, the lower the amount of the operation. If the $$k\_1$$ invariant equation is developed to express it solely as a function of the input quantity, we have:

$$
k\_1 = (c\_0 + c\_{in}) \cdot g\_0 \Bigg(1 - (1-\mu) \bigg(1- \frac {c\_0}{c\_0 + c\_{in}} \bigg) \Bigg)
$$

It's easy to see that the above expression converges to the value of the initial invariant $$k\_0 = c\_0 \cdot g\_0$$ the lower the input value $$c\_{in}$$ is, or more formally:

$$
\lim\_{c\_{in} \rarr 0} k\_1 = k\_0
$$

3\. The final price of the GEX token in the pool after the transaction is lower than the price that would be obtained in a pool of pure constant product. It is easy to intuitively see that by increasing the balance of GEX tokens in the pool, the relative price of this token against the other token should decrease:

$$
P\_1^g = \frac{c\_1}{g\_1} = \frac{c\_0 + c\_{in}}{g\_0 - g\_{out} + \mu g\_{out}} < \frac{c\_0 + c\_{in}}{g\_0 - g\_{out}}
$$

This means that transactions in a GLP are not reversible even without taking into account the protocol commissions: if a mint operation is done and immediately after the opposite is carried out, redeeming the tokens in the pool, a lower amount will be obtained depending on how far the liquidity product $$k\_1$$ is from the initial one $$k\_0$$. As seen in the second property, the invariants coincide at zero and separate as the amount of the trade $$c\_{in}$$ increases, or more specifically the ratio $$c\_0/c\_{in}$$ that determines the slippage that the trade produces in the pool price. The greater the slippage (entropy) generated by an operation in the pool, the more irreversible that operation is. Said entropy is captured by the GLP by increasing the value of the GEX token, which is why GLPs are called entropy capturing machines.&#x20;

The irreversibility of the operations presents important advantages for the security of the Geminon protocol, since it implies that flash loan attacks cannot be carried out on a GLP: since the amount lent cannot be repaid in its entirety, the transaction will revert. In general, any attack that involves price manipulation in a GLP using large transactions that must be undone in a short period of time, will mean a financial loss for the attacker in favor of the protocol.

#### Redeem GEX tokens (redeemSwap)

The equations for GEX token redemption are very similar to those for minting. The main difference between both processes is that during the exchange, the protocol commission is deducted from the amount of GEX tokens entered. The amount of exit collateral $$c\_{out}$$, given an input amount $$g\_{in}'$$ (minus the commission) is worth:

$$
c\_{out} = c\_0 \bigg( 1 - \frac {g\_0}{g\_0 + g\_{in}'} \bigg)
$$

And the new balances that determine the liquidity product of the pool:

$$
c\_1 = c\_0 - c\_{out}
$$

$$
g\_1 = g\_0 + g\_{in}'(1 - \rho)
$$

### Price curve

In a constant product liquidity pool, the price of a token with respect to its peer is the quotient of the reserves of both. Using the constant product ratio $$x \cdot y = k$$ we get:

$$
P\_y = \frac{x^2}{k}
$$

The price of one token in a liquidity pool is a parabolic function of the amount of the second token in the pool. In a GLP, on the other hand, the value of $$k$$ is not constant, but rather its value varies with the amount of collateral in the pool. The GEX token price function in a GLP can be written as:

$$
P\_g = \frac{c^2}{k(c)}
$$

Where $$k(c)$$ is a function that varies linearly with the amount of collateral tokens. As a consequence, the GLP price function for the GEX token does not vary quadratically with the amount of collateral as it happens in a Uniswap-type pool, but rather linearly. The goal of this design is to reduce the volatility of the GEX token.&#x20;

For a detailed discussion on the influence of the mint ratio on the value of $$k$$, see the next page "Supply Control".


# Supply Control

The supply of GEX tokens is controlled by varying the liquidity product $$k$$ of the GLP by adding minting and burning coefficients to the AMM equations.

### Mint ratio

The mint ratio of the GEX token in a GLP is calculated as the quotient between the supply ratio of the pool, $$\sigma\_p$$, and the weight ratio of the collateral of said pool, $$\omega\_p$$:

$$
\mu\_p = \frac{\sigma\_p }{\omega\_p}
$$

The mint ratio rises when the total amount of minted tokens is below its target value or when the pool has less collateral than desired. In this case, in the event of a mint operation, the pool creates more liquidity and rises less in price compared to another GLP that has more collateral, which creates an arbitrage incentive for the pool with less collateral to attract more suppliers.&#x20;

When the GLP has more collateral than desired, the mint ratio drops compared to other GLP, creating less liquidity and driving the price up more, encouraging the use of other pools to mint instead.

### Burn ratio

The burn rate of GEX tokens in a pool is proportional to the pool's supply ratio $$\sigma\_p$$ and the weight ratio $$\omega\_p$$:

$$
\rho\_p = \sigma\_p \cdot \omega\_p
$$

The difference between the burn ratio and the mint ratio is determined by the collateral weight ratio: while in burning the relationship is proportional, in minting it is the inverse. This means that the behavior of the GLP when adjusting the arbitrage incentives is opposite depending on whether it is a supply (mint) or withdrawal (burn) operation of collateral.&#x20;

In a GEX token burn operation, if the pool has less collateral than desired, it burns fewer tokens which results in a lower final price, creating an arbitrage incentive to mint in the pool. If the pool instead has more collateral than desired, the amount of GEX tokens burned increases, resulting in a higher final price that discourages the supply of collateral to the pool.

### Supply ratio

The supply ratio has the mission of creating liquidity for the GEX token proportionally to the amount of collateral that is deposited in the pools, thus creating a price curve with constant variance. It is calculated as a ratio between the difference of the target supply of the GEX token, $$S\_g$$, and the total supply minted by the pools in the network $$\sum\_p m\_p$$:

$$
\sigma\_p = \begin{cases}
\ \ \ \ \ 2 &\text{if } m\_p \le 0 \\
1 + \frac{S\_g - \sum\_p m\_p}{S\_g} &\text{if } 0 < m\_p \le S\_p \\
\ \ \ \ \ 1 &\text{if } m\_p > S\_p
\end{cases}
$$

The supply ratio has its range of values limited to the interval \[1, 2] for stability reasons. The ratio takes its maximum value at 2 when the supply of the GEX token is null, so that the generation of liquidity is prioritized over the rise in price. When the target supply level (100 million tokens) is reached, the ratio is equal to 1, and exactly the same number of tokens that are delivered to the user are minted. When this happens, the number of GEX tokens in the pool becomes constant, so the liquidity product $$k$$ varies linearly with the amount of collateral in the pool, and the GEX token price curve converges to $$y = x$$, perfectly linear.&#x20;

If the supply ratio is less than 1, the amount of GEX tokens in the pool starts to decrease and the price curve is no longer linear, approaching a parabola the closer the mint ratio gets to 0. If the supply ratio is greater than 2, an inversion of the price curve occurs: when minting GEX tokens their price would fall and when exchanging them it would rise, causing unstable behavior of the pool. For this reason the values are limited to the interval \[1, 2].

### Pool weight ratio

The weight ratio is responsible for creating arbitrage opportunities between the pools that help keep the amount of collateral in each one close to its target value. It is defined as the relationship between the current weight of the collateral, and the target weight set in the protocol parameters:

$$
\omega\_p' = \frac{v\_p}{\rho\_p \cdot \sum\_p v\_p}
$$

Where $$v\_p$$ is the value, measured in USD, of the collateral that the pool contains, $$\sum\_p v\_p$$ is the joint value of the collateral in all the GLPs in the network, and $$\rho\_p$$ is the target weight. The value of the calculated ratio $$\omega\_p'$$ is limited so that its value is between 0.75 and 1.25:

$$
\omega\_p = \begin{cases}
0.75 &\text{if } \omega\_p' < 0.75 \\
\ \ \omega\_p' &\text{if } 0.75 \le \omega\_p' \le 1.25 \\
1.25 &\text{if } \omega\_p' > 1.25
\end{cases}
$$

The weight ratio will have a value greater than 1 when the value of the collateral in the pool is greater than the target, and less than 1 when the value of the collateral is below its target.


# Internal oracle

Geminon GLPs are part of a complete decentralized finance system that includes stablecoin minting and lending. These types of applications are vulnerable to price manipulation attacks, and therefore need reliable sources of prices for their calculations. Given the central role that the GEX token plays in the Geminon protocol, an internal oracle has been incorporated into the GLPs that allows secure token pricing.&#x20;

### Oracle algorithm&#x20;

The GLP internal oracle algorithm employs a principle similar to that used for the GEX token supply limiter and StableSwap Guard, which is based on adaptive exponential smoothing whose parameters vary depending on the application. The oracle algorithm calculates two values, an instantaneous value that includes the operations within the current block ($$\Delta t = 0$$) and another considered the safe value that is only updated at the close of each block ($$\Delta t > 0$$).&#x20;

#### Instant value&#x20;

The oracle's instantaneous value, $$l\_n$$, is updated each time an operation occurs on a GLP. The smoothing parameter, $$\beta$$, is obtained from the relationship between the volume of the current trade, $$v\_n$$, and the average volume of trades in the pool $$\overline{V}$$.

$$
\beta\_n = \begin{cases}
\ \ \ \ \ 1 &\text{if } \beta\_n > 1 \\
\dfrac {\overline{V}\_n}{v\_n + \epsilon} &\text{if } \beta\_n \le 1
\end{cases}
$$

$$
l\_n = \beta\_n p\_n + (1-\beta\_n) l\_{n-1}
$$

The parameter $$\beta$$ takes its maximum value, limited to 1, when the volume of the current trade is less than the usual volume of the pool. In that case, the instantaneous value of the oracle price $$l\_n$$ matches the instantaneous price of the pool $$p\_n$$. If the volume of the last trade is higher than the usual volume, then $$\beta < 1$$ and the price is filtered proportionally to the volume anomaly. For example, if the volume of the operation is 1000 times higher than normal, then the new price will have a weight of 0.001 in the average price $$l\_n$$ and its value will not affect the instantaneous price of the oracle, achieving its objective of filtering out abnormal operations.

To calculate the average volume of operations, a simple exponential smoothing is used, with parameter $$\gamma = 0.001$$. This smoothing is equivalent to using the average of the volume of the last 1000 trades:

$$
\overline{V}\_{n+1} = \gamma v\_n + (1 - \gamma) \overline{V}\_n
$$

The update of the average volume of operations is done afterwards, so the volume of the current operation is not taken into account in the oracle calculations until the next operation. This detail is important, since it prevents a flash loan from altering the average volume data used to calculate the parameter $$\beta$$, improving the filtering capacity of the algorithm.

Finally, the accumulated volume of the current block is calculated:

$$
V\_B = \begin{cases}
\ \ \ \ \ 0 &\text{if } \Delta t > 0 \\
\sum\_{n \in B} v\_n &\text{if } \Delta t = 0
\end{cases}
$$

#### Safe value

The oracle safe value is calculated only at the start of a new block ($$\Delta t > 0$$). The calculation is similar to that of the instantaneous value, the difference being that the safe value takes as input the values of the oracle's instantaneous value, producing second-order filtering. For the smoothing parameter $$\alpha$$, the cumulative volume of the previous block $$V\_{B-1}$$ is used instead of the volume of the last trade:

$$
\alpha\_n = \begin{cases}
\ \ \ \ \ \ 1 &\text{if } \alpha\_n > 1 \\
\dfrac {\overline{V}*n}{V*{B-1} + \epsilon} &\text{if } \alpha\_n \le 1
\end{cases}
$$

Finally, to calculate the safe value of the price $$m\_n$$, the smoothed instantaneous value of the previous block is used as input, $$l\_{n-1}$$, instead of the current price $$p\_n$$:

$$
m\_n = \alpha\_n l\_{n-1} + (1-\alpha\_n) m\_{n-1}
$$

This calculation structure ensures that the safe price $$m\_n$$ cannot be affected by a flash loan attack, since it takes the closing price of the previous block, which has also been previously filtered, ruling out operations with anomalous volume, and which is again filtered through of the parameter $$\alpha$$. This double filtering also ensures that even spot attacks are properly discarded until several trades with normal volume are made in the pool at the new price.

The justification for security against spot attacks that last longer than the block time of the network is found in the hypothesis of market efficiency and the principle of non-arbitration. An attacker who tries to manipulate the price of a pool without using a flash loan is exposed to market reaction (arbitrage) in the next block to restore the price balance, so the price resulting from the following operations will be a fair market price that must be reflected by the oracle.

This ability to immediately reflect price changes when normal trading flow is established while filtering out one-off anomalies is possible because the smoothing is done in the volume domain rather than the time domain, therefore, a great noise filtering capacity is achieved without introducing delay in the smoothed series.

The goal of a price oracle is not to completely eliminate large trades but to prevent instant price manipulations while providing the most up-to-date price possible. In this task, the algorithm proposed by Geminon is extremely efficient and outperforms the algorithms used so far in other decentralized protocols. The combination of this oracle with the entropy capture feature of GLP makes it extremely unlikely that a GEX token price manipulation attack would prove beneficial to the attacker.


# Price manipulation attacks

Price manipulation attacks are the most common type of attack against blockchain-based decentralized finance protocols. These attacks are almost always executed using a flash loan, which is why they are also known by that name. Despite the fact that this type of attack has been carried out dozens (if not hundreds) of times and its mechanism is widely known, projects with the same vulnerabilities that allow these attacks continue to be put into production. Taking this reality into account, the Geminon protocol has been designed in such a way that it is safe against this type of attack.

### Flash loans

Flash lending is a feature that was initially introduced by the Aave lending protocol in 2020, and soon after by Uniswap v2. As most decentralized exchange and lending protocols released in the following months were inspired by or forked from Aave and Uniswap, flash lending functionality ended up being available everywhere.

A flash loan allows you to borrow any amount of tokens available in a smart contract (usually a liquidity pool on a DEX or a loan pool) without posting any collateral as long as it is returned in the same transaction. By definition, this is only possible if another smart contract is used to execute the transaction, so the use of flash loans is reserved for developers specialized in this technology.

Thanks to flash loans, anyone with the necessary knowledge can have an almost unlimited amount of liquidity for their operations. The flash loan functionality was created with the aim of providing decentralized protocols with high liquidity and capital efficiency, allowing anyone to carry out large arbitrage operations without the need to have the required capital in advance, also generating extra income from fees to the protocols. However, this also opened the door to the possibility that anyone could carry out price gouging attacks on the blockchain.

### Countermeasures

The Geminon protocol incorporates several security measures intended to mitigate, prevent, or deter flash loan attacks against the protocol. Taken together, all of these measures make Geminon one of the most secure  protocols against flash loans created to date.

From the perspective of an attack aimed at minting a large amount of stablecoin using a flash loan, there are five overlapping security mechanisms:

* GEX Token Supply Limiter&#x20;
* Internal GLP Oracle
* Protocol oracle
* Stablecoin Supply Limiter
* GLP entropy capture

All these systems work together, so that depending on the state of the protocol and the characteristics of the attack, it will be more likely that one or more of them will intervene.

#### GEX Token Supply Limiter

Any attempt to manipulate the GEX token that involves artificially increasing its price will lead to the minting of a large number of GEX tokens on GLP. This instantaneous mass minting could trigger the token's supply cap, which is set at 5 million units per day on average. Activating the limiter implies that the attack transaction reverts, so it would not have any effect on the system. For more information on how this mechanism works, consult the dedicated section:

{% content-ref url="/pages/NH0wgiBW1kglvkOswWAs" %}
[Supply limiter](/tokens/gex/supply-limiter)
{% endcontent-ref %}

#### GLP internal oracle

GLPs incorporate an internal oracle developed by Geminon whose algorithm is immune to price manipulation using flash loans.

{% content-ref url="/pages/xlvC6nmCjsIHcik5rcur" %}
[Internal oracle](/modules/genesis-liquidity-pools/internal-oracle)
{% endcontent-ref %}

#### Protocol oracle

The Geminon oracle contract acts as a coordinator for the rest of the protocol contracts. One of its functions is to aggregate the data from the oracles of each of the GLPs in the network, providing a secure price for the GEX token that is the average of the internal oracles of each GLP. This is an additional layer of security to the internal oracles of each pool, which enhances the effect of the rest of the security systems:

* Increases the probability that the GEX token supply limiter will be activated, since to achieve the same variation in the average price of the n pools in the network, it is necessary to mint n times more GEX tokens than if it were a single pool.
* Enhances the effectiveness of the internal GLP oracle, adding a third layer of smoothing to one-off price changes.
* Enhances the entropy capture of the GLPs, multiplying the cost and potential losses for the attacker trying to manipulate the price.

#### Stablecoin Supply Limiter

All Geminon stablecoins incorporate a supply limiter like the one used by the GEX token. This system would be the last to intervene in the event of an attack, and although it can also cause the transactions of the attack to revert, it is considered more of a mechanism to mitigate the scope of the attacks by limiting the possible impact on the protocol balances.

#### GLP entropy capture

It is one of the most effective protection systems in the pool, since it makes operations with a high impact on the price irreversible. In the case of flash loans, this means that the transaction will revert when the full amount of the loan cannot be repaid, and in spot attacks it will make the operation unprofitable for the attacker. This effect is discussed in detail in the next section.

### Simulations

Given the importance of ensuring the security of the protocol against price manipulation attacks, the Geminon team carried out simulations of the behavior of the internal oracle of a GLP against different attack patterns using flash lending. The simulations empirically confirmed the expected behavior of the protocol design.

#### Settings

For the simulations, a single isolated pool was used, so the synergies of using several pools and the master oracle of the protocol are not taken into account. A series of 100,000 trades with a random amount and interval were simulated, generating constant long-term growth in the size of the pool, and for every 10,000 legitimate trades a manipulation attack was introduced with a random amount between $1 million and $1 billion, so that attacks were tested on all pool liquidity regimes. Both simple attack patterns were tested, as well as attacks with multiple operations that sought to deceive the internal oracle of the pool to make it reflect the manipulated price.

#### Results

* In more than 50% of the simulated attacks, the transaction was reversed because the GEX token mint limiter was triggered in the first instance. In a multi-pool environment, this percentage would have been even higher.
* No attack pattern managed to manipulate the secure pool price within the same block, implying that no flash loan attack would have been effective against the protocol, even with only one GLP running on the network. The following figure shows the pool price sequence during one of the simulated attacks. You can see how the attack produces an instantaneous spike in the raw pool price, while the oracle instantaneous price perfectly filters the attack and the safe price remains unchanged until it ends. It can also be seen how during normal operations before and after the attack, the oracle faithfully reflects the exact price of the pool without delay.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2FifYFKRIG3vsnrVRz8uGo%2FFlashloan%20prices.png?alt=media&amp;token=2e719e6c-2148-486c-916c-02409d75e299" alt=""><figcaption><p>Pool price sequence during a flash loan attack. Raw price and oracle prices.</p></figcaption></figure>

* In the case of spot attacks, with a duration longer than one block, the final price of the pool ended up being higher because the pool captured a significant percentage of the collateral deposited by the attacker, making the attack not only unsuccessful but also produce benefits for the protocol. In the case of flash loans, the transactions would have been reverted due to the impossibility of repaying the entire loan at the end of the transaction. The following figure shows the attacker's balance variation during the flash loan. It can be seen that it ends up with a lower balance than the initial one, without counting the fees.

<figure><img src="https://59440869-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyLNwJGvR0O66g51S3pdB%2Fuploads%2F0hHJF1RJoos8Zg1TgFqW%2FFlashloan%20balances.png?alt=media&amp;token=b9ee6319-de77-4000-afb8-303d5ea4e25d" alt=""><figcaption><p>Sequence of the attacker's balance during a flash loan. Pool entropy capture.</p></figcaption></figure>


# Safety protocols

In addition to protection against external attacks, the Geminon protocol contracts incorporate protection against internal attacks, which are attacks that could be carried out by a malicious team member or an attacker who gains control of the protocol keys. All the administrative functions of the GLP whose malicious use may have an impact on the funds held by the contract, are protected with additional security systems.

### Parameter changes

The basic parameters of a pool can only be changed by the contract owner. The functions involved have some additional security mechanisms:

#### Minting and redemption fees (setMintFee() / setRedeemFee())

Allows you to change the base commission that the pool charges users. Malicious access to these functions does not present significant risks, so the only additional security measure is that their maximum value is limited to 0.5%.

#### Pool weight (setPoolWeight())

Allows you to change the target weight of the pool, which influences the weight ratio which is a component of the token mint and burn ratios. Malicious use of the feature would not have a significant impact. It incorporates several additional checks:

* The new weight cannot be zero.
* The weight cannot be increased if migration or deletion of the pool has been requested.
* The difference between the new objective and the previous one cannot be greater than 5%.
* The difference between the new target and the current pool weight cannot be greater than 10%.

### Infrastructure changes

The infrastructure of a pool is made up of other Geminon or external protocol contracts with which the pool interacts for its operation. Only the owner can access these features, but since these are important features, they all have security timelocks.

The contract change timelock system requires two steps: a first transaction in which the contract address change request is made and the new contract address is specified using the requestAddressChange() function, which starts the counter of the lock time, and a second transaction that verifies that the lock time has elapsed (several days or weeks) and applies the changes. The contract owner can cancel the request at that time. This system guarantees that all changes are public and the characteristics of the new contracts can be observed before they become operational.

#### Change the price feed (applyPriceFeedChange())

The price feeder is a contract on the Chainlink network that provides the price of the collateral in dollars. This price is used informatively for user transactions and in calculating the relative weights of the pools, which in turn influence the token minting and burning ratios. An unauthorized change would have a moderate impact on the protocol, although it would not put user funds at risk, so an intermediate lock is used.

Protected by a timelock of 7 days.

#### Change the stablecoin minter (applySCMinterChange())

The stablecoin minter can ask for GEX even GLP tokens if they run out of liquidity to service stablecoin redemptions. Although the redemption function is protected (see below), it is considered that the introduction of a malicious contract in the role of minting stablecoins would present a high risk to the funds of a LPG, so a long block is used.

Protected by a 30-day timelock.

#### Oracle Change (applyOracleChange())

The protocol oracle (not to be confused with the pool's internal oracle) performs important functions in the management and coordination of the different protocol contracts. It is also involved in certain security checks, as well as providing GEX token prices to other contracts. It is considered a critical function of the protocol, so a long lock is used.

Protected by a 30-day timelock.

#### Change the lender contract (applyLenderChange())

The protocol was designed with the idea that the loan agreement (still under development) could partially utilize the LPG funds increasing the capital efficiency of the protocol. For this reason, a function was left enabled that would allow these loans to be made. Previously, it is necessary to register the address of the loan contract in the GLP. This function is considered critical to the security of the protocol, so a long lock is used.

Protected by a 30-day timelock.

### Migration / removal of the pool

Geminon pools do not use liquidity providers, so all liquidity is owned by the protocol and cannot be withdrawn. However, there could be situations in the future where it is necessary to change the liquidity to a new contract: discovery of vulnerabilities, updates to the protocol, changes in accepted collateral, etc. To cover these eventualities, procedures were designed that allowed collateral to be moved to a new pool (migration) or manually withdrawn (elimination). Both procedures are obviously critical from the perspective of the security of the funds and are therefore protected by the most complex security procedures in the entire protocol. The processes are slightly different for each:

#### Migration

The migration procedure requires three steps:

1. Request the pool address change in the oracle contract with the requestAddressChange() function, which initiates a 7-day temporary block.
2. Request in the pool contract to start the migration procedure with the requestMigration() function. This initiates a 30-day timelock. Additionally, several requirements must be met in order to execute the function:&#x20;
   * There can be no other pool migration or removal requested, neither from the target pool nor from another pool on the network.&#x20;
   * The Geminon oracle address cannot be null, the pool must have been connected to the protocol oracle.&#x20;
   * At least 30 days must have passed since the pool was connected to the oracle.&#x20;
   * The pool migration request must be registered in the oracle from 7 days before.&#x20;
   * The target weight of the pool has to be set below 5%.&#x20;
   * The current weight of the pool's collateral in the network must be less than 5%.&#x20;
   * Minting of GEX tokens in the pool is paused and cannot be resumed if the deletion request is not cancelled.
3. Perform pool migration using the migratePool() function. This function performs several additional checks:&#x20;
   * The pool migration must be requested in the pool for at least 30 days.&#x20;
   * The pool migration must be requested in the oracle contract.&#x20;
   * The Geminon oracle address cannot be null, the pool must have been connected to the protocol oracle.&#x20;
   * At least 60 days must have passed since the pool was connected to the oracle.&#x20;
   * The target weight of the pool has to be set below 2%.&#x20;
   * The current weight of the pool's collateral in the network must be less than 2%.

The migration procedure automatically transfers all collateral and GEX tokens contained in the migrated pool to the new pool. In this procedure, the funds are managed internally by the protocol contracts.

#### Removal

The removal procedure requires three steps, and is more restrictive than the migration procedure in terms of maximum collateral weights required. The rest of the requirements are identical:

1. Request the pool address change in the oracle contract with the requestRemoveAddress() function, which initiates a 7-day temporary block.
2. Request in the pool contract to start the migration procedure with the requestRemove() function. This initiates a 30-day timelock. Additionally, several requirements must be met in order to execute the function:&#x20;
   * There can be no other pool migration or removal requested, neither from the target pool nor from another pool on the network.&#x20;
   * The Geminon oracle address cannot be null, the pool must have been connected to the protocol oracle.&#x20;
   * At least 30 days must have passed since the pool was connected to the oracle.&#x20;
   * The pool migration request must be registered in the oracle from 7 days before.&#x20;
   * The target weight of the pool has to be set below 5%.&#x20;
   * The current weight of the pool's collateral in the network must be less than 5%.&#x20;
   * Minting of GEX tokens in the pool is paused and cannot be resumed if the deletion request is not cancelled.
3. Perform pool migration using the migratePool() function. This function performs several additional checks:&#x20;
   * The pool migration must be requested in the pool for at least 30 days.&#x20;
   * The pool migration must be requested in the oracle contract.&#x20;
   * The Geminon oracle address cannot be null, the pool must have been connected to the protocol oracle.&#x20;
   * At least 60 days must have passed since the pool was connected to the oracle.&#x20;
   * The target weight of the pool has to be set below 1%.&#x20;
   * The current weight of the pool's collateral in the network must be less than 1%.

Unlike migration, the pool deletion procedure transfers the remaining funds from the pool to the contract owner, who must manually convert them to another type of collateral and reintegrate them into another protocol pool. For this reason, the pool is required to contain less than 1% of all protocol collateral to allow for removal. Despite all security measures, this procedure requires trust and should not be carried out except in extreme circumstances.

### Protocol functions

#### Pause / resume minting (pauseMint() / unpauseMint())

These functions allow you to pause and resume the minting function of the GEX token in the pool. Token redemption cannot be paused. Only the owner can call these functions. The resume cannot be performed if pool migration or removal is requested.

#### Match Balances (matchBalances())

Allows you to make the internal GEX token and collateral balances of the pool match the balance of the respective tokens in the contract address of the pool. This function is used to recover mistakenly sent tokens directly to the contract. Only the owner can use the function. As an additional security measure to avoid sudden price variations, the function requires that the difference between the internal balance of the pool and the actual number of tokens that the address contains is less than 1%.

#### Bailout of the stablecoin minter (bailoutMinter())

This feature allows the minter contract to receive GEX tokens from the pool in case it does not have enough liquidity to redeem stablecoin from users. Since it reduces the balance of GEX tokens in the pool, it has the effect of increasing the price of the token. The function can be called manually by the contract owner, or it can be called automatically by the contract minter. For the transaction to not roll back, several conditions must be met:

* The SC Minter contract must be registered in the pool that receives the request.&#x20;
* The Geminon oracle must be registered in the pool for more than 30 days.&#x20;
* The SC Minter contract must be registered in the Geminon oracle for more than 7 days.&#x20;
* The minter's contract must have less than 5% of the GEX tokens in the pool balance.&#x20;
* The maximum amount that the pool can give up is 5% of its GEX token balance.

#### Collateral loan (lendCollateral())

This feature allows the loan contract to use a portion of the collateral from a pool to deliver an overcollateralized loan. The collateral of the loan must be a valid collateral of the LPG of the network, so that even in case of liquidation of the borrower the collateral can be returned to the pool. The function alone can be called by the loan contract, and requires many conditions:

* The loan contract must be registered in the pool that receives the request.&#x20;
* The Geminon oracle must be registered in the pool for more than 30 days.&#x20;
* The loan contract must be registered in the Geminon oracle for more than 7 days.&#x20;
* The SC Minter contract must be registered in the pool that receives the request.&#x20;
* Migration or removal of the pool may not have been requested.&#x20;
* The total cumulative value of the pool's loans cannot be greater than 5% of the total value of the GEX tokens locked in protocol contracts.&#x20;
* The maximum amount that the pool can cede is 25% of its collateral balance.

The most restrictive requirement is 5% of the value of GEX tokens locked in other contracts, usually in the stablecoins minter. This requirement will be the one that habitually limits the use of capital from the pools for loans.


# Stablecoins Minter

The SC Minter module is the main access point to Geminon's stablecoin and index offering. It allows users to exchange GEX tokens for one of the Geminon stablecoins, and vice versa.

The minting and redemption mechanism is algorithmic. The SC Minter contract always exchanges a value (measured in US dollars) of GEX tokens for the exact same stablecoin value and vice versa. There is no slippage in the operation, only the protocol commission is discounted.

### Minting protocol

In order to mint a new supply of stablecoin, it is necessary to hand over a number of GEX tokens, $$V\_G$$. The amount of minted stablecoin, $$V\_S$$, is given by the expression:

$$
V\_S = V\_G \dfrac {P\_G} {P\_S}
$$

The price of the GEX token, $$P\_G$$, is obtained from the protocol oracle as the average of the price in all the pools of the network.&#x20;

The stablecoin price, $$P\_S$$, is derived from the stablecoin contract being traded. All Geminon stablecoins and index coins have built-in functions in their contracts that allow obtaining their exchange value in US dollars. For more detailed information on how stablecoin prices are obtained, see the following pages:

{% content-ref url="/pages/gjpP5kbrKY7g84T7aooa" %}
[Stablecoins](/tokens/stablecoins)
{% endcontent-ref %}

{% content-ref url="/pages/ZEGM73MmCfRwVDJ8rvwc" %}
[Deflationary currencies](/tokens/deflationary-currencies)
{% endcontent-ref %}

#### Redeem

The process for redeeming stablecoin is identical to that for minting. A quantity of stablecoin, $$V\_S$$, is given in exchange for a quantity of GEX tokens, $$V\_G$$, which is calculated with the same expression used for minting:

$$
V\_G = V\_S \dfrac {P\_S} {P\_G}
$$

### Price manipulation attacks

The formulas described in the previous point for calculating the amounts of minted stablecoin depend directly on the values of the GEX token prices and the coin in question. This makes the contract vulnerable to changes in those prices. Price gouging attacks are the most common in blockchain-based decentralized finance protocols. For this reason, secure pricing sources that cannot be easily manipulated should always be used.

Geminon stablecoins are priced from the Chainlink oracle network, which is decentralized and takes data from external sources, so they are considered completely secure.

The price of the GEX token, on the other hand, depends on the state of the liquidity pools in the network, which is why it is susceptible to manipulation, especially through flash loans. The Geminon protocol incorporates security measures that prevent such price manipulations from being successful:

* The price of the GEX token is taken indirectly through the Geminon oracle, which uses the price of the pools at the close of the previous block. This means that flash loan attacks have no effect on the price, since the operations within the current block are not incorporated into the calculation.&#x20;
* The Geminon oracle calculates the price by taking the average of all the GLP. This increases the cost for the attacker, since it is necessary to simultaneously manipulate all the pools.&#x20;
* The GLPs incorporate an algorithm that filters operations with abnormal volume for the calculation of the reference price of the pool.&#x20;
* GLPs entropy capture feature heavily penalizes trades that produce excessive price slippage, making the attack economically unfeasible.

For more detailed information on LPG security mechanisms, consult the dedicated sections:

{% content-ref url="/pages/xlvC6nmCjsIHcik5rcur" %}
[Internal oracle](/modules/genesis-liquidity-pools/internal-oracle)
{% endcontent-ref %}

{% content-ref url="/pages/57q13O5ALzdnJnIcGkFm" %}
[Price manipulation attacks](/modules/genesis-liquidity-pools/price-manipulation-attacks)
{% endcontent-ref %}

### Internal security protocols

The SC Minter contract incorporates the same internal security mechanisms as the GLP contracts. For more detailed information, consult the previous section corresponding to GLP safety protocols.


# Decentralized Forex

The stablecoin exchange (ForDEX) module is integrated into the minting contract (SC Minter) and can be considered an extension of its functionality. Its function is to allow the exchange of any pair of Geminon stablecoins without price slippage.

The stablecoin exchange systems (stableswaps) that have implemented most protocols to date are based on liquidity pools. The system proposed by Geminon is completely different, since it does not use liquidity but is purely algorithmic: it takes advantage of the native capacity of the protocol to mint and burn coins, this being the reason why the Geminon Stableswap module has been integrated into the SC Minter contract. The system proposed by Geminon has several advantages over systems based on liquidity pools:

* It does not depend on the presence of external actors to function. An LP-based stableswap requires liquidity providers and arbitrageurs to keep the price of each traded pair close to its reference value, while our system works fully independently.&#x20;
* Better results in operations for users: the inefficiencies inherent in the existence of intermediaries (LPs and arbitrageurs) who obtain their benefit precisely from sliding prices are eliminated, at the expense of users. Our system always provides an exact price on exchanges regardless of the amount of the operation (infinite liquidity).&#x20;
* The implementation of the algorithmic solution is noticeably simpler, and therefore less prone to vulnerabilities.

## Oracle front running attacks

Geminon stablecoins use Chainlink oracles to obtain real-time prices against the dollar of the fiat currency that they replicate. However, due to the intrinsic characteristics of blockchain technology, there is a delay (lag) between the moment the price is observed in the market and the moment the data is written to the blockchain. This delay is the sum of the time it takes for the Chainlink network to reach consensus on the value of the price data, the time it takes for Chainlink to send the transaction to the destination blockchain with the new value, and the time that the network takes to process the transaction and include it in the next block. The total time that this process lasts can be more than a minute.

Due to the significant delay with which the oracle reflects on-chain prices, it is theoretically possible for an attacker to make a risk-free profit by trading an on-chain asset that is priced using this oracle, since it would only be necessary to observe the price of the asset in the real world to know in advance how its price will change on the blockchain in the immediate future (temporary arbitrage). The attack will only be economically viable if the cost of the operation (gas + commissions + slippage) is less than the expected price movement. Since our system does not slip, the attack threshold is lower and the amount is unlimited, so a security system has been designed to make this type of attack unfeasible.

### Probability of the attack

The Forex market is one of the least volatile in the world, especially when it comes to major pairs like EUR/USD, whose one-hour volatility rarely exceeds 0.3%. This low volatility means that the base commission usually charged by a decentralized exchange on the blockchain is higher than the expected profit of almost any intraday operation in the foreign exchange market, so the probability of this type of attack is generally quite low. , since it would also be unprofitable if successful. However, since the described attack is theoretically possible if there is enough volatility in the market, it is necessary to implement measures to ensure that it cannot be carried out under any circumstances.

### Stableswap Guard

The StableswapGuard contract implements a security system based on an internal price oracle that tracks global stablecoin positions taken in the last 5 minutes on both SC Minter and Stableswap. Every time an operation is carried out in stable currency, the contract checks if contrary positions have been opened in the last 5 minutes that produce an abnormal profit, and if so, it applies an extra security fee to the operation equal to the volatility of the period. between the opening and closing of the position, eliminating its possible profit.

{% hint style="warning" %}
Scalping on low timeframes using the Geminon Stableswap module is not recommended. When operating, always check the amount of the commission applied, and if it is higher than normal, wait a few minutes to carry out your operation.
{% endhint %}

### Internal oracle algorithm

The StableSwapGuard algorithm is similar to that used for the internal GLP oracle and for the Geminon token mint limiter. It is based on an adaptive exponential moving average whose parameter varies depending on the relationship between the volume of the current operation and the total volume accumulated in the last 5 minutes:

$$
\Delta t = t\_n - t\_{n-1}
$$

$$
V\_n = \begin{cases}
\ \ \ \ \ v\_n &\text{if } \Delta t > 300 \\
V\_{n-1}+v\_n &\text{if } \Delta t \le 300
\end{cases}
$$

$$
w\_n = \begin{cases}
\ \ \ \ \ 1 &\text{if } \Delta t > 300 \\
\dfrac {v\_n}{v\_n+V\_n} &\text{if } \Delta t \le 300
\end{cases}
$$

$$
m\_n = w\_n p\_n + (1-w\_n) m\_{n-1}
$$

Where $$\Delta t$$ is the time interval in seconds since the last trade, $$v\_n$$ is the volume (in US dollars) of the current trade, and $$p\_n$$ is the current price of the stablecoin (in US dollars).

The StableSwapGuard contract stores the previous amount for each stablecoin by separating buy trades and sell trades. To calculate the safety fee, the difference between the current price and the average value of the operations of the opposite sign is compared, and if said value is higher than the base fee, the safety fee is applied to the operation.


# Lending / borrowing

{% hint style="info" %}
The lending protocol is currently under development.
{% endhint %}


# Protocolo Geminon

Un protocolo de monedas estables de cuarta generación.

{% hint style="info" %}
El protocolo Geminon está obsoleto. Todos los contratos inteligentes se han pausado y el colateral se ha trasladado a bóvedas. Los poseedores de GEX pueden canjear sus tokens por la moneda nativa de la cadena de bloques donde se mantienen a precio constante. El equipo está trabajando en el desarrollo de Geminon v2. Consulte <https://geminonprotocol.medium.com/> para obtener más información.
{% endhint %}

## ¿Qué es Geminon?

Geminon es un protocolo de monedas estables multicadena. Actualmente está desplegado en las redes Ethereum, BNB Chain y Avalanche. Permite a los usuarios acuñar, intercambiar y canjear tanto monedas deflacionarias vinculadas a los índices del IPC de diferentes países como también monedas estables vinculadas a una ampia gama de monedas fiat.&#x20;

La primera versión del protocolo incluye varios servicios DeFi asociados a las monedas estables, como un intercambio de divisas descentralizado (ForDEX) de deslizamiento cero, préstamo de criptoactivos y monedas estables y también un puente multicadena.&#x20;

El protocolo de monedas estables de Geminon tiene un diseño único que combina la colateralización con una capa intermedia algorítmica que amortigua la volatilidad del colateral. Este novedoso diseño combina las ventajas de las monedas estables algorítmicas y las colateralizadas, al tiempo que elimina o reduce sus inconvenientes.

## ¿Cómo funciona?

Geminon tiene 4 módulos principales:

### Pools de Liquidez Génesis (GLP)

Los GLP son el punto de entrada principal al protocolo Geminon. Permiten a los usuarios obtener tokens GEX a cambio de depositar otros criptoactivos como colateral. Para saber más acerca de qué activos son aceptados como colateral y cómo funcionan en detalle los GLP, visite los siguientes apartados:

{% content-ref url="/pages/kDjc63cl5B7Oxa3JPkhL" %}
[Colateral](/geminon-docs-esp/protocolo-geminon/colateral)
{% endcontent-ref %}

{% content-ref url="/pages/3JHqVL3XWHWk1hqwUb08" %}
[Pools de Liquidez Génesis (GLP)](/geminon-docs-esp/modulos/pools-de-liquidez-genesis-glp)
{% endcontent-ref %}

### Acuñador de monedas estables (SC Minter)

Es el punto de acceso principal a las monedas estables de Geminon. Es un módulo algorítmico que permite canjear tokens GEX por monedas estables a su precio de referencia exacto y viceversa.&#x20;

{% content-ref url="/pages/BzWQuGCDOtWxsoDeItq6" %}
[Acuñador de Monedas Estables (SC Minter)](/geminon-docs-esp/modulos/acunador-de-monedas-estables-sc-minter)
{% endcontent-ref %}

### Intercambio de monedas estables (StableSwap)

Permite intercambiar directamente cualquier par de monedas estables o indexadas a la inflación del protocolo Geminon sin deslizamiento.&#x20;

{% content-ref url="/pages/fcYyj0JPiZHaeTQjTha8" %}
[Intercambio Forex Descentralizado](/geminon-docs-esp/modulos/intercambio-forex-descentralizado)
{% endcontent-ref %}

### Préstamos

Usando este módulo los usuarios pueden depositar criptoactivos para obtener intereses o pedirlos en préstamo depositando colateral y pagando un interés. Este módulo se encuentra actualmente en desarrollo.

{% content-ref url="/pages/rm9X9gTVtRpuXhDC62ep" %}
[Préstamos](/geminon-docs-esp/modulos/prestamos)
{% endcontent-ref %}


# Introducción

Bitcoin fue diseñado en 2008 como un sistema de pago electrónico para permitir a las personas realizar transacciones directamente entre sí sin la necesidad de un tercero de confianza, es decir, un dinero descentralizado para Internet.&#x20;

El diseño económico de Bitcoin con un suministro fijo lo convierte en una buena reserva de valor a largo plazo. Sin embargo, esta oferta inelástica hace que su precio sea extremadamente volátil en el corto plazo, haciendo inapropiado su uso como moneda. Esto ha llevado a la creación de las denominadas monedas estables, diseñadas para mantener una vinculación con alguna moneda fiduciaria, siendo la más común el dólar estadounidense.

### Tipos de moneda estable

Los primeros intentos de crear monedas estables datan de 2012 (Mastercoin). Tether, el mayor emisor de monedas estables en la actualidad, se creó en 2014. El número de monedas estables que existen hoy en día se cuenta por decenas.

En los últimos años, se han propuesto varias taxonomías en función del tipo de colateral utilizado, el objetivo de vinculación y el mecanismo tecnológico. Sin ser demasiado estrictos con la clasificación, es comúnmente aceptado que existen tres tipos principales de monedas estables:

* **Centralizadas**: Las características comunes que comparten todas las monedas de este grupo es que son emitidas por una empresa tradicional que mantiene reservas, en moneda fiduciaria y otros activos de liquidez equivalente (como letras del Tesoro), por un valor igual o superior al valor nominal de las monedas estables emitidas, y que todas son **censurables**, es decir, incorporan funciones de lista negra en sus contratos inteligentes que permiten al emisor incautar los bienes de cualquier usuario a voluntad. Ejemplos de este tipo son el USDT de Tether, el USDC de Circle y el BUSD de Paxos.&#x20;
* **Algorítmicas**: Bajo esta categoría se encuentran aquellos protocolos que no utilizan ninguna fuente de valor externa al propio protocolo para mantener la paridad de su moneda estable, por lo que desde una perspectiva más formal se denominan monedas estables de **colateral endógeno**, en el caso de que utilicen un sistema de **acciones de señoreaje**, o monedas estables de **colateral implícito**, si utilizan un sistema de **rebase** o **bonos**. Se pueden encontrar ejemplos de este tipo de monedas estables en Ampleforth (AMPL), Neutrino (USDN), Haven (xUSD), Beanstalk (BEAN) y el infame UST de Terra.&#x20;
* **Colateralizadas**: esta categoría incluye todas las monedas estables que utilizan fuentes externas de valor como garantía. Estas fuentes pueden ser estables (por lo general, otras monedas estables centralizadas), flotantes (otros criptoactivos) o mixtas, y dependiendo de la proporción de valor requerida para acuñarlas, pueden estar **sobrecolateralizadas** o **justamente colateralizadas**. Algunas se emiten en forma de deuda, por lo que el emisor paga intereses al protocolo por la moneda acuñada. Los ejemplos más conocidos de esta categoría son el DAI de Maker, FRAX, Liquity (LUSD), Magic Internet Money (MIM) y FEI.&#x20;

Es importante tener en cuenta que, en un sentido amplio, todas las monedas estables son colateralizadas, ya que todas necesitan una fuente de valor para mantener un precio estable. La única diferencia real entre ellas radica por tanto en la **naturaleza de esa fuente de valor**.

### La fuente de valor de las monedas estables de Geminon

Si se toma estrictamente la clasificación anterior, el protocolo Geminon entraría en la categoría de algorítmico, ya que sus monedas estables se acuñan únicamente a partir de un activo interno, el token GEX. Sin embargo, esto sería inexacto ya que el token GEX no es la fuente real de valor en el protocolo.

La razón es que el token GEX actúa como proxy de la verdadera fuente de valor en el sistema, que es la garantía depositada en los GLP. Esta configuración es necesaria ya que, de lo contrario, no sería posible utilizar colateral flotante para las monedas estables sin sobrecolateralizar fuertemente el protocolo para absorber su volatilidad.

Actualmente no existe ningún otro protocolo que utilice este mecanismo de estabilidad, a pesar de que combina las ventajas de los sistemas algorítmicos y colateralizados, eliminando o reduciendo sus inconvenientes:

* Brinda a los titulares de tokens GEX una exposición directa a la emisión de monedas estables, que es la principal ventaja de los protocolos algorítmicos basados en acciones de señoreaje.
* Tiene escalabilidad ilimitada. La falta de escalabilidad es el principal problema que plantean las monedas estables sobrecolateralizadas.
* Está más descentralizado que la mayoría de las monedas estables colateralizadas o sobrecolateralizadas, ya que tiene una menor necesidad de incluir activos foráneos a la cadena de bloques para mantener el ancla de precios.
* Es capaz de mantener la vinculación en cualquier condición de mercado con la misma eficacia que las monedas estables centralizadas, evitando el riesgo de una “espiral de la muerte” de las monedas estables algorítmicas.

El sistema propuesto por el protocolo Geminon tiene por lo tanto un mejor equilibrio entre descentralización, seguridad y escalabilidad que cualquier otra moneda estable existente.

Algunos podrían argumentar que el esquema propuesto es equivalente al uso directo del colateral para la emisión de monedas estables y, como consecuencia, el sistema podría colapsar en el momento en que la capitalización total de las garantías fuera menor que la de las monedas estables emitidas, haciendo que el valor del token GEX y el de las monedas estables emitidas a partir de él cayeran a casi cero, como sucedió con el UST de Terra.

Todas las simulaciones realizadas del comportamiento a largo plazo del protocolo, sin embargo, contradicen esta teoría: para todas las configuraciones estacionarias con operaciones aleatorias en las que se devuelve cíclicamente a los GLP todo el suministro de tokens GEX, el precio final del token después de 1 millón de operaciones es siempre mayor que el inicial en al menos un orden de magnitud. Este efecto no puede deberse a las comisiones, ya que la cantidad de colateral residual en los pools también es mayor y al desactivar estas se obtienen los mismos resultados. Tal comportamiento no sería posible a menos que existiera otra fuente de valor en el protocolo distinta del colateral.

### Los Pools de Liquidez Génesis como fuente de valor

Los GLP constituyen un mecanismo algorítmico de colateralización implícita.

En todos los sistemas de trading existentes, ya sea un broker de acciones o de futuros, un intercambio de criptomonedas o un intercambio descentralizado (DEX), cada vez que se realiza una transacción hay un impacto en el precio, llamado deslizamiento. Podemos pensar en este deslizamiento como la entropía creada por la acción de negociar, y es una pérdida que sufre el operador a favor del creador de mercado que le da contrapartida. En el caso del pool de liquidez de un DEX, ese creador de mercado es el proveedor de liquidez.

En los GLP de Geminon, sin embargo, no hay proveedores de liquidez. En su lugar, es el propio GLP el que genera nueva liquidez cada vez que alguien agrega colateral (de ahí el nombre de Liquidez Génesis). Esto significa que todo el valor que normalmente capturan esos proveedores de liquidez (la entropía) se retiene dentro del GLP y se refleja en el valor a largo plazo del token GEX. Y esto es lo que muestran todas las simulaciones del protocolo: cuanto más se intercambia el token GEX en un GLP, mayor es su valor terminal, independientemente de la dirección de los intercambios.

Los GLP son una forma de pools de arranque de liquidez (LBP) y también pueden ser vistos como máquinas de captura de entropía (ECM). Son la pieza clave en el funcionamiento del protocolo Geminon, y muy especialmente en su sistema de generación de valor. Puede leer más en detalle sobre ellos en el capítulo dedicado.

{% content-ref url="/pages/3JHqVL3XWHWk1hqwUb08" %}
[Pools de Liquidez Génesis (GLP)](/geminon-docs-esp/modulos/pools-de-liquidez-genesis-glp)
{% endcontent-ref %}


# Colateral

El token GEX está totalmente colateralizado con oro, Bitcoin, Ethereum, BNB y AVAX. Se ha seleccionado a *Paxos Gold* y *Tether Gold* como proveedores para el oro tokenizado, *Ren Bitcoin* para la versión envuelta de Bitcoin en Ethereum y BSC, y *Bitcoin Avalanche Bridged* en la red Avalanche. El peso y la dirección de cada token colateral es:

### Red Ethereum (60%)

* 20% Pax Gold (PAXG): 0x45804880De22913dAFE09f4980848ECE6EcbAf78
* 20% Tether Gold (XAUT): 0x68749665FF8D2d112Fa859AA293F07A622782F38
* 10% Ren Bitcoin (RENBTC): 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D <mark style="color:red;">(obsoleto)</mark>
* 10% Ethereum (ETH)

### BNB Smart Chain (20%)

* 10% Ren Bitcoin (RENBTC): 0xfCe146bF3146100cfe5dB4129cf6C82b0eF4Ad8c <mark style="color:red;">(obsoleto)</mark>
* 10% BNB (BNB)

### Avalanche (20%)

* 10% Bitcoin Avalanche Bridged (BTC.B): 0x152b9d0FdC40C096757F570A51E494bd4b943E50&#x20;
* 10% Avalanche (AVAX)

{% hint style="warning" %}
Debido a la caída del protocolo REN en diciembre de 2022, los pools de Ren BTC en las redes Ethereum y BNB Chain han sido retirados del servicio y el colateral correspondiente transferido a otros pools, por lo que el único pool de BTC activo está en la red Avalanche.
{% endhint %}


# Direcciones de despliegue

Geminon es un protocolo multicadena nativo, lo que significa que todos sus contratos inteligentes y funcionalidades están disponibles en varias cadenas de bloques simultáneamente.&#x20;

El protocolo ha sido implementado inicialmente en Ethereum, BNB Chain y Avalanche. El despliegue se ha realizado de forma que las direcciones de cada token y módulos coincidan en todas las cadenas siempre que sea posible. La única excepción son los Pools de Liquidez Génesis de Pax Gold y Tether Gold, que solo están disponibles en la red Ethereum.&#x20;

El código de todos los contratos inteligentes enumerados aquí es público y está verificado.

### Desplegador (owner)

El desplegador de los contratos inteligentes es el propietario y, por lo tanto, es la única dirección que puede usar ciertas funciones en los contratos, algunas de las cuales son críticas para la seguridad del protocolo. Consulte la sección de consejos de seguridad para obtener más información al respecto.

La dirección es la misma en todas las redes:

* 0x88d70DEBB940E0bEE526981D99B0f3000E0a3268

{% content-ref url="/pages/KJKIscdpScpUCvb0BTVR" %}
[Consejos de seguridad](/geminon-docs-esp/consejos-de-seguridad)
{% endcontent-ref %}


# Tokens

## Token GEX

La dirección del token Geminon es la misma en Ethereum, BSC y Avalanche:

* 0x2743Bb6962fb1D7d13C056476F3Bc331D7C3E112

## Monedas estables indexadas a la inflación

### USDI

Dólar indexado a la inflación en EEUU

* 0x4C24e67DC2a00AdA5E90C1E284d2EE4260A21E05

Faro del índice: contrato que calcula el valor de referencia del índice de inflación

* 0x31ac1cc4f770501AdE10E252A6AE27F36D4469Fa

### EURI

Euro indexado a la inflación en la Eurozona

* 0xcbB00E1f27a59735f390F3263d335A112f10Db8b

Faro del índice: contrato que calcula el valor de referencia del índice de inflación

* 0x842b95dc806745a2B1e0C99a39e0BcF60eC7Ecc2

## Monedas estables

### USDG

Dólar EEUU de Geminon

* 0x825B116b431c441C8f5eC19abC069adbd0a169cF

### EURG

Euro de Geminon

* 0x38f8058b4dF45E8451d10f40343DBAaeCAE620cF

### CNYG

Renminbi yuan chino de Geminon

* 0x52644C661Bd2436C0a620Cf11b617276b8c7C2D1

### JPYG

Yen japonés de Geminon

* 0x9eCA773DE915a76D5aD25D3995F10dd5532022b2


# Módulos

Contratos que contienen las funcionalidades principales del protocolo

## Pools de Liquidez Génesis

La dirección del pool del activo nativo y del de bitcoins en cada red es la misma. Los pools de PAXG y XAUT son únicos en Ethereum.

#### Ethereum

* ETH-GEX pool: 0xA4df7a003303552AcDdF550A0A65818c4A218315 <mark style="color:red;">(obsoleto)</mark>
* RENBTC-GEX pool: 0x5ae76CbAedf4E0F710C2b429890B4cCC0737104D <mark style="color:red;">(obsoleto)</mark>
* PAXG-GEX pool: 0x48A814C44beeFE3A1C7c165367c1Ea12eA599b48 <mark style="color:red;">(obsoleto)</mark>
* XAUT-GEX pool: 0xE7e708277A03dA75186C231b5B43FcFB34BEd29B <mark style="color:red;">(obsoleto)</mark>

#### BNB Smart Chain

* BNB-GEX pool: 0xA4df7a003303552AcDdF550A0A65818c4A218315 <mark style="color:red;">(obsoleto)</mark>
* RENBTC-GEX pool: 0x5ae76CbAedf4E0F710C2b429890B4cCC0737104D <mark style="color:red;">(obsoleto)</mark>

#### Avalanche

* AVAX-GEX pool: 0xA4df7a003303552AcDdF550A0A65818c4A218315 <mark style="color:red;">(obsoleto)</mark>
* BTC.B-GEX pool: 0x5ae76CbAedf4E0F710C2b429890B4cCC0737104D <mark style="color:red;">(obsoleto)</mark>

## Acuñador de moneda estable

La dirección del acuñador es la misma en todas las redes.

* 0xeF0dfe8cF872B4dF3681Ad37A17Ef5e2D473B877 <mark style="color:red;">(obsoleto)</mark>

## Oráculo

La dirección del oráculo es la misma en todas las redes. Primera versión (obsoleta):

* 0x2208C74e717df65E367A7dB03B8675627D31ac31 <mark style="color:red;">(obsoleto)</mark>

Segunda versión del oráculo (actualmente en uso):

* 0xa7d3d2bAd28fd928b72283E8a96f6E8D5c5D94e2 <mark style="color:red;">(obsoleto)</mark>

## Puente entre cadenas

La dirección del puente es la misma en todas las redes. Primera versión (en pruebas, no abierto al público)

* 0xC783565D32517DCC80d0aAA44580ef92dAd224e3 <mark style="color:red;">(obsoleto)</mark>

## Bóveda

La dirección de la bóveda es la misma en todas las redes.

* 0x4606887be86edF5bD47eEEAa0851864d9A70B07B


# Acerca de

Estos son los impulsores a largo plazo de Geminon. Lograr estos objetivos probablemente requerirá múltiples iteraciones del protocolo.

### Objetivo

El objetivo de Geminon es convertirse en uno de los 5 principales proveedores de monedas estables para el mercado cripto en los próximos dos años.

### Misión

La misión de Geminon es crear la moneda estable con el mejor equilibrio posible entre descentralización, seguridad y escalabilidad.

### Visión

En su forma final, el protocolo Geminon debería tener estas características:

* Inmutabilidad. El equipo de desarrollo debería poder renunciar a la propiedad de los contratos inteligentes con la seguridad de que estos pueden funcionar indefinidamente sin intervención humana.&#x20;
* Independencia. El protocolo debería poder funcionar con poca o ninguna dependencia de oráculos y protocolos externos.&#x20;
* Descentralización total. El colateral procedente de emisores centralizados debe eliminarse por completo.&#x20;
* Redundancia. El número de capas de colateral y sistemas algorítmicos para mantener la paridad debe ser lo más variado posible.&#x20;
* Sostenibilidad. Todas las primitivas de seguridad de protocolo deberían mantenerse e incluso crecer por sí solas con el tiempo.

### Equipo

Geminon está construido por un equipo anónimo, siguiendo los principios fundacionales de Bitcoin y el liderazgo de Satoshi Nakamoto. La privacidad es uno de los valores fundamentales de Geminon, y eso comienza con el propio equipo. Un proyecto criptográfico no puede ser realmente descentralizado ni seguro si las personas que controlan las claves del protocolo pueden verse amenazadas y obligadas a cerrar el proyecto en contra de su voluntad.&#x20;

Un equipo público nunca ha sido garantía de nada, ya que las mayores estafas siempre las han cometido personas reconocibles precisamente para ganarse la confianza del público. Por eso Geminon también prefiere seguir otro de los principios fundamentales de la criptografía: que un proyecto debe ser libre de confianza.

> ***"No confíes en nosotros: confía en nuestro código."***


# Comisiones

Detalle de las tarifas de uso del protocolo Geminon

Geminon utiliza un sistema de comisiones variables de diseño propio. Nuestros contratos aplican un sistema de tarifas progresivas que aumentan con el tamaño de la operación realizada (se paga una comisión mayor cuanto más grande es el importe), con un doble propósito:

* Hacer más equitativos los costes operativos para los usuarios. En redes como Ethereum con un alto precio del gas, los pequeños usuarios sufren en sus operaciones un impacto mucho mayor debido al coste de transacción de la red. El sistema de comisiones variables de Geminon hace que las transacciones pequeñas (<1000$) paguen solo una pequeña tarifa básica, mientras que las grandes operaciones pagan tarifas mayores, lo cual compensa en parte el efecto del coste del gas sin perjudicar los ingresos del protocolo.
* Desincentivar el flujo tóxico de órdenes. En todo sistema que realiza operaciones financieras, las grandes órdenes (en relación a la liquidez disponible) suelen tener efectos perjudiciales para el sistema. El algoritmo de liquidez de los GLP penaliza este tipo de órdenes y el sistema de comisiones variables lo refuerza y extiende al resto de módulos del protocolo.&#x20;

### Tramos de comisión variable

La comisión total cobrada se calcula sumando a la tarifa de base (que es un parámetro configurable de los contratos inteligentes) la parte variable (inmutable). Esta última se calcula por interpolación lineal según los siguientes tramos:

* Por debajo de 1000$: no hay parte variable, se cobra solo la tarifa base.
* Entre 1.000$ - 10.000$: de 0% a 0,05% sobre la tarifa base.
* Entre 10.000$ - 100.000$: de 0,05% a 0,1% sobre la tarifa base.
* Entre 100.000$ - 1.000.000$: de 0,1% a 0,2% sobre la tarifa base.
* Más de 1.000.000$: 0,2% sobre la tarifa base.&#x20;

Por ejemplo, para una comisión base del 0,1%, la curva de comisiones en función del importe de la operación sería:

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2F1kcTKgoifslfjiBlXxHu%2FVariable%20fees.png?alt=media&amp;token=631dda20-44d5-4684-b80b-378070d9355d" alt=""><figcaption><p>Valor de la comisión por acuñar GEX en función del importe en dólares.</p></figcaption></figure>

## Reparto de comisiones

Al contrario de lo que sucede con otros proyectos descentralizados, no todas las comisiones generadas por el protocolo Geminon van destinadas a los poseedores del token sino que una parte  importante va al equipo de desarrollo. Esto es así por varios motivos:

* Dadas las características del proyecto, el equipo no se ha reservado ningún porcentaje del suministro ni tampoco se ha recibido financiación externa, por lo que la única vía de beneficios proviene de los márgenes operativos y no de la especulación, como sucede en cualquier negocio tradicional.
* Este sistema proporciona los incentivos económicos adecuados para que el equipo se mantenga comprometido con el proyecto a largo plazo.&#x20;
* Proporciona recursos al equipo que pueden ser reinvertidos en el desarrollo del proyecto generando crecimiento sostenible, no especulativo.

La proporción de las comisiones que recibe el equipo no está fijada sino que depende de qué funciones del protocolo sean más utilizadas por los usuarios, por lo que no se puede saber de antemano. En los siguientes puntos se explica en detalle este reparto.

### Pools de Liquidez Génesis (GLP)

Los GLP cargan una comisión cuando se acuña GEX depositando colateral y cuando se canjea GEX por colateral. El importe íntegro de las comisiones generadas en los GLP es para el equipo. La comisión se compone de una tarifa básica, que es un parámetro que puede modificar el equipo, y la parte variable que se calcula en función del importe de la operación. La comisión básica está fijada actualmente en 0,1% para acuñar GEX y 0,2% para canjearlo y no se puede fijar nunca por encima del 0,5%. La comisión variable oscila entre el 0 y el 0,2%.&#x20;

### Acuñador de Monedas Estables (SC Minter)

Carga una comisión por acuñar y canjear moneda estable. A diferencia de los GLP, el SC Minter sólo recauda para el equipo el importe de la comisión de base, que es un 0,1% para acuñar moneda estable y un 0,2% para canjearla. El importe de la comisión variable, que oscila entre el 0 y el 0,2%, lo perciben de forma indirecta los poseedores del token GEX.&#x20;

### Intercambio de Monedas Estables (StableSwap)

El intercambio de estables es el único módulo que no recauda comisiones para el equipo. El importe íntegro de las comisiones generadas lo perciben indirectamente los poseedores del token GEX. Se cobra una comisión en cada intercambio de moneda que consta de una parte fija, que depende del par intercambiado y que tiene que ser siempre mayor o igual a la suma de las comisiones de acuñación y canjeo del SC Minter (>= 0,3%), y una parte variable que depende del importe de la operación y oscila entre 0% y 0,2%.&#x20;

El módulo de intercambio de monedas estables implementa un sistema de seguridad para evitar ataques por adelantamiento del oráculo (front running) que cobra una comisión adicional (Safety Fee) si detecta este tipo de ataque para hacerlo económicamente inviable. Esta comisión se calcula automáticamente en función del beneficio esperado del atacante para suprimirlo y por tanto no tiene límite. Para más información lea la sección sobre el módulo Stableswap:

{% content-ref url="/pages/fcYyj0JPiZHaeTQjTha8" %}
[Intercambio Forex Descentralizado](/geminon-docs-esp/modulos/intercambio-forex-descentralizado)
{% endcontent-ref %}

### Tabla resumen

Esta tabla muestra el valor actual de las comisiones del protocolo. Estas tarifas pueden ser modificadas en cualquier momento por el equipo si las circunstancias del mercado lo requieren.&#x20;

| Módulo     | Función          | Comisión (base - máxima)   |
| ---------- | ---------------- | -------------------------- |
| GLP        | mintSwap         | 0,1% - 0,3%                |
| GLP        | redeemSwap       | 0,2% - 0,4%                |
| SC Minter  | mintStablecoin   | 0,1% - 0,3%                |
| SC Minter  | redeemStablecoin | 0,2% - 0,4%                |
| Stableswap | stableSwap       | 0,3% - 0,5% + Safety Fee\* |


# Comienzo rápido

La primera versión del protocolo permite usar la funcionalidad básica para acuñar tokens GEX y monedas estables.

### Comprar GEX

El token GEX solo se puede obtener mediante el depósito de colateral en uno de los Pools de Liquidez Génesis. Actualmente existen 5 tipos de activos que se aceptan como garantía: oro, Bitcoin y las monedas nativas de las blockchains en las que opera el protocolo (Ethereum, BNB y Avalanche).

#### Elija red y colateral

No todos los activos están disponibles en todas las redes (por ejemplo, el oro tokenizado solo existe en Ethereum), por lo que, según la red en la que desee operar, el tipo de garantía utilizable será diferente. Para ver información detallada de los tokens de colateral visite esta página:

{% content-ref url="/pages/kDjc63cl5B7Oxa3JPkhL" %}
[Colateral](/geminon-docs-esp/protocolo-geminon/colateral)
{% endcontent-ref %}

#### Compre colateral

Una vez que haya decidido qué tipo de colateral desea utilizar, busque qué intercambios o DEX negocian el activo para adquirirlo.

Si no conoce ninguno, puede utilizar un agregador como [*Coingecko*](https://www.coingecko.com/) o [*Coin Market Cap*](https://coinmarketcap.com/) para encontrar un lugar donde adquirir el colateral.

#### Suministre colateral a los pools de Geminon

El token GEX se puede adquirir utilizando los Pools de Liquidez Génesis del protocolo a través de nuestra aplicación: [https://app.geminon.fi](http://test.geminon.fi).

{% hint style="info" %}
Divida sus operaciones si espera que tengan un gran impacto en el precio del pool, esto le dará un mejor resultado que una sola operación grande.&#x20;

Este consejo solo es aplicable a los Pools de Liquidez Génesis de Geminon, ya que estos no siguen estrictamente una fórmula de AMM de producto constante (como los pools de Uniswap). Los GLP son técnicamente máquinas de captura de entropía, por lo que cuanta menos entropía (impacto en el precio) cause su operación en el pool, mejor resultado obtendrá.
{% endhint %}


# Consejos de seguridad

Los riesgos en un protocolo criptográfico pueden provenir tanto del exterior (hackers) como del interior (miembro malicioso del equipo o contraseñas comprometidas). Los atacantes externos pueden apuntar al protocolo (préstamos flash, ataques de reentrada...) o a los usuarios (phishing, suplantación de identidad de sitios web).&#x20;

El usuario no puede hacer nada para evitar ataques externos al protocolo (ese es el trabajo del equipo), pero sí puede hacer todo lo posible para evitar ataques que se dirijan hacia él y, si el protocolo está bien diseñado, también puede ayudar a prevenir ataques internos y minimizar sus consecuencias.&#x20;

Esta sección proporciona algunos consejos para una interacción más segura con el Protocolo Geminon.

### Vigile siempre las acciones de la dirección del desplegador

El desplegador de los contratos inteligentes es el propietario y por lo tanto es la única dirección que puede utilizar ciertas funciones en los contratos, algunas de las cuales son críticas para la seguridad del protocolo ya que su uso de forma maliciosa puede comprometer el valor de los tokens.&#x20;

Todas las funciones críticas del protocolo tienen cierres temporales implementados como medida de seguridad, ya que facilitan el control público de esas acciones.&#x20;

Por ello, la rendición pública de cuentas de la dirección del propietario es muy importante. Siempre revise periódicamente las acciones de esa dirección sobre los contratos inteligentes de protocolo en un explorador de blockchain y verifique que hayan sido anunciadas públicamente y que se hayan explicado claramente sus objetivos y motivaciones.&#x20;

Acciones que siempre deben ser anunciadas por el propietario:

* Agregar acuñador al token GEX o las monedas estables (bloqueo de tiempo de 7 días).
* Aplicar cambio del alimentador de precios de un GLP (bloqueo de tiempo de 7 días).&#x20;
* Aplicar cambio del Stablecoin Minter en un GLP (bloqueo de tiempo de 30 días).&#x20;
* Aplicar cambio de oráculo en un GLP (bloqueo de tiempo de 30 días).&#x20;
* Aplicar el cambio de prestamista del Tesoro en un GLP (bloqueo de tiempo de 30 días).
* Establecer el peso de un GLP, especialmente si es un peso inferior y esta acción se repite varias veces.&#x20;
* Solicitar la migración de un GLP (bloqueo de tiempo de 30 días + reducción del peso del pool a menos del 5 % antes y 2 % después + la acuñación se detiene en el pool).&#x20;
* Solicitar la eliminación de un GLP (bloqueo de tiempo de 30 días + reducción del peso del pool a menos del 5 % antes y un 1 % después, + la acuñación se detiene en el pool).

Puede encontrar la dirección del desplegador en la sección correspondiente:

{% content-ref url="/pages/astSBmKxXda9pD5Wjskt" %}
[Direcciones de despliegue](/geminon-docs-esp/protocolo-geminon/direcciones-de-despliegue)
{% endcontent-ref %}


# GEX

Token de utilidad del protocolo Geminon.

El token GEX es el principal punto de entrada a las aplicaciones de Geminon. Es necesario para acuñar y canjear monedas estables y pagar tarifas. En el futuro tendrá funcionalidades adicionales a medida que crezca el protocolo.&#x20;

Más allá de su utilidad para los usuarios, el token GEX es una pieza clave del protocolo Geminon, ya que su misión fundamental es amortiguar la volatilidad del colateral creando una respuesta lineal a los cambios en el nivel de este, lo que facilita la posterior creación de activos de respuesta nula del precio (estables) frente a cambios del colateral. Haciendo una analogía con el cálculo, se puede pensar en GEX como la primera derivada de una función de precio parabólica y en las monedas estables como la segunda derivada.

### Suministro inicial

No existe un suministro inicial de tokens: nadie, ni siquiera el equipo, tiene asignado un suministro en el momento del lanzamiento. La única forma de conseguir tokens GEX es depositar colateral en los Pools de Liquidez Génesis (minería de colateral). La cantidad de tokens en circulación y su distribución depende exclusivamente del libre mercado, el equipo no tiene ningún control sobre ello.&#x20;

### Control del suministro

Para cumplir su misión de amortiguar la volatilidad entre el colateral y las monedas estables, el token GEX debe tener un suministro elástico. El suministro está controlado por los Pools de Liquidez Génesis, a los que se les permite acuñar y quemar tokens. Cada vez que se agrega o retira colateral de un pool, se acuña o quema una cierta cantidad de tokens para garantizar que el suministro sea siempre proporcional a la cantidad de colateral.&#x20;

Aunque la oferta no está estrictamente limitada, el ratio de acuñación/quema de tokens tiene en cuenta un objetivo de oferta máxima de 100 millones de tokens, y cuando se supera ese valor, el ratio de acuñación se reduce al mínimo imprescindible para mantener la linealidad del precio frente a la cantidad de colateral.

### Control del peso del colateral

La composición del colateral inicial del token GEX es 40% oro, 30% bitcoin, y el 30% restante a partes iguales entre las monedas nativas de las blockchains en las que opera: 10% ETH, 10% BNB y 10% AVAX.

Dado que existen versiones descentralizadas de bitcoin tokenizado en las tres cadenas, se decidió además asignar el 10% de bitcoin a cada cadena. De esta forma, el peso de cada cadena en custodia del colateral es del 60% en Ethereum, 20% en BSC y 20% en Avalanche. Esta fue una elección de diseño, y la composición del colateral podría cambiarse en el futuro si fuera necesario para mejorar la seguridad del protocolo.

{% content-ref url="/pages/kDjc63cl5B7Oxa3JPkhL" %}
[Colateral](/geminon-docs-esp/protocolo-geminon/colateral)
{% endcontent-ref %}

Esta proporción de peso solo podría sostenerse por sí sola si los usuarios siempre intercambiaran GEX en los pools por esas proporciones de colateral exactas. Como esto es inviable, los GLP también se encargan de hacer cumplir que el peso de los pools se mantenga siempre en la proporción exacta.

Para lograr esto, se aplica un coeficiente a la tasa de suministro de cada grupo, lo que significa que la cantidad de tokens GEX acuñados/quemados es diferente dependiendo de si el valor del colateral del pool está por encima o por debajo de su valor objetivo.

Esta asimetría en las emisiones de cada pool crea oportunidades de arbitraje entre los pools que dan al mercado los incentivos necesarios para mantener automáticamente los pesos equilibrados.

### Limitador de acuñación

Una de las hipótesis de diseño de los contratos inteligentes de Geminon es que en cualquier momento cualquier contrato de protocolo o el propio propietario puede actuar de forma malintencionada. Siguiendo este principio, todas las funciones críticas del protocolo incorporan mecanismos de protección redundantes para protegerse no solo de ataques externos, sino también de ataques internos.

La parte más crítica del contrato de tokens GEX es la función de acuñación, que crea nuevo suministro de tokens. Para evitar que un atacante que obtenga acceso a esta función acumule una cantidad ilimitada de tokens y para reducir la probabilidad de ataques de préstamos instantáneos sobre el protocolo, el contrato incorpora un limitador de tasa de suministro automático. Este limitador de tasa utiliza un algoritmo desarrollado por Geminon que puede rastrear con mucha precisión la media móvil de 24 horas del suministro sin la necesidad de almacenar el valor de todos las operaciones (lo que haría que las transacciones fueran extremadamente costosas en términos de gas).

El suministro de GEX está limitado a un máximo de 5 millones de unidades por día, que es el 5 % del nivel de suministro objetivo del token. En el peor de los casos, el impacto de este tipo de ataque en el protocolo sería limitado y podría detenerse antes de que se produjera un daño significativo.

Para una información más detallada sobre el funcionamiento del algoritmo consulte la siguiente página:

{% content-ref url="/pages/n0ZiNDcvXHi9r3q5ft7G" %}
[Limitador de suministro](/geminon-docs-esp/tokens/gex/limitador-de-suministro)
{% endcontent-ref %}

### Cómo obtener tokens GEX

GEX es un token totalmente colateralizado y, por lo tanto, su suministro solo se puede acuñar agregando garantías a los Pools de Liquidez Génesis. Puede encontrar toda la información sobre cómo obtener tokens GEX en nuestra guía de inicio rápido:

{% content-ref url="/pages/JfXUWh8CWYCyjEAY0hcL" %}
[Comienzo rápido](/geminon-docs-esp/comienzo-rapido)
{% endcontent-ref %}


# Limitador de suministro

El contrato ERC20ElasticSupply es una extensión del estándar ERC20 que permite crear tokens con suministro elástico que pueden ser acuñados y quemados por otros contratos. Como medida de seguridad, el contrato incluye un limitador de acuñación cuyos parámetros quedan fijados por el constructor durante la creación del contrato del token.&#x20;

Tanto el token GEX como todas las monedas estables de Geminon incluyen este mecanismo de seguridad. Este sistema está pensado para los casos en los que se conceden permisos de acuñación de tokens de Geminon a contratos externos al protocolo, concretamente en el caso de puentes entre cadenas operados por terceras partes, ya que en caso de hackeo del puente se limita el daño posible al protocolo.&#x20;

### Algoritmo

El algoritmo, desarrollado por Geminon, se basa en un suavizado exponencial adaptativo cuyos parámetros $$w\_1$$ y $$w\_2$$ varían en función del intervalo $$\Delta t$$ transcurrido desde la última acuñación o quema del token.&#x20;

$$
\Delta t = t\_n - t\_{n-1}
$$

$$
\delta = \frac{86400}{\Delta t}
$$

$$
\alpha = \frac {2}{1+\delta}
$$

$$
w\_1 = \begin{cases}
\ \ \ 1 &\text{if } \Delta t = 0 \\
\alpha \cdot \delta &\text{if } \Delta t > 0
\end{cases}
$$

$$
w\_2 = \begin{cases}
\ \ \ \ 1 &\text{if } \Delta t = 0 \\
1-\alpha &\text{if } \Delta t > 0
\end{cases}
$$

$$
\lambda\_n = w\_1 v\_n + w\_2 \lambda\_{n-1}
$$

Donde $$\Delta t$$ es el intervalo de tiempo en segundos transcurrido desde la última operación y $$v\_n$$ es el volumen (número de tokens) que se quiere acuñar o quemar, en cuyo último caso tendrá valor negativo y se reducirá el valor de $$\lambda$$.

Nótese que el tiempo $$t$$ es una variable discreta definida por el momento de creación del bloque en el que se mina la transacción actual, por lo que aquellas transacciones minadas dentro de un mismo bloque tienen $$\Delta t = 0$$. En estos casos los pesos $$w\_1$$ y $$w\_2$$ toman valor 1 y el volumen de tokens de la transacción se suma directamente al acumulado hasta el momento.&#x20;

### Fundamentos

El algoritmo descrito está diseñado para aproximar mediante un cálculo mínimo el valor de una media móvil de periodo 24 horas calculada sobre una serie temporal discreta de frecuencia variable.&#x20;

En una aplicación informática tradicional, si deseamos monitorizar el valor acumulado de una variable discreta en un intervalo de tiempo determinado, lo que haríamos es crear una tabla que almacene cada valor de la variable junto con su marca de tiempo, y usar dicha tabla para calcular un promedio de todos los valores que estén dentro de la ventana de tiempo deseada, por ejemplo las últimas 24 horas.&#x20;

En una aplicación de blockchain sin embargo un cálculo básico como ese resultaría prohibitivo en coste. Primero, porque almacenar datos en blockchain, especialmente en una congestionada como Ethereum, es extremadamente caro. Y segundo, porque en cada transacción sería necesario iterar sobre las listas de valores y tiempos almacenados, con lo que la complejidad del cálculo y con ello el coste de la transacción crecería con el número de datos almacenados en el periodo.&#x20;

Esta aproximación no solo sería desproporcionadamente cara sino además peligrosa: dado un volumen de operaciones lo suficientemente alto, se podría alcanzar el límite de gas por bloque de la red, haciendo que las funciones de acuñación del token en cuestión quedaran temporalmente bloqueadas al revertir las transacciones que excedan dicho límite de gas. Un actor malicioso podría aprovechar esta vulnerabilidad para lanzar ataques de denegación de servicio contra el protocolo.&#x20;

Si tratáramos con una serie temporal uniforme, con los valores separados a intervalos regulares en el tiempo, se podría aproximar de forma sencilla la media móvil de periodo $$t$$ sin más que usar una media móvil exponencial equivalente con parámetro $$\alpha = 2/({1+t})$$. En este caso, dado que tampoco existe la posibilidad de imputar los valores faltantes para transformar la serie irregular en regular, la única opción pasa por la introducción de una variable $$\delta$$ que compensa la irregularidad en el domino de la frecuencia adaptando la intensidad del suavizado que se aplica a cada nuevo dato en función de cómo de alejado está de la frecuencia básica definida por el periodo de la media móvil que se trata de aproximar (86400 segundos en nuestro caso).&#x20;

### Eficacia del algoritmo

El algoritmo autorregresivo que ha diseñado Geminon es capaz de aproximar de forma óptima la curva de la media móvil calculada de forma explícita.&#x20;

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2FS3JEsrUoW93R8HfnbnKa%2FSupplyLimiterEchelon.png?alt=media&amp;token=f50f2cd3-7f02-4bc9-ae50-8d8180da0864" alt=""><figcaption><p>Respuesta del estimador (naranja) a una señal constante (azul). Valor real de la serie en verde.</p></figcaption></figure>

En una simulación simple introduciendo operaciones de importe constante a intervalos constantes para producir una función rampa en el valor de la media móvil, el aproximador es capaz de seguir la rampa y converge perfectamente al nuevo nivel sin necesidad de almacenar los valores de la serie.&#x20;

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2FjWpfvBXQ722lIphTqqyN%2FSupplyLimiterRandom.png?alt=media&amp;token=a4205e61-c9fc-46a9-8e06-c58575ad7738" alt=""><figcaption><p>Respuesta del estimador (naranja) a una señal aleatoria en amplitud y frecuencia (azul). Valor real de la serie en verde.</p></figcaption></figure>

En una prueba mucho más difícil, se introduce una serie de valores aleatorios a intervalos de tiempo también aleatorios. Como puede verse en la figura, el algoritmo diseñado por Geminon es capaz de seguir en todo momento el valor real de la media móvil a pesar de la fuerte aleatoriedad de la señal sin necesidad de almacenar los valores previos.&#x20;


# Monedas deflacionarias

Las monedas indexadas a la inflación son la razón de la existencia del protocolo Geminon. El diseño inicial del protocolo tuvo como objetivo crear una moneda estable de cuarta generación, con una combinación de escalabilidad, descentralización y seguridad superior a las alternativas existentes y que además fuera resistente a la pérdida de valor debida a la inflación.&#x20;

### Valor de referencia (peg)

A pesar de su nombre, las monedas indexadas de Geminon no replican a ningún índice, sino que utilizan como valor de referencia la predicción del valor de dicho índice para el próximo periodo. Este detalle es importante puesto que les permite situarse sobre la curva de inflación, en lugar de por detrás de la curva.&#x20;

#### Monotonía

Otra diferencia importante frente a un simple índice de inflación es que las monedas indexadas de Geminon están programadas para que su valor no pueda descender nunca frente a su moneda base: en los casos en que se produce deflación su valor queda fijo al de la moneda base en lugar de seguir la bajada del índice de inflación, por lo que en términos globales se obtiene una curva de valor monótona creciente, es decir, una moneda puramente deflacionaria.&#x20;

### Predicción del índice

El contrato PredictIndex implementa un sistema de predicción de series temporales basado en el modelo de tendencia lineal no estacional de Holt-Winters. En su forma recurrente, el modelo viene dado por dos ecuaciones para el suavizado de la serie y la tendencia:

$$
S\_n = \alpha X\_n + (1 - \alpha)(S\_{n-1} +
T\_{n-1})
$$

$$
T\_n = \gamma (S\_n - S\_{n-1}) + (1 - \gamma) T\_{n-1}
$$

Donde $$X$$ es la serie temporal, $$S$$ el valor suavizado de la serie, $$T$$ la componente tendencial de la serie y $$\alpha$$, $$\gamma$$ los parámetros del modelo. La predicción de la serie temporal $$S$$ en el instante $$n + m$$ viene dada por la expresión:

$$
\hat{X\_n}(m) = S\_n + m T\_n
$$

Los parámetros $$\alpha$$ y $$\gamma$$ se obtienen por optimización, seleccionando el par que da el error mínimo de predicción a un periodo para la serie temporal analizada.&#x20;

### Valor objetivo

El valor objetivo es el valor que la moneda debe alcanzar en la fecha de predicción del índice. Es la conversión del valor del índice en valor de cambio monetario (expresado en USD). Se obtiene dividiendo el valor de predicción entre el valor de base del índice.

$$
Y\_n = \dfrac {\hat{X\_n}} {X\_b}
$$

Este valor expresa también el porcentaje de inflación acumulada desde la fecha del periodo usado como base hasta la actualidad.&#x20;

#### Función rampa

La serie temporal del índice de precios al consumo tiene periodicidad mensual. Si se utilizara directamente el valor objetivo como valor de referencia de la moneda, se producirían saltos bruscos en su valor una vez al mes coincidiendo con la publicación del nuevo dato de inflación. Estos saltos bruscos en el precio, al ser predecibles, permitirían llevar a cabo ataques de arbitraje temporal contra el protocolo.&#x20;

Para evitar este tipo de ataques y generar una curva de variación del precio continua, se utiliza una función de interpolación lineal que genera una rampa continua entre el último valor objetivo y el siguiente:

$$
\delta\_{t,n} = \dfrac {t - t\_{n-1}} {t\_n - t\_{n-1}}
$$

$$
y\_{t,n} = Y\_{n-1} + \delta\_{t,n} (Y\_n - Y\_{n-1})
$$

### Limitador de variación

Los tokens indexados incorporan un mecanismo de seguridad para evitar variaciones excesivas de su valor objetivo en un periodo determinado. Cada vez que se actualiza el valor objetivo del token, el contrato comprueba que dicho valor se encuentra dentro de límites:

* Límite inferior: el límite inferior de variación viene dado por el requisito de monotonía de la función de precio. El nuevo valor objetivo no puede ser menor que el valor de referencia actual de la moneda. Si el objetivo calculado es menor, se toma como nuevo objetivo el valor actual de referencia, con lo que el valor de referencia queda temporalmente fijo al precio actual.&#x20;
* Límite superior: es un parámetro del contrato, que viene establecido por defecto en un 2% mensual. Si el nuevo valor objetivo supone una variación respecto al objetivo anterior mayor al 2%, se utiliza el valor límite como objetivo.&#x20;

### Valor de respaldo

El contrato ERC20Indexed, que sirve de base para las monedas indexadas a la inflación de Geminon, implementa un mecanismo de respaldo que permite que los tokens puedan funcionar de forma autónoma, cumpliendo su función de cobertura frente a la inflación incluso si nadie actualiza los valores del índice de referencia a través del contrato PredictIndex.&#x20;

En caso de una actualización normal, la tasa de variación mensual se calcula como:

$$
V\_n = \dfrac {T\_n} {S\_n}
$$

Donde $$T\_n$$ y $$S\_n$$ son la tendencia y el suavizado según el modelo de Holt-Winters descrito anteriormente. Si definimos una tasa de variación constante de respaldo $$V\_0$$, en caso de que en el siguiente periodo los valores de $$T\_n$$ y $$S\_n$$ no estuvieran disponibles, se calcularía una nueva tasa de variación según la expresión:

$$
V\_n = \alpha V\_0 + (1 - \alpha)V\_{n-1}
$$

La tasa de variación calculada de este modo converge lentamente hacia el valor por defecto $$V\_0$$. Si deja de actualizarse el índice subyacente de forma permanente, transcurrido un número suficiente de periodos se tendrá $$V\_n = V\_0$$. El nuevo valor objetivo se calcularía en cada periodo de forma recursiva utilizando la tasa de variación de respaldo:

$$
\hat{X}\_{n+1} = X\_n (1 +  V\_n)
$$

Para evitar que se pueda invocar la actualización de respaldo aprovechando la ventana entre la fecha de publicación del nuevo dato del índice y la transacción de actualización, el contrato PredictIndex hace disponible la predicción para los siguientes dos periodos, de forma que solo se considera desactualizado si fallan dos actualizaciones consecutivas. El contrato del token puede comenzar a realizar actualizaciones de respaldo solo cuando se sobrepasa la fecha de la segunda predicción sin que se hayan vuelto a actualizar los datos del índice, es decir, cuando pasan más de dos meses sin actualizar los valores.&#x20;


# USDI

USDI es una moneda indexada a la inflación en EEUU. Para el valor de la inflación se toma como referencia el índice de precios al consumo para todos los consumidores urbanos de todos los productos (CPIAUCSL), que puede consultarse en el siguiente enlace:

{% embed url="<https://fred.stlouisfed.org/series/CPIAUCSL>" %}

El índice, de base 100 en los años 1982-1984, se actualiza mensualmente. Los cambios porcentuales en el índice miden la tasa de variación de la inflación entre dos periodos cualquiera. Por ejemplo, en enero de 2010 el índice tenía un valor de 217,488, y en noviembre de 2022 de 298,349, lo que significa que la inflación acumulada en ese periodo ha sido del 37,19%.&#x20;

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2FSvlU3FnRsZL5LTBxuH5k%2FCPI%20pred.png?alt=media&amp;token=d286fa5a-2b1f-403b-8d4e-65a36d299110" alt=""><figcaption><p>Índice de Precios al Consumo (CPI) de EEUU (base 1982-1984). Predicciones del modelo de Holt-Winters.</p></figcaption></figure>

USDI no toma su valor directamente del CPI, ya que el dato se publica con un mes de retraso. En su lugar, se calcula la predicción del índice que será publicado en el mes siguiente, cuyo valor corresponde al mes actual, y se utiliza el valor de dicha predicción como valor objetivo de referencia del token.&#x20;

En los casos en que el nuevo valor objetivo está por debajo del valor actual (deflación), el valor de referencia del USDI permanece constante, de forma que en ningún caso su valor decaiga frente al dólar. Esta distinción es lo que hace que el USDI sea una moneda deflacionaria propiamente dicha y no un simple índice de inflación tokenizado. En la figura se observa cómo es bastante habitual que aparezcan periodos deflacionarios, algunas veces de varios años de duración, en los que el valor de referencia del USDI se mantiene constante mientras el valor objetivo no recupera su máximo anterior.

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2Fdd4xAos0BzwM7GpkBmwi%2FUSDI%20peg.png?alt=media&amp;token=89a2f855-9eae-44ce-b14b-3860489c7837" alt=""><figcaption><p>Valor de referencia (peg) del USDI frente a valor objetivo de PredictIndex.</p></figcaption></figure>

### Actualización del valor objetivo

El token USDI se diseñó para que sus valores de referencia se pudieran actualizar de forma descentralizada. El sistema se basa en el uso del servicio *Any API* de la red de oráculos de Chainlink, que permite hacer llamadas a cualquier API desde una aplicación en blockchain y recibir los datos de la respuesta de una forma verificable. Para más información consultar la documentación de Chainlink:

{% embed url="<https://docs.chain.link/any-api/introduction/>" %}

El funcionamiento del mecanismo de actualización sin embargo es complejo e involucra cuatro contratos diferentes:

* Contrato ChainlinkFredRelease. Permite realizar llamadas a la API de la Reserva Federal a través de la red Chainlink para obtener la fecha de la siguiente publicación del dato del índice de precios al consumo (CPI).
* Contrato ChainlinkFredObservation. Permite realizar llamadas a la API de la Reserva Federal a través de la red Chainlink para obtener el valor del último dato publicado del índice de precios al consumo (CPI).
* Contrato PredictIndex. Lee de los dos contratos anteriores el valor de la siguiente fecha de publicación y el del último dato publicado, y los usa para calcular la predicción del próximo dato que se publicará en esa fecha y actualizar el valor objetivo.
* Contrato USDI. Lee el nuevo valor objetivo del contrato PredictIndex, comprueba que es válido y actualiza sus valores para el objetivo.

El procedimiento de actualización es descentralizado y puede ser llevado a cabo por cualquiera dispuesto a pagar las comisiones de gas y de la red Chainlink. Son necesarias un total de cinco transacciones para completar el proceso:

* Dos transacciones para depositar tokens LINK en los contratos *ChainlinkFredRelease* y *ChainlinkFredObservation* a través de la función *depositLink()* para pagar la comisión de Chainlink por las llamadas a la API.
* Una transacción usando la función requestData() del contrato PredictIndex para hacer las llamadas a las API a través de los contratos *ChainlinkFredRelease* y *ChainlinkFredObservation*.
* Una transacción usando la función fetchData() del contrato PredictIndex para leer de los contratos *ChainlinkFredRelease* y *ChainlinkFredObservation* los datos obtenidos de las llamadas a la API y actualizar las predicciones del índice.
* Una transacción utilizando la función *updateTarget()* del token para actualizar el valor objetivo. Cualquiera puede llamar a esta función, ya que el contrato comprueba automáticamente si debe actualizarse y en caso contrario revierte la transacción. Esta función se llama también automáticamente desde el contrato del SCMinter cada vez que se realiza una transacción involucrando al USDI, lo que garantiza que siempre se opera con un valor de referencia actualizado.

#### Actualización manual

El contrato PredictIndex dispone además de un mecanismo auxiliar que permite al propietario actualizar manualmente los valores del índice de inflación de referencia y de la próxima fecha de lanzamiento en caso de que el mecanismo principal no esté disponible por algún motivo. Este procedimiento requiere solo dos transacciones:

* Una transacción utilizando la función *provideData()* del contrato PredictIndex asociado al token USDI, proporcionando los valores de la fecha de la siguiente publicación del dato de inflación y el del último dato publicado. Solo una dirección autorizada por el propietario del contrato puede ejecutar esta acción.
* Una transacción utilizando la función *updateTarget()* del token para actualizar el valor objetivo, igual que en el apartado anterior.

#### Valor de respaldo

El contrato del token USDI está preparado para funcionar de forma completamente autónoma. Incluso si nadie actualiza nunca el valor objetivo del contrato PredictIndex, la función *updateTarget()* puede realizar una actualización de respaldo utilizando un valor por defecto. Este valor es de un 0,2% mensual, que equivale a un 2,68% anualizado. La tasa de variación mensual converge lentamente hacia ese valor si dejan de actualizarse los valores del índice de referencia. Consultar la página anterior sobre monedas indexadas a la inflación para más información sobre cómo se calcula este valor de respaldo.


# EURI

EURI es una moneda indexada a la inflación de la Eurozona. Para el valor de la inflación se toma como referencia el índice armonizado de precios al consumo (HICP) para todos los productos, que puede consultarse en el siguiente enlace:

{% embed url="<https://ec.europa.eu/eurostat/databrowser/view/PRC_HICP_MIDX__custom_4410812/default/line?lang=en>" %}

Se utiliza el índice con base 100 en el año 1996. Los cambios porcentuales en el índice miden la tasa de variación de la inflación entre dos periodos cualquiera. Por ejemplo, en enero de 2010 el índice tenía un valor de 127,6, y en noviembre de 2022 de 168,6, lo que significa que la inflación acumulada en ese periodo ha sido del 32,13%.

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2F8zndB9fyQ35S6sUheQXJ%2FHICP%20pred.png?alt=media&amp;token=c1a31b1e-dde3-4f7a-9b28-f9da9b9b4463" alt=""><figcaption><p>Índice Armonizado de Precios al Consumo (HICP) de la Eurozona (base 1996). Predicciones del modelo de Holt-Winters.</p></figcaption></figure>

EURI no toma su valor directamente del HICP, ya que el dato se publica con un mes de retraso. En su lugar, se calcula la predicción del índice que será publicado en el mes siguiente, cuyo valor corresponde al mes actual, y se utiliza el valor de dicha predicción como valor objetivo de referencia del token. Como puede verse en la figura, las predicciones del modelo de Holt-Winters son bastante precisas y replican la serie de datos con gran fidelidad.&#x20;

En los casos en que el nuevo valor objetivo está por debajo del valor actual (deflación), el valor de referencia del EURI permanece constante, de forma que en ningún caso su valor decaiga frente al euro.

### Actualización del valor objetivo

Aunque utiliza el mismo contrato PredictIndex que el token USDI, el token EURI no tiene disponible por el momento la opción de actualizar los valores mediante llamadas directas a una API a través de la red Chainlink. El único mecanismo de actualización de los valores del HICP es manual, que requiere realizar dos transacciones:

* Una transacción utilizando la función *provideData()* del contrato PredictIndex asociado al token EURI, proporcionando los valores de la fecha de la siguiente publicación del dato de inflación y el del último dato publicado. Solo una dirección autorizada por el propietario del contrato puede ejecutar esta acción.
* Una transacción utilizando la función *updateTarget()* del token para actualizar el valor objetivo. Cualquiera puede llamar a esta función, ya que el contrato comprueba automáticamente si debe actualizarse y en caso contrario revierte la transacción. Esta función se llama también automáticamente desde el contrato del SCMinter cada vez que se realiza una transacción involucrando al EURI, lo que garantiza que siempre se opera con un valor de referencia actualizado.

#### Valor de respaldo

El contrato del token EURI está preparado para funcionar de forma completamente autónoma. Incluso si nadie actualiza nunca el valor objetivo del contrato PredictIndex, la función *updateTarget()* puede realizar una actualización de respaldo utilizando un valor por defecto. Este valor es de un 0,2% mensual, que equivale a un 2,68% anualizado. La tasa de variación mensual converge lentamente hacia ese valor si dejan de actualizarse los valores del índice de referencia. Consultar la página sobre monedas indexadas a la inflación para más información sobre cómo se calcula este valor de respaldo.

{% content-ref url="/pages/YoocuFs66FR0OyCGUkR8" %}
[Monedas deflacionarias](/geminon-docs-esp/tokens/monedas-deflacionarias)
{% endcontent-ref %}


# Monedas estables

Las monedas estables de Geminon son tokens ERC20 con suministro elástico. Solo se puede crear nuevo suministro a través del contrato inteligente acuñador de monedas estables (SC minter) a cambio de tokens GEX. Para más información sobre este sistema consultar la sección sobre el limitador:

{% content-ref url="/pages/n0ZiNDcvXHi9r3q5ft7G" %}
[Limitador de suministro](/geminon-docs-esp/tokens/gex/limitador-de-suministro)
{% endcontent-ref %}

### Valor de referencia

Todas las monedas estables de Geminon incorporan en su contrato una conexión a un alimentador de precios de la red de oráculos Chainlink que proporciona precios actualizados del tipo de cambio de la moneda que replican frente al dólar. El valor del último precio de la moneda puede obtenerse llamando la función *getPegValue().* Los oráculos de Chainlink utilizan los valores del mercado Forex real como fuente de sus datos, por lo que son extremadamente seguros frente a cualquier tipo de ataque.

Todos los contratos de Geminon utilizan este valor proporcionado por el oráculo como referencia para calcular las cantidades de moneda a intercambiar. Como el precio de las monedas está fijado algorítmicamente, los usuarios tienen la seguridad de que sus monedas estable pueden ser intercambiadas siempre por su precio de referencia usando los contratos de Geminon. En caso de que las monedas sean utilizadas en otros protocolos o exchanges externos, el precio se mantendría cercano a su valor de referencia gracias al arbitraje entre el mercado en cuestión y los contratos de nuestro protocolo.

### Monedas disponibles

Geminon ofrece una amplia variedad de monedas estables de diferentes regiones del mundo, y la lista sigue creciendo:

<table><thead><tr><th width="121" align="center">Símbolo</th><th width="216" align="center">Nombre</th><th width="158" align="center">País / región</th><th align="center">Redes</th></tr></thead><tbody><tr><td align="center">USDG</td><td align="center">Geminon US Dollar</td><td align="center">USA</td><td align="center">Ethereum, BNB, Avalanche</td></tr><tr><td align="center">EURG</td><td align="center">Geminon Euro</td><td align="center">Europa</td><td align="center">Ethereum, BNB, Avalanche</td></tr><tr><td align="center">CNYG</td><td align="center">Geminon Renminbi</td><td align="center">China</td><td align="center">Ethereum</td></tr><tr><td align="center">JPYG</td><td align="center">Geminon Japanese Yen</td><td align="center">Japón</td><td align="center">Ethereum, BNB, Avalanche</td></tr></tbody></table>


# Pools de Liquidez Génesis (GLP)

Los GLP son el punto de entrada para los usuarios al protocolo Geminon, y constituyen la base de su funcionamiento. Permiten a los usuarios obtener tokens GEX, que son necesarios para acceder a otras funciones del protocolo, a cambio de depositar otros tokens como colateral.&#x20;

A pesar de su nombre, no son pools de liquidez; se utiliza esa denominación por conveniencia, ya que ayuda a los usuarios a reconocer el propósito de este módulo. Un GLP presenta varias diferencias frente a un pool de liquidez tipo Uniswap:

* No hay proveedores de liquidez: en su lugar, es el propio pool el que crea y destruye la liquidez cada vez que se deposita o retira el activo usado como colateral del pool.
* No se puede intercambiar cualquier par de activos: uno de los dos tokens del intercambio tiene que ser siempre el token GEX.
* No están aislados: utilizan información del estado de los otros GLP para sus operaciones.
* Permiten prestar a plazo una parte de los activos del pool.
* Pueden acuñar y quemar el token GEX.

Un GLP es un tipo de LBP (Liquidity Bootstrapping Pool), una variante de los pools de liquidez especializada en el lanzamiento de nuevos tokens al mercado con liquidez muy baja. Los LBP fueron descritos por primera vez en 2020 por el protocolo Balancer. La principal diferencia respecto a un pool de liquidez tipo Uniswap, es que un LBP no sigue una curva de liquidez de producto constante, sino que utiliza una curva paramétrica que permite por ejemplo ejecutar una *Subasta Holandesa* (con precio descendente) para lanzar un nuevo token al mercado, asegurando una distribución justa del mismo.

Dadas sus características, los GLP desarrollados por Geminon presentan varias ventajas respecto a un pool de liquidez tipo Uniswap:

* Mayores rendimientos para los poseedores del token GEX: al no existir proveedores de liquidez, todos los beneficios provenientes del deslizamiento de las operaciones en un GLP lo reciben los poseedores del token.&#x20;
* Al igual que un LBP, permiten lanzar tokens al mercado sin necesidad de aportar una gran liquidez inicial, ya que es el propio pool el que crea la liquidez de forma dinámica.&#x20;
* Control del suministro del token, lo cual permite a su vez un control preciso de la curva de precios que ayuda a evitar los regímenes exponenciales en los extremos de la curva.
* Permite equilibrar los pesos del colateral entre distintos pools.
* Mayor seguridad para los usuarios: la liquidez que contienen no puede ser retirada instantáneamente: no permiten hacer "rug pulls".
* Mayor seguridad para el protocolo: la característica de captura de entropía de los GLP hace que aquellas operaciones que generan un gran deslizamiento del precio en un pool, como las manipulaciones usando préstamos flash, sean económicamente inviables para el atacante.


# Creador de Mercado Automático

Todo pool de liquidez se basa en un algoritmo de creación de mercado automático (AMM) que determina los precios y las cantidades de los tokens en cada operación de compraventa. Los GLP de Geminon utilizan un algoritmo propio derivado del AMM de producto constante que les confiere las capacidades de creación de liquidez de un LBP.

### AMM de producto constante

La práctica totalidad de los protocolos de intercambio descentralizado (DEX) que existen hoy en día utilizan para sus pools de liquidez la conocida como fórmula de producto constante:

$$
x \cdot y = k
$$

Donde $$x$$ e $$y$$ son las cantidades del par de tokens en el pool y $$k$$ una constante que queda fijada cuando se añade la liquidez inicial durante su creación. El pool de liquidez crea un mercado automático para el par de tokens simplemente imponiendo la condición de que, tras todo intercambio, el producto de las cantidades de ambos tokens no puede ser inferior a la constante de liquidez:

$$
(x + \Delta x)(y + \Delta y ) \nless k
$$

Dada una cantidad de tokens $$\Delta x$$  que se quieren intercambiar utilizando el pool de liquidez, la cantidad del token intercambiado a recibir, $$- \Delta y$$ se calcula como:

$$

* \Delta y = y - \frac {k}{x + \Delta x}
  $$

### AMM de producto constante generalizado

La fórmula del AMM de producto constante puede generalizarse para un pool formado por *n* tokens con pesos $$w\_n$$ tales que $$\sum\_n w\_n = 1$$:

$$
\prod\_n B\_n^{w\_n} = k
$$

Donde $$B\_n$$ es el balance del n-ésimo token en el pool. Desarrollando la fórmula anterior, se obtiene que para un intercambio de un par cualquiera de tokens del pool, dada la cantidad de entrada de un token $$\Delta x$$, la cantidad recibida del segundo token viene dada por:

$$
-\Delta y = y \Bigg(1 - \bigg(\frac {x} {x + \Delta x}\bigg)^{\frac{w\_x}{w\_y}}\Bigg)
$$

De las ecuaciones anteriores se deriva que la cotización o precio relativo de un token en función de otro en el pool depende exclusivamente de los balances y los pesos relativos de ambos tokens en el pool:

$$
P\_x^y = \frac {\frac {x}{w\_x}} {\frac {y}{w\_y}}
$$

Puede demostrarse fácilmente que estas ecuaciones se transforman en las ecuaciones para un pool de dos tokens vistas en el punto anterior haciendo $$w\_x = w\_y$$.&#x20;

### AMM de Geminon

Las ecuaciones del AMM generalizadas del punto anterior son las que utiliza el protocolo Balancer para sus pools. En los LBP de Balancer es posible alterar los pesos relativos $$w$$ de los tokens en el pool, lo cual cambia el precio relativo de ambos tokens y también el valor de la constante de liquidez del pool $$k$$.&#x20;

El algoritmo de AMM desarrollado para los GLP de Geminon también altera el valor del invariante del pool $$k$$, aunque emplea un mecanismo completamente diferente. Las principales diferencias son:

* La variación de la constante de liquidez es completamente automática en los GLP: no es posible alterar manualmente los pesos de los tokens en el pool, y por tanto los precios.
* La parametrización de la liquidez en un GLP varía en función de las operaciones realizadas, no en función del tiempo como sucede en los LBP.&#x20;
* El algoritmo del GLP no varía los pesos de los tokens en el pool sino el balance del token GEX.

#### Descripción del algoritmo

El AMM de Geminon funciona en dos pasos:

1. Se calcula la cantidad del token de salida utilizando la fórmula del AMM de producto constante con la liquidez disponible en ese momento en el pool, es decir, en este paso el GLP se comporta exactamente igual que un pool de liquidez tipo Uniswap.
2. En el segundo paso, se modifica el balance del token GEX en el pool acuñando o quemando tokens. La variación del suministro del token GEX se calcula a partir de la cantidad de tokens que el usuario ha recibido o entregado al pool, dependiendo de la operación realizada.&#x20;

Para ayudar a reducir el deslizamiento de las operaciones, el cual impacta negativamente en el resultado del usuario, el pool divide automáticamente la cantidad de entrada en dos y ejecuta los pasos anteriores dos veces, de forma que en la segunda iteración el usuario se beneficia del incremento de liquidez que él mismo ha generado. Este mecanismo es especialmente efectivo cuando la liquidez del pool es muy baja.

#### Acuñación de tokens GEX (mintSwap)

Para una operación de compra (acuñación) de tokens GEX, inicialmente se calcula la cantidad de tokens GEX a recibir como si se tratara de un pool de liquidez tipo Uniswap. Si $$c\_0$$ es el balance de colateral en el pool, y $$g\_0$$ el balance de tokens GEX en el pool, el invariante del pool vale:

$$
k\_0 = c\_0 \cdot g\_0 = (c\_0 + c\_{in})(g\_0 - g\_{out})
$$

Y la cantidad de tokens recibida por el usuario, $$g\_{out}$$, cuando este entrega una cantidad de colateral, $$c\_{in}$$, se calcula despejando en la ecuación anterior del invariante:

$$
g\_{out} = g\_0 \bigg( 1 - \frac {c\_0}{c\_0 + c\_{in}} \bigg)
$$

Tras calcular la cantidad de tokens GEX de salida, se aplica el coeficiente de acuñación $$\mu$$, que incrementa el balance de tokens GEX en el pool:

$$
g\_1 = g\_0 - g\_{out}(1 - \mu)
$$

$$
c\_1 = c\_0 + c\_{in}
$$

$$
k\_1 = c\_1 \cdot g\_1
$$

Finalmente, las comisiones por acuñación del protocolo se deducen de la cantidad de tokens GEX a enviar al usuario.

El coeficiente de acuñación $$\mu$$ toma sus valores en el intervalo $$\[1,2]$$, lo cual hace que pueda deducirse el comportamiento del GLP en las operaciones de acuñación de tokens GEX:

1\. En una operación de acuñación la liquidez siempre aumenta: al estar los valores del coeficiente  de acuñación restringidos ($$\mu \in \[1,2]$$) la diferencia $$1-\mu$$ es siempre menor o igual a 0, lo que implica que $$g\_1 \ge g\_0$$, el balance final de GEX en el pool será siempre igual o mayor al inicial. Como además $$c\_1 > c\_0$$ por tratarse de una operación de acuñación, $$k\_1 > k\_0$$, luego el producto de liquidez del pool tras la operación será siempre estrictamente mayor que el inicial.

2\. El resultado de una operación en el GLP se acerca más al obtenido en un pool de liquidez tipo Uniswap cuanto más bajo sea el importe de la operación. Si se desarrolla la ecuación del invariante $$k\_1$$ para expresarlo únicamente en función de la cantidad de entrada se tiene:&#x20;

$$
k\_1 = (c\_0 + c\_{in}) \cdot g\_0 \Bigg(1 - (1-\mu) \bigg(1- \frac {c\_0}{c\_0 + c\_{in}} \bigg) \Bigg)
$$

Es fácil ver que la expresión anterior converge al valor del invariante inicial $$k\_0 = c\_0 \cdot g\_0$$ cuanto más bajo sea el valor de entrada $$c\_{in}$$, o más formalmente:

$$
\lim\_{c\_{in} \rarr 0} k\_1 = k\_0
$$

3\. El precio final del token GEX en el pool tras la transacción es inferior al precio que se obtendría en un pool de producto constante puro. Es fácil de ver intuitivamente que, al incrementar el balance de tokens GEX en el pool, el precio relativo de este frente al otro token debe descender:

$$
P\_1^g = \frac{c\_1}{g\_1} = \frac{c\_0 + c\_{in}}{g\_0 - g\_{out} + \mu g\_{out}} < \frac{c\_0 + c\_{in}}{g\_0 - g\_{out}}
$$

Esto supone que las transacciones en un GLP no son reversibles incluso sin tener en cuenta las comisiones del protocolo: si se realiza una operación de acuñación e inmediatamente después se realiza la contraria, canjeando los tokens en el pool, se obtendrá una cantidad inferior en función de lo alejado que esté el producto de liquidez $$k\_1$$ del inicial $$k\_0$$. Como se ha visto en la segunda propiedad, los invariantes coinciden en cero y se separan conforme aumenta el importe de la operación $$c\_{in}$$, o más concretamente la relación $$c\_0/c\_{in}$$ que determina el deslizamiento que produce la operación en el precio del pool. Cuanto mayor es el deslizamiento (entropía) que genera una operación en el pool, más irreversible es dicha operación. Dicha entropía es capturada por el GLP incrementando el valor del token GEX, motivo por el cual se denomina a los GLP máquinas de captura de entropía.

La irreversibilidad de las operaciones presenta importantes ventajas para la seguridad del protocolo Geminon, ya que implica que no se pueden realizar ataques mediante préstamo flash a un GLP: al no poder devolverse la cantidad prestada en su totalidad, la transacción revertirá. En general, cualquier ataque que implique manipulación de precios en un GLP utilizando transacciones de gran importe que deban deshacerse en un intervalo breve de tiempo, supondrá una pérdida económica para el atacante a favor del protocolo.

#### Canjeo de tokens GEX (redeemSwap)

Las ecuaciones para el canjeo de token GEX son muy similares a las de acuñación. La principal diferencia entre ambos procesos es que durante el canjeo la comisión del protocolo se deduce de la cantidad de entrada de tokens GEX. La cantidad de colateral de salida $$c\_{out}$$, dada una cantidad de entrada (descontada la comisión) $$g\_{in}'$$ vale:

$$
c\_{out} = c\_0 \bigg( 1 - \frac {g\_0}{g\_0 + g\_{in}'} \bigg)
$$

Y los nuevos balances que determinan el producto de liquidez del pool:

$$
c\_1 = c\_0 - c\_{out}
$$

$$
g\_1 = g\_0 + g\_{in}'(1 - \rho)
$$

### Curva de precios

En un pool de liquidez de producto constante, el precio de un token respecto a su par es el cociente de las reservas de ambos. Utilizando la relación del producto constante $$xy = k$$ se obtiene:

$$
P\_y = \frac{x^2}{k}
$$

El precio de un token en un pool de liquidez es una función parabólica de la cantidad del segundo token en el pool. En un GLP en cambio el valor de $$k$$ no es constante, sino que su valor varía con la cantidad de colateral en el pool. La función de precio del token GEX en un GLP puede escribirse como:

$$
P\_g = \frac{c^2}{k(c)}
$$

Donde $$k(c)$$ es una función que varía linealmente con la cantidad de tokens de colateral. Como consecuencia, la función de precio de los GLP para el token GEX no varía de forma cuadrática con la cantidad de colateral como sucede en un pool tipo Uniswap, sino linealmente. El objetivo de este diseño es reducir la volatilidad del token GEX.&#x20;

Para una discusión detallada sobre la influencia del ratio de acuñación en el valor de $$k$$, consultar la siguiente página "Control del suministro".


# Control del suministro

El suministro de tokens GEX se controla variando el producto de liquidez $$k$$ de los GLP añadiendo a las ecuaciones del AMM sendos coeficientes de acuñación $$\mu$$ y quema $$\rho$$.

### Ratio de acuñación

El ratio de acuñación del token GEX en un GLP se calcula como el cociente entre el ratio de suministro del pool, $$\sigma\_p$$, y el ratio de peso del colateral de dicho pool, $$\omega\_p$$:

$$
\mu\_p = \frac{\sigma\_p }{\omega\_p}
$$

El ratio de acuñación sube cuando la cantidad total de tokens acuñados está por debajo de su valor objetivo o cuando el pool tiene menos colateral del deseado. En este caso, ante una operación de acuñación, el pool crea más liquidez y sube menos de precio en comparación con otro GLP que tenga más colateral, lo cual crea un incentivo de arbitraje para que el pool con menos colateral atraiga más proveedores.&#x20;

Cuando el GLP tiene más colateral del deseado, el ratio de acuñación baja respecto a otros GLP, creando menos liquidez y haciendo subir más el precio, incentivando el uso de otros pools para la acuñación en su lugar.&#x20;

### Ratio de quema

El ratio de quema de tokens GEX en un pool es proporcional al ratio de suministro del pool $$\sigma\_p$$ y al ratio de peso $$\omega\_p$$:

$$
\rho\_p = \sigma\_p \cdot \omega\_p
$$

La diferencia entre el ratio de quema y el de acuñación viene determinada por el ratio de peso del colateral: mientras que en la quema la relación es proporcional, en la acuñación es la inversa. Esto hace que el comportamiento del GLP a la hora de ajustar los incentivos de arbitraje sea opuesto en función de si se trata de un operación de suministro (acuñación) o retirada (quema) de colateral.&#x20;

En una operación de quema de tokens GEX, si el pool tiene menos colateral del deseado, quema menos tokens lo que resulta en un precio final más bajo, creando un incentivo de arbitraje para la acuñación en el pool. Si el pool en cambio tiene más colateral del deseado, aumenta la cantidad de tokens GEX quemados, resultando en un precio final mayor que desincentiva el suministro de colateral al pool.

### Ratio de suministro

El ratio de suministro tiene la misión de crear liquidez para el token GEX de forma proporcional a la cantidad de colateral que se deposita en los pools, creando de esta forma una curva de precios con varianza constante. Se calcula como una proporción entre la diferencia del suministro objetivo del token GEX, $$S\_g$$, y el suministro total acuñado por los pools de la red $$\sum\_p m\_p$$:

$$
\sigma\_p = \begin{cases}
\ \ \ \ \ 2 &\text{if } m\_p \le 0 \\
1 + \frac{S\_g - \sum\_p m\_p}{S\_g} &\text{if } 0 < m\_p \le S\_p \\
\ \ \ \ \ 1 &\text{if } m\_p > S\_p
\end{cases}
$$

El ratio de suministro tiene limitado su rango de valores al intervalo \[1, 2] por razones de estabilidad. El ratio toma su valor máximo en 2 cuando el suministro del token GEX es nulo, de forma que se prioriza la generación de liquidez sobre la subida del precio. Cuando se alcanza el nivel objetivo de suministro (100 millones de tokens), el ratio vale 1, y se acuña exactamente la misma cantidad de tokens que se entregan al usuario. Cuando esto sucede, la cantidad de tokens GEX en el pool se vuelve constante, por lo que el producto de liquidez $$k$$ varía linealmente con la cantidad de colateral en el pool, y la curva de precio del token GEX converge a $$y = x$$, perfectamente lineal.&#x20;

Si el ratio de suministro es inferior a 1, la cantidad de tokens GEX en el pool comienza a descender y la curva de precios deja de ser lineal, aproximándose a una parábola cuanto más se acerque a 0 el ratio de acuñación. Si el ratio de suministro es superior a 2, se produce una inversión de la curva de precios: al acuñar tokens GEX su precio bajaría y al canjearlos subiría, provocando un comportamiento inestable del pool. Por este motivo los valores están limitados al intervalo \[1, 2].

### Ratio de peso del pool

El ratio de peso es el responsable de crear oportunidades de arbitraje entre los pools que ayuden a mantener la cantidad de colateral en cada uno cerca de su valor objetivo. Se define como la relación entre el peso actual del colateral, y el peso objetivo fijado en los parámetros del protocolo:

$$
\omega\_p' = \frac{v\_p}{\rho\_p \cdot \sum\_p v\_p}
$$

Donde $$v\_p$$ es el valor, medido en USD, del colateral que contiene el pool, $$\sum\_p v\_p$$ es el valor conjunto del colateral en todos los GLP de la red y $$\rho\_p$$ es el peso objetivo. El valor del ratio calculado $$\omega\_p'$$ se limita para que su valor esté comprendido entre 0.75 y 1.25:

$$
\omega\_p = \begin{cases}
0.75 &\text{if } \omega\_p' < 0.75 \\
\ \ \omega\_p' &\text{if } 0.75 \le \omega\_p' \le 1.25 \\
1.25 &\text{if } \omega\_p' > 1.25
\end{cases}
$$

El ratio de peso tendrá un valor mayor a 1 cuando el valor del colateral en el pool sea mayor al objetivo, y menor que 1 cuando el valor del colateral esté por debajo de su objetivo.


# Oráculo interno

Los GLP de Geminon forman parte de un sistema de finanzas descentralizadas completo que incluye creación de monedas estables y préstamos. Este tipo de aplicaciones son vulnerables a ataques de manipulación de precios, y por ello necesitan fuentes fiables de precios para sus cálculos. Dado el rol central que desempeña el token GEX en el protocolo Geminon, se ha incorporado a los GLP un oráculo interno que permite obtener precios seguros del token.

### Algoritmo del oráculo

El algoritmo del oráculo interno de los GLP emplea un principio similar al usado para el limitador de suministro del token GEX y para el sistema de seguridad del intercambio de moneda estable (StableSwap Guard), que se basa en un suavizado exponencial adaptativo cuyos parámetros varían en función de la aplicación. El algoritmo del oráculo calcula dos valores, un valor instantáneo que incluye las operaciones dentro del bloque actual ($$\Delta t = 0$$) y otro considerado el valor seguro que solo se actualiza al cierre de cada bloque ($$\Delta t > 0$$).

#### Valor instantáneo

El valor instantáneo del oráculo, $$l\_n$$, se actualiza cada vez que se produce una operación en un GLP. El parámetro de suavizado, $$\beta$$, se obtiene a partir de la relación entre el volumen de la operación actual, $$v\_n$$, y el volumen medio de las operaciones en el pool $$\overline{V}$$.&#x20;

$$
\beta\_n = \begin{cases}
\ \ \ \ \ 1 &\text{if } \beta\_n > 1 \\
\dfrac {\overline{V}\_n}{v\_n + \epsilon} &\text{if } \beta\_n \le 1
\end{cases}
$$

$$
l\_n = \beta\_n p\_n + (1-\beta\_n) l\_{n-1}
$$

El parámetro $$\beta$$ toma su valor máximo, limitado a 1, cuando el volumen de la operación actual es inferior al volumen habitual del pool. En ese caso, el valor instantáneo del precio del oráculo $$l\_n$$ coincide con el precio instantáneo del pool $$p\_n$$. Si el volumen de la última operación es mayor al volumen habitual, entonces $$\beta < 1$$ y el precio se filtra proporcionalmente a la anomalía del volumen. Por ejemplo, si el volumen de la operación es 1000 veces mayor al normal, entonces el nuevo precio tendrá un peso de 0.001 en el precio promedio $$l\_n$$ y su valor no afectará al precio instantáneo del oráculo, logrando su objetivo de filtrar las operaciones anómalas.&#x20;

Para el cálculo del volumen medio de operaciones se utiliza un suavizado exponencial simple, con parámetro $$\gamma = 0.001$$. Este suavizado es equivalente a utilizar la media del volumen de las últimas 1000 operaciones:

$$
\overline{V}\_{n+1} = \gamma v\_n + (1 - \gamma) \overline{V}\_n
$$

La actualización del volumen medio de operaciones se realiza a posteriori, por lo que el volumen de la operación en curso no se tiene en cuenta en los cálculos del oráculo hasta la siguiente operación. Este detalle es importante, puesto que evita que un préstamo flash pueda alterar el dato de volumen medio usado para calcular el parámetro $$\beta$$, mejorando la capacidad de filtrado del algoritmo.

Finalmente, se calcula el volumen acumulado del bloque en curso:

$$
V\_B = \begin{cases}
\ \ \ \ \ 0 &\text{if } \Delta t > 0 \\
\sum\_{n \in B} v\_n &\text{if } \Delta t = 0
\end{cases}
$$

#### Valor seguro

El valor seguro del oráculo se calcula únicamente al inicio de un nuevo bloque ($$\Delta t > 0$$). El cálculo es similar al del valor instantáneo, siendo la diferencia que el valor seguro toma como entrada los valores del valor instantáneo del oráculo, produciendo un filtrado de segundo orden. Para el parámetro de suavizado $$\alpha$$, se utiliza el volumen acumulado del bloque anterior $$V\_{B-1}$$ en lugar del volumen de la última operación $$v\_n$$:

$$
\alpha\_n = \begin{cases}
\ \ \ \ \ \ 1 &\text{if } \alpha\_n > 1 \\
\dfrac {\overline{V}*n}{V*{B-1} + \epsilon} &\text{if } \alpha\_n \le 1
\end{cases}
$$

Finalmente, para el cálculo del valor seguro del precio $$m\_n$$ se utiliza como entrada el valor instantáneo suavizado del bloque anterior, $$l\_{n-1}$$, en lugar del precio actual $$p\_n$$:

$$
m\_n = \alpha\_n l\_{n-1} + (1-\alpha\_n) m\_{n-1}
$$

Esta estructura de cálculo asegura que el precio seguro $$m\_n$$ no puede verse afectado por un ataque de préstamo flash, ya que toma el precio de cierre del bloque anterior, que además ha sido previamente filtrado descartando operaciones con volumen anómalo, y que es nuevamente filtrado a través del parámetro $$\alpha$$. Este filtrado doble asegura además que incluso ataques realizados al contado sean adecuadamente descartados hasta que se realicen varias operaciones con volumen normal en el pool al nuevo precio.

La justificación de la seguridad frente a ataques realizados al contado y que tienen una duración superior al tiempo de bloque de la red se encuentra en la hipótesis de eficiencia del mercado y el principio de no arbitraje. Un atacante que intente manipular el precio de un pool sin utilizar un préstamo flash se expone a la reacción del mercado (arbitraje) en el bloque siguiente para restablecer el equilibrio de precios, por lo que el precio resultante de las operaciones siguientes será un precio justo de mercado que debe ser reflejado por el oráculo.&#x20;

Esta capacidad de reflejar inmediatamente los cambios en el precio cuando se establece un flujo de operaciones normal a la vez que se filtran las anomalías puntuales es posible gracias a que el suavizado se realiza en el dominio del volumen en lugar de en el dominio del tiempo, por lo que se logra una gran capacidad de filtrado del ruido sin introducir retardo en la serie suavizada.&#x20;

El objetivo de un oráculo de precios no es eliminar por completo las operaciones de gran tamaño sino evitar las manipulaciones instantáneas de precios a la vez que proporciona un precio lo más actualizado posible. En esta tarea, el algoritmo propuesto por Geminon es extremadamente eficiente y supera a los algoritmos utilizados hasta ahora en otros protocolos descentralizados. La combinación de este oráculo con la característica de captura de entropía de los GLP hace extremadamente improbable que un ataque de manipulación de precio del token GEX resulte beneficioso para el atacante.&#x20;


# Ataques de manipulación de precios

Los ataques de manipulación de precios son el tipo de ataque más común contra los protocolos de finanzas descentralizadas basados en blockchain. Estos ataques casi siempre se ejecutan utilizando un préstamo flash (flash loan), motivo por el que también se conocen por ese nombre. A pesar de que este tipo de ataque ha sido realizado decenas (si no cientos) de veces y su mecanismo es ampliamente conocido, se siguen poniendo en producción proyectos con las mismas vulnerabilidades que permiten estos ataques. Teniendo en cuenta esta realidad, el protocolo Geminon se ha diseñado de forma que sea seguro ante este tipo de ataques.

### Préstamos flash

Los préstamos flash son una característica que fue introducida inicialmente por el protocolo de préstamos Aave en 2020, y poco después por Uniswap v2. Dado que la mayoría de protocolos de préstamo e intercambio descentralizado lanzados en los meses siguientes se inspiraron o fueron copias (forks) de Aave y Uniswap, la funcionalidad de préstamo flash terminó estando disponible por doquier.

Un préstamo flash permite tomar prestada cualquier cantidad de tokens disponible en un contrato inteligente (habitualmente un pool de liquidez en un DEX o un pool de préstamos) sin entregar ninguna garantía siempre que se devuelva en la misma transacción. Por definición esto solo es posible si se utiliza otro contrato inteligente para ejecutar la transacción, por lo que el uso de préstamos flash está reservado a desarrolladores especializados en esta tecnología.

Gracias a los préstamos flash cualquiera con los conocimientos necesarios puede disponer de una cantidad casi ilimitada de liquidez para sus operaciones. La funcionalidad de préstamos flash se creó con el objetivo de dotar a los protocolos descentralizados de una gran liquidez y eficiencia del capital, permitiendo que cualquiera pudiera hacer operaciones de arbitraje de gran importe sin necesidad de tener el capital necesario por adelantado, generando además ingresos extra por comisiones a los protocolos. Sin embargo, esto abrió la puerta también a la posibilidad de que cualquier pudiera realizar ataques de manipulación de precios en la blockchain.&#x20;

### Contramedidas

El protocolo Geminon incorpora varias medidas de seguridad destinadas a mitigar, impedir o disuadir los ataques por préstamo flash contra el protocolo. Tomadas en conjunto, todas estas medidas convierten a Geminon en uno de los protocolos más seguros frente a préstamos flash creados hasta la fecha.

Desde la perspectiva de un ataque dirigido a acuñar una gran cantidad de moneda estable usando un préstamo flash existen cinco mecanismos de seguridad solapados:

* Limitador de suministro del token GEX
* Oráculo interno del GLP
* Oráculo del protocolo
* Limitador de suministro de la moneda estable
* Captura de entropía del GLP

Todos estos sistemas funcionan de forma conjunta, de forma que en función del estado en que se encuentre el protocolo y las características del ataque, será más probable que intervenga uno o varios de ellos.

#### Limitador de suministro del token GEX

Cualquier intento de manipulación del token GEX que implique incrementar artificialmente su precio, provocará la acuñación de una gran cantidad de tokens GEX en los GLP. Esta acuñación masiva instantánea podría disparar el limitador de suministro del token, que está establecido en 5 millones de unidades al día en promedio. La activación del limitador implica que la transacción del ataque revierta, por lo que no tendría ningún efecto sobre el sistema. Para más información sobre el funcionamiento de este mecanismo consultar la sección dedicada:

{% content-ref url="/pages/n0ZiNDcvXHi9r3q5ft7G" %}
[Limitador de suministro](/geminon-docs-esp/tokens/gex/limitador-de-suministro)
{% endcontent-ref %}

#### Oráculo interno del GLP

Los GLP incorporan un oráculo interno desarrollado por Geminon cuyo algoritmo es inmune a las manipulaciones de precio utilizando préstamos flash.&#x20;

{% content-ref url="/pages/7dKzO3SqOBnAAPIweNYZ" %}
[Oráculo interno](/geminon-docs-esp/modulos/pools-de-liquidez-genesis-glp/oraculo-interno)
{% endcontent-ref %}

#### Oráculo del protocolo

El contrato del oráculo de Geminon actúa como coordinador del resto de contratos del protocolo. Una de sus funciones es la de agregar los datos de los oráculos de cada uno de los GLP de la red, proporcionando un precio seguro para el token GEX que es el promedio de los oráculos internos de cada GLP. Se trata de una capa adicional de seguridad a los oráculos internos de cada pool, que potencia el efecto del resto de sistemas de seguridad:

* Incrementa la probabilidad de que se active el limitador de suministro del token GEX, ya que para lograr una misma variación del precio medio de los *n* pools de la red, es necesario acuñar *n* veces más tokens GEX que si se tratara de un único pool.
* Potencia la eficacia del oráculo interno de los GLP, añadiendo una tercera capa de suavizado a las alteraciones puntuales de precios.
* Potencia la captura de entropía de los GLP, multiplicando el coste y las potenciales pérdidas para el atacante que intenta manipular el precio.

#### Limitador de suministro de moneda estable

Todas las monedas estables de Geminon incorporan un limitador de suministro como el que utiliza el token GEX. Este sistema sería el último en intervenir en caso de ataque, y aunque también puede provocar que reviertan las transacciones del ataque, se considera más un mecanismo para mitigar el alcance de los ataques limitando el posible impacto en las cuentas del protocolo.

#### Captura de entropía del GLP

Es una de los sistemas de protección más efectivos del pool, ya que hace que las operaciones de alto impacto en el precio sean irreversibles. En el caso de préstamos flash, esto significa que la transacción revertirá al no poder devolverse el importe íntegro del préstamo, y en los ataques al contado hará que la operación no sea rentable para el atacante. En el siguiente punto se trata en detalle este efecto.

### Simulaciones

Dada la importancia de asegurar la seguridad del protocolo frente a los ataques de manipulación de precios, el equipo de Geminon llevó a cabo simulaciones del comportamiento del oráculo interno de un GLP frente a diferentes patrones de ataque mediante préstamo flash. Las simulaciones confirmaron empíricamente el comportamiento esperado del diseño del protocolo.

#### Configuración

Para las simulaciones se utilizó un único pool aislado, por lo que no se tienen en cuenta las sinergias del uso de varios pools y del oráculo maestro del protocolo. Se simularon series de 100.000 operaciones de importe e intervalo aleatorios, que generaban un crecimiento constante de largo plazo del tamaño del pool, y cada 10.000 operaciones legítimas se introducía un ataque de manipulación con un importe aleatorio entre 1 millón y 1000 millones $, de forma que se probaron ataques en todos los regímenes de liquidez del pool. Se probaron tanto patrones de ataque simple, como ataques con múltiples operaciones que buscaban engañar al oráculo interno del pool para hacerlo reflejar el precio manipulado.

#### Resultados

* En más del 50% de los ataques simulados la transacción fue revertida debido a que se disparó en primera instancia el limitador de acuñación del token GEX. En un entorno de varios pools, este porcentaje hubiera sido aún mayor.
* Ningún patrón de ataque logró manipular el precio seguro del pool dentro del mismo bloque, lo que implica que ningún ataque de préstamo flash habría sido efectivo contra el protocolo, incluso habiendo un único GLP funcionando en la red. En la siguiente figura puede verse la secuencia de precios del pool durante uno de los ataques simulados. Puede verse cómo el ataque produce un pico instantáneo en el precio bruto del pool, mientras que el precio instantáneo del oráculo logra filtrar perfectamente el ataque y el precio seguro permanece inalterado hasta que finaliza. También puede verse como durante las operaciones normales antes y después del ataque, el oráculo refleja fielmente y sin retardos el precio exacto del pool.

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2F9x9NpvTQkA9Jfa2LKfQ0%2FFlashloan%20prices.png?alt=media&amp;token=884bfd39-3b5b-405b-b7f8-ae17169fccf2" alt=""><figcaption><p>Secuencia de precios del pool durante un ataque de préstamo flash. Precio bruto y precios del oráculo. </p></figcaption></figure>

* En el caso de ataques al contado, con duración mayor a un bloque, el precio final del pool terminó siendo mayor debido a que el pool capturó un porcentaje importante del colateral depositado por el atacante, haciendo que el ataque no solo no tuviera éxito sino que produjera beneficios para el protocolo. En el caso de préstamos flash las transacciones hubieran sido revertidas por imposibilidad de devolver el préstamo completo al finalizar la transacción. La siguiente figura muestra la variación de balance del atacante durante el préstamo flash. Puede observarse que termina con un balance inferior al inicial, sin contar con las comisiones.&#x20;

<figure><img src="https://908723225-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJAuHpqjaWZcWvJ9BBx58%2Fuploads%2FX6jC2tFFVkAnv1TXF4KT%2FFlashloan%20balances.png?alt=media&amp;token=b3fedb9e-5718-45bc-8a2e-ee044fb716f7" alt=""><figcaption><p>Secuencia del balance del atacante durante un flash loan. Captura de entropía del pool.</p></figcaption></figure>


# Protocolos de seguridad

Además de la protección contra ataques externos, los contratos del protocolo Geminon incorporan protección contra ataques internos, que son aquellos que podría llevar a cabo un miembro del equipo malicioso o un atacante que se hiciera con el control de las claves del protocolo. Todas las funciones administrativas de los GLP cuyo uso malicioso pueda tener algún impacto sobre los fondos que custodia el contrato, están protegidos con sistemas de seguridad adicionales.

### Cambios de parámetros

Los parámetros básicos de un pool solo pueden ser cambiados por el propietario del contrato. Las funciones involucradas tienen algunos mecanismos de seguridad adicionales:

#### Comisiones de acuñación y canjeo (setMintFee() / setRedeemFee())

Permite cambiar la comisión base que cobra el pool a los usuarios. El acceso malicioso a estas funciones no presenta riesgos significativos, por lo que la única medida de seguridad adicional es que su valor máximo está limitado al 0,5%.

Peso del pool (setPoolWeight())

Permite cambiar el peso objetivo del pool, que influye en el ratio de peso que es un componente de los ratios de acuñación y quema de tokens. El uso malintencionado de la función no tendría un impacto significativo. Incorpora varias comprobaciones adicionales:

* El nuevo peso no puede ser cero.
* No puede aumentarse el peso si se ha solicitado la migración o la eliminación del pool.&#x20;
* La diferencia entre el nuevo objetivo y el anterior no puede ser mayor al 5%.&#x20;
* La diferencia entre el nuevo objetivo y el peso actual del pool no puede ser mayor al 10%.

### Cambios de infraestructura

La infraestructura de un pool está constituida por otros contratos del protocolo Geminon o externos con los que el pool interactúa para su funcionamiento. Solo el propietario puede acceder a estas funciones, pero dado que se trata de funciones importantes, todas cuentan con bloqueos temporales de seguridad.

El sistema de bloqueos temporales de cambio de contratos requiere dos pasos: una primera transacción en la que se hace la solicitud de cambio de la dirección del contrato y se especifica la dirección del nuevo contrato usando la función *requestAddressChange()*, lo cual inicia el contador de tiempo del bloqueo, y una segunda transacción que verifica que ha transcurrido el tiempo de bloqueo (varios días o semanas) y aplica los cambios. El propietario del contrato puede cancelar la solicitud en ese tiempo. Este sistema garantiza que todo cambio es público y se puedan observar las características de los nuevos contratos antes de que entren en funcionamiento.&#x20;

#### Cambio del alimentador de precios (applyPriceFeedChange())

El alimentador de precios es un contrato de la red Chainlink que proporciona el precio del colateral en dólares. Este precio se utiliza de forma informativa para las transacciones de los usuarios y en el cálculo de los pesos relativos de los pools, que a su vez influyen en los ratios de acuñación y quema de tokens. Un cambio no autorizado tendría un impacto moderado en el protocolo, aunque no pondría en riesgo fondos de los usuarios, por lo que se emplea un bloqueo intermedio.

Protegido por un bloqueo temporal de 7 días.

#### Cambio del acuñador de moneda estable (applySCMinterChange())

El acuñador de moneda estable puede pedir tokens GEX  aun GLP si se queda sin liquidez para atender los canjeos de moneda estable. Aunque la función de rescate está protegida (ver más adelante), se considera que la introducción de un contrato malicioso en el rol de acuñador de estables presentaría un riesgo alto para los fondos de un GLP, por lo que se emplea un bloqueo largo.

Protegido por un bloqueo temporal de 30 días.

#### Cambio del oráculo (applyOracleChange())

El oráculo del protocolo (no confundir con el oráculo interno del pool) realiza importantes funciones en la gestión y coordinación de los diferentes contratos del protocolo. También interviene en determinadas comprobaciones de seguridad, además de proporcionar los precios del token GEX a otros contratos. Se considera una función crítica del protocolo, por lo que se emplea un bloqueo largo.&#x20;

Protegido por un bloqueo temporal de 30 días.&#x20;

#### Cambio del contrato de préstamo (applyLenderChange())

El protocolo se diseñó con la idea de que el contrato de préstamos (todavía en desarrollo) pudiera utilizar parcialmente los fondos de los GLP aumentando la eficiencia del capital del protocolo. Por este motivo, se dejó habilitada una función que permitiría realizar estos préstamos. Previamente, es necesario dar de alta la dirección del contrato de préstamos en el GLP. Esta función se considera crítica para la seguridad del protocolo, por lo que se emplea un bloqueo largo.

Protegido por un bloqueo temporal de 30 días.&#x20;

### Migración / eliminación del pool

Los pools de Geminon no utilizan proveedores de liquidez, por lo que toda la liquidez es propiedad del protocolo y no puede ser retirada. Sin embargo, podrían darse situaciones en el futuro en las que fuera necesario cambiar la liquidez a un nuevo contrato: descubrimiento de vulnerabilidades, actualizaciones del protocolo, cambios en el colateral aceptado, etc. Para cubrir estas eventualidades, se diseñaron procedimientos que permitían mover el colateral a un nuevo pool (migración) o bien retirarlo manualmente (eliminación). Ambos procedimientos son evidentemente críticos desde la perspectiva de la seguridad de los fondos y por tanto están protegidos con los procedimientos de seguridad más complejos de todo el protocolo. Los procesos son ligeramente distintos para cada uno:

#### Migración

El procedimiento de migración requiere tres pasos:

1. Solicitar en el contrato del oráculo el cambio de dirección del pool con la función *requestAddressChange()*, lo que inicia un bloqueo temporal de 7 días.&#x20;
2. Solicitar en el contrato del pool el inicio del procedimiento de migración con la función *requestMigration()*. Esto inicia un bloqueo temporal de 30 días. Adicionalmente, se tienen que cumplir varios requisitos para poder ejecutar la función:
   * No puede haber otra migración o eliminación de pool solicitada, ni del pool objetivo ni de otro pool de la red.&#x20;
   * La dirección del oráculo Geminon no puede ser nula, tiene que haberse conectado el pool al oráculo del protocolo.
   * Tienen que haber transcurrido al menos 30 días desde que se conectó el pool al oráculo.
   * En el oráculo tiene que figurar registrada la solicitud de migración del pool desde 7 días antes.
   * El peso objetivo del pool tiene que estar fijado por debajo del 5%.
   * El peso actual del colateral del pool en la red tiene que ser menor al 5%.
   * La acuñación de tokens GEX en el pool queda en pausa y no se puede reanudar si no se cancela la solicitud de eliminación.
3. Realizar la migración del pool usando la función *migratePool()*. Esta función realiza varias comprobaciones adicionales:
   * La migración del pool tiene que figurar solicitada en el pool desde hace al menos 30 días.&#x20;
   * La migración del pool debe figurar solicitada el contrato del oráculo.
   * La dirección del oráculo Geminon no puede ser nula, tiene que haberse conectado el pool al oráculo del protocolo.
   * Tienen que haber transcurrido al menos 60 días desde que se conectó el pool al oráculo.
   * El peso objetivo del pool tiene que estar fijado por debajo del 2%.
   * El peso actual del colateral del pool en la red tiene que ser menor al 2%.

El procedimiento de migración transfiere automáticamente al nuevo pool todo el colateral y los tokens GEX que contiene el pool migrado. En este procedimiento los fondos son manejados internamente por los contratos del protocolo.

#### Eliminación

El procedimiento de eliminación requiere tres pasos, y es más restrictivo que el de migración en cuanto a los pesos máximos del colateral requeridos. El resto de requisitos son idénticos:

1. Solicitar en el contrato del oráculo la eliminación de la dirección del pool con la función *requestRemoveAddress()*, lo que inicia un bloqueo temporal de 7 días.&#x20;
2. Solicitar en el contrato del pool el inicio del procedimiento de eliminación con la función *requestRemove()*. Esto inicia un bloqueo temporal de 30 días. Adicionalmente, se tienen que cumplir varios requisitos para poder ejecutar la función:
   * No puede haber otra migración o eliminación de pool solicitada, ni del pool objetivo ni de otro pool de la red.&#x20;
   * La dirección del oráculo Geminon no puede ser nula, tiene que haberse conectado el pool al oráculo del protocolo.
   * Tienen que haber transcurrido al menos 30 días desde que se conectó el pool al oráculo.
   * En el oráculo tiene que figurar registrada la solicitud de migración del pool desde 7 días antes.
   * El peso objetivo del pool tiene que estar fijado por debajo del 5%.
   * El peso actual del colateral del pool en la red tiene que ser menor al 5%.
   * La acuñación de tokens GEX en el pool queda en pausa y no se puede reanudar si no se cancela la solicitud de eliminación.
3. Realizar la eliminación del pool usando la función *removePool()*. Esta función realiza varias comprobaciones adicionales:
   * La migración del pool tiene que figurar solicitada en el pool desde hace al menos 30 días.&#x20;
   * La migración del pool debe figurar solicitada el contrato del oráculo.
   * La dirección del oráculo Geminon no puede ser nula, tiene que haberse conectado el pool al oráculo del protocolo.
   * Tienen que haber transcurrido al menos 60 días desde que se conectó el pool al oráculo.
   * El peso objetivo del pool tiene que estar fijado por debajo del 1%.
   * El peso actual del colateral del pool en la red tiene que ser menor al 1%.

Al contrario que en la migración, el procedimiento de eliminación de un pool transfiere los fondos restantes del pool al propietario del contrato, que debe encargarse manualmente de convertirlos a otro tipo de colateral y reintegrarlos a otro pool del protocolo. Por este motivo se requiere que el pool contenga menos del 1% de todo el colateral del protocolo para permitir su eliminación. A pesar de todas las medidas de seguridad, este procedimiento requiere confianza y no debería llevarse a cabo salvo en circunstancias extremas.&#x20;

### Funciones del protocolo

#### Pausar / reanudar acuñación (pauseMint() / unpauseMint())

Estas funciones permiten pausar y reanudar la función de acuñación del token GEX en el pool. El canjeo de tokens no se puede pausar. Solo el propietario puede invocar estas funciones. La reanudación no puede llevarse a cabo si está solicitada la migración o eliminación del pool.

#### Hacer coincidir balances (matchBalances())

Permite hacer que los balances internos de token GEX y colateral del pool coincidan con el balance de los respectivos tokens en la dirección del contrato del pool. Esta función se utiliza para recuperar tokens enviados por error directamente al contrato. Solo el propietario puede usar la función. Como medida de seguridad adicional para evitar variaciones bruscas de precios, la función requiere que la diferencia entre el balance interno del pool y la cantidad real de tokens que contiene la dirección sea inferior al 1%.&#x20;

#### Rescate del acuñador de moneda estable (bailoutMinter())

Esta función permite al contrato del acuñador recibir tokens GEX del pool en caso de que no tenga liquidez suficiente para canjear moneda estable de los usuarios. Dado que reduce el balance de tokens GEX del pool, tiene como efecto una subida del precio del token. La función puede llamarla manualmente el propietario del contrato, o puede ser invocada automáticamente por el contrato del acuñador. Para que la transacción no revierta, deben cumplirse varias condiciones:

* El contrato del acuñador tiene que estar dado de alta en el pool que recibe la solicitud.
* El oráculo Geminon tiene que estar dado de alta en el pool desde hace más de 30 días.&#x20;
* El contrato del acuñador tiene que estar dado de alta en el oráculo Geminon desde hace más de 7 días.&#x20;
* El contrato del acuñador tiene que tener menos de un 5% de los tokens GEX que hay en el balance del pool.&#x20;
* La cantidad máxima que puede ceder el pool es el 5% de su balance de tokens GEX.&#x20;

#### Préstamo de colateral (lendCollateral())

Esta función permite al contrato de préstamos utilizar una parte del colateral de un pool para entregar un préstamo sobrecolateralizado. El colateral del préstamo debe ser un colateral válido de los GLP de la red, de forma que incluso en caso de liquidación del prestatario el colateral pueda ser reintegrado al pool. La función sola la puede invocar el contrato de préstamos, y requiere muchas condiciones:

* El contrato de préstamos tiene que estar dado de alta en el pool que recibe la solicitud.
* El oráculo Geminon tiene que estar dado de alta en el pool desde hace más de 30 días.&#x20;
* El contrato de préstamos tiene que estar dado de alta en el oráculo Geminon desde hace más de 7 días.&#x20;
* El contrato del acuñador tiene que estar dado de alta en el pool que recibe la solicitud.
* No puede haberse solicitado la migración o eliminación del pool.&#x20;
* El valor total acumulado de los préstamos del pool no puede ser mayor al 5% del valor total de los tokens GEX bloqueados en contratos del protocolo.
* La cantidad máxima que puede ceder el pool es el 25% de su balance de colateral.

El requerimiento más restrictivo es el del 5% del valor de los tokens GEX bloqueados en otros contratos, usualmente en la acuñación de moneda estable. Este requerimiento será el que limite habitualmente el uso de capital de los pools para préstamos.&#x20;


# Acuñador de Monedas Estables (SC Minter)

El módulo del SC Minter es el punto de acceso principal a la oferta de monedas estables e indexadas de Geminon. Permite a los usuarios intercambiar tokens GEX por alguna de las monedas estables de Geminon, y viceversa.&#x20;

El mecanismo de acuñación y redención es algorítmico. El contrato SC Minter siempre intercambia un valor (medido en dólares US) de tokens GEX por el mismo valor de moneda estable de forma exacta y viceversa. No existe deslizamiento en la operación, únicamente se descuenta la comisión del protocolo.

### Protocolo de acuñación de moneda

Para acuñar nuevo suministro de moneda estable, es necesario entregar una cantidad de tokens GEX, $$V\_G$$. La cantidad de moneda estable acuñada, $$V\_S$$, viene dada por la expresión:

$$
V\_S = V\_G \dfrac {P\_G} {P\_S}
$$

El precio del token GEX, $$P\_G$$, se obtiene del oráculo del protocolo como promedio del precio en todos los pools de la red.

El precio de la moneda estable, $$P\_S$$, se obtiene del contrato de la moneda estable que se está operando. Todas las monedas estables e indexadas de Geminon llevan incorporadas en sus contratos funciones que permiten obtener su valor de cambio en dólares US. Para una información más detallada sobre cómo se obtienen los precios de las monedas estables, consultar las siguientes páginas:

{% content-ref url="/pages/gZ4bslXyZ06uFCosXEUV" %}
[Monedas estables](/geminon-docs-esp/tokens/monedas-estables)
{% endcontent-ref %}

{% content-ref url="/pages/YoocuFs66FR0OyCGUkR8" %}
[Monedas deflacionarias](/geminon-docs-esp/tokens/monedas-deflacionarias)
{% endcontent-ref %}

#### Canjeo de moneda

El proceso para canjear moneda estable es idéntico al de acuñación. Se entrega una cantidad de moneda estable, $$V\_S$$,  a cambio de una cantidad de tokens GEX, $$V\_G$$, que se calcula con la misma expresión usada para la acuñación:

$$
V\_G = V\_S \dfrac {P\_S} {P\_G}
$$

### Ataques de manipulación del precio

Las fórmulas descritas en el punto anterior para el cálculo de las cantidades de moneda estable acuñada dependen directamente de los valores de los precios del token GEX y de la moneda en cuestión. Esto hace que el contrato sea vulnerable a las alteraciones en dichos precios. Los ataques de manipulación de precios son los más habituales en los protocolos de finanzas descentralizadas basados en blockchain. Por este motivo, siempre deben utilizarse fuentes seguras para los precios que no puedan ser manipuladas con facilidad.

El precio de las monedas estables de Geminon proviene de la red de oráculos de Chainlink, que es descentralizada y toma los datos de fuentes externas, por lo que se consideran totalmente seguros.

El precio del token GEX en cambio depende del estado de los pools de liquidez en la red, por lo que es susceptible de manipulación, especialmente mediante préstamos flash. El protocolo Geminon incorpora medidas de seguridad que evitan que dichas manipulaciones del precio puedan tener éxito:

* El precio del token GEX se toma indirectamente a través del oráculo Geminon, que utiliza el precio de los pools al cierre del bloque anterior. Esto hace que los ataques mediante préstamo flash no tengan efecto alguno sobre el precio, ya que las operaciones dentro del bloque actual no se incorporan al cálculo.
* El oráculo Geminon calcula el precio tomando la media de todos los GLP. Esto incrementa el coste para el atacante, ya que es necesario manipular simultáneamente todos los pools.&#x20;
* Los GLP incorporan un algoritmo que filtra las operaciones con volumen anómalo para el cálculo del precio de referencia del pool.&#x20;
* La característica de captura de entropía de los GLP penaliza fuertemente las operaciones que producen un deslizamiento excesivo del precio, lo que hace que el ataque sea inviable económicamente.

Para una información más detallada sobre los mecanismos de seguridad de los GLP consultar las secciones dedicadas:

{% content-ref url="/pages/7dKzO3SqOBnAAPIweNYZ" %}
[Oráculo interno](/geminon-docs-esp/modulos/pools-de-liquidez-genesis-glp/oraculo-interno)
{% endcontent-ref %}

{% content-ref url="/pages/wpedMAl3gNv85WdVLFbR" %}
[Ataques de manipulación de precios](/geminon-docs-esp/modulos/pools-de-liquidez-genesis-glp/ataques-de-manipulacion-de-precios)
{% endcontent-ref %}

### Protocolos de seguridad interna

El contrato SC Minter incorpora los mismos mecanismos de seguridad interna que los contratos GLP. Para una información más detallada consultar la sección previa correspondiente a los protocolos de seguridad de los GLP.


# Intercambio Forex Descentralizado

El módulo de intercambio de moneda estable (ForDEX) está integrado dentro del contrato acuñador (SC Minter) y puede considerarse una extensión de la funcionalidad del mismo. Su función es permitir el intercambio de cualquier par de monedas estables de Geminon sin deslizamiento del precio.

Los sistemas de intercambio de moneda estable (stableswaps) que han implementado la mayoría de protocolos hasta la fecha están basados en pools de liquidez. El sistema propuesto por Geminon es completamente diferente, ya que no utiliza liquidez sino que es puramente algorítmico: aprovecha la capacidad nativa del protocolo para acuñar y quemar monedas, siendo esta la causa de que el módulo de Stableswap de Geminon se haya integrado dentro del contrato del SC Minter. El sistema propuesto por Geminon tiene varias ventajas respecto a los sistemas basados en pools de liquidez:

* No depende de la presencia de actores externos para funcionar. Un stableswap basado en LPs requiere proveedores de liquidez y arbitrajistas que mantengan el precio de cada uno de los pares negociados cerca de su valor de referencia, mientras que nuestro sistema funciona de forma plenamente independiente.&#x20;
* Mejor resultado en las operaciones para los usuarios: se eliminan las ineficiencias propias de la existencia de intermediarios (LPs y arbitrajistas) que obtienen su beneficio precisamente del deslizamiento de los precios, a expensas de los usuarios. Nuestro sistema proporciona siempre un precio exacto en los intercambios independientemente del importe de la operación (liquidez infinita).
* La implementación de la solución algorítmica es notablemente más simple, y por tanto menos propensa a vulnerabilidades.&#x20;

## Ataques por adelantamiento del oráculo (front running)

Las monedas estables de Geminon utilizan los oráculos de Chainlink para obtener los precios respecto al dólar de las monedas fiat que replican en tiempo real. Sin embargo, debido a las características intrínsecas de la tecnología de cadena de bloques, existe un retardo (lag) entre el instante en que se produce la observación del precio en el mercado y el momento en que dicho dato se escribe en la blockchain. Este retardo es la suma del tiempo que tarda la red de Chainlink en alcanzar consenso sobre el valor del dato de precio, el tiempo que tarda Chainlink en enviar la transacción a la blockchain de destino con el nuevo valor y el tiempo que dicha red tarda en procesar la transacción e incluirla en el siguiente bloque. El tiempo total que dura este proceso puede ser mayor a un minuto.

Debido al notable retardo con que el oráculo refleja los precios dentro de la cadena, es en teoría posible para un atacante obtener un beneficio libre de riesgo operando un activo en cadena cuyo precio se fije usando este oráculo, puesto que solo sería necesario observar el precio del activo en el mundo real para conocer de antemano cómo va a cambiar su precio en la blockchain en el futuro inmediato (arbitraje temporal). El ataque solo será económicamente viable si el coste de la operación (gas + comisiones + deslizamiento) es menor que el movimiento esperado del precio. Dado que nuestro sistema no tiene deslizamiento, el umbral de ataque es más bajo y el importe es ilimitado, por lo que se ha diseñado un sistema de seguridad que haga inviables este tipo de ataques.

### Probabilidad del ataque

El mercado Forex es uno de los menos volátiles del mundo, especialmente si se trata de pares mayores como el EUR/USD, cuya volatilidad a una hora casi nunca supera el 0,3%. Esta baja volatilidad hace que la comisión de base que se cobra habitualmente por un intercambio descentralizado en blockchain sea superior al beneficio esperable de casi cualquier operación intradiaria en el mercado de divisas, por lo que la probabilidad de este tipo de ataque en general es bastante baja, dado que además resultaría poco rentable en caso de tener éxito. Sin embargo, dado que el ataque descrito es teóricamente posible si existe la suficiente volatilidad en el mercado, es necesario implementar medidas para asegurar que no pueda llevarse a cabo en ninguna circunstancia.

### Guardia del intercambio de estables (Stableswap Guard)

El contrato StableswapGuard implementa un sistema de seguridad basado en un oráculo de precios interno que rastrea las posiciones globales en moneda estable que se han tomado en los últimos 5 minutos tanto en el SC Minter como en el Stableswap. Cada vez que se realiza una operación en moneda estable, el contrato comprueba si se han abierto posiciones contrarias en los últimos 5 minutos que produzcan un beneficio anormal, y en su caso aplica una comisión de seguridad extra a la operación igual a la volatilidad del periodo entre la apertura y el cierre de la posición eliminando su posible beneficio.

{% hint style="warning" %}
No se recomienda realizar operativa de *scalping* en *timeframes* bajos usando el módulo de Stableswap de Geminon. Al operar compruebe siempre el importe de la comisión aplicada, y en caso de ser más alta de lo normal espere unos minutos para realizar su operación.
{% endhint %}

### Algoritmo del oráculo interno

El algoritmo del StableSwapGuard es similar al utilizado para el oráculo interno de los GLP y para el limitador de acuñación de los tokens de Geminon. Se basa en una media móvil exponencial adaptativa cuyo parámetro varía en función de la relación entre volumen de la operación actual y el volumen total acumulado en los últimos 5 minutos:

$$
\Delta t = t\_n - t\_{n-1}
$$

$$
V\_n = \begin{cases}
\ \ \ \ \ v\_n &\text{if } \Delta t > 300 \\
V\_{n-1}+v\_n &\text{if } \Delta t \le 300
\end{cases}
$$

$$
w\_n = \begin{cases}
\ \ \ \ \ 1 &\text{if } \Delta t > 300 \\
\dfrac {v\_n}{v\_n+V\_n} &\text{if } \Delta t \le 300
\end{cases}
$$

$$
m\_n = w\_n p\_n + (1-w\_n) m\_{n-1}
$$

Donde $$\Delta t$$ es el intervalo de tiempo en segundos transcurrido desde la última operación, $$v\_n$$ es el volumen (en dólares US) de la operación actual y $$p\_n$$ es el precio actual de la moneda estable (en dólares US).&#x20;

El contrato de StableSwapGuard almacena la cantidad anterior para cada moneda estable separando operaciones de compra y operaciones de venta. Para calcular la comisión de seguridad, se compara la diferencia entre precio actual y el valor promedio de las operaciones de signo contrario, y si dicho valor es superior a la comisión de base, se aplica la comisión de seguridad a la operación. &#x20;


# Préstamos

{% hint style="info" %}
El protocolo de préstamos se encuentra actualmente en desarrollo
{% endhint %}


