Skip to content

Commit

Permalink
Add instantiate2 create pair message
Browse files Browse the repository at this point in the history
  • Loading branch information
tasiov committed Aug 22, 2023
1 parent 3b38f7e commit 47e8592
Show file tree
Hide file tree
Showing 20 changed files with 1,228 additions and 166 deletions.
930 changes: 886 additions & 44 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["contracts/*", "packages/*"]
members = ["contracts/*", "packages/*", "unit-tests"]

[workspace.package]
version = "0.1.0"
Expand Down
42 changes: 21 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,54 +16,54 @@ INFINITY SWAP IS PROVIDED “AS IS”, AT YOUR OWN RISK, AND WITHOUT WARRANTIES

## Overview

Infinity Swap is an automated market maker (AMM) protocol that allows for the buying and selling of NFT assets with a specified fungible token. The buy and sell price of the NFT assets are determined by the parameters of the pool, the bonding curve, and the assets custodied by the pool.
Infinity Swap is an automated market maker (AMM) protocol that allows for the buying and selling of NFT assets with a specified fungible token. The buy and sell price of the NFT assets are determined by the parameters of the pair, the bonding curve, and the assets custodied by the pair.

Infinity Swap makes use of an NFT AMM design, but is written for [CosmWasm](https://github.com/CosmWasm/cosmwasm) so that it may be used on Cosmos SDK based chains.

## Features

- Pool pricing indexed within the contract for optimized price discovery
- Pair pricing indexed within the contract for optimized price discovery
- Respects listing price of marketplace contract
- Respects the minimum price of marketplace contract
- Respects the maximum finders fee of marketplace contract
- Respects the trading fee percentage of the marketplace contract
- Pool owner can set a finders fee that is paid to the finder address on a trade
- Pool owner can set a swap fee that is paid to the pool owner of a Trade pool
- Reinvestment of tokens and NFTs back into Trade pools based on parameter flags
- Flexible asset redirection for trader and pool owner
- Pair owner can set a finders fee that is paid to the finder address on a trade
- Pair owner can set a swap fee that is paid to the pair owner of a Trade pair
- Reinvestment of tokens and NFTs back into Trade pairs based on parameter flags
- Flexible asset redirection for trader and pair owner
- Queries that allow for simulation of swaps
- User slippage tolerance for swaps
- User may decide to revert whole transaction or revert individual swaps using the robust flag

## How It Works

1. Liquidity providers begin by creating a pool with specific parameters. They define which pools the assets will hold and the bonding curve which will be used to determine the price. Once the pool is created, liquidity providers can deposit tokens and/or NFTs into the pool. Once the pool is funded, liquidity providers can activate the pool so that it can begin trading.
2. Traders can then buy and sell NFTs from the pool. The price of the NFTs is determined by the bonding curve and the assets held by the pool. The price of the NFTs will change as the pool is traded.
3. Liquidity providers can withdraw their assets from the pool at any time.
1. Liquidity providers begin by creating a pair with specific parameters. They define which pairs the assets will hold and the bonding curve which will be used to determine the price. Once the pair is created, liquidity providers can deposit tokens and/or NFTs into the pair. Once the pair is funded, liquidity providers can activate the pair so that it can begin trading.
2. Traders can then buy and sell NFTs from the pair. The price of the NFTs is determined by the bonding curve and the assets held by the pair. The price of the NFTs will change as the pair is traded.
3. Liquidity providers can withdraw their assets from the pair at any time.

### Creating Pools
### Creating Pairs

Creating pools follows a three message process where the first message creates the pool, the second message deposits assets into the pool, and the third message activates the pool. The three messages can be concatenated into a single transaction by the client.
Creating pairs follows a three message process where the first message creates the pair, the second message deposits assets into the pair, and the third message activates the pair. The three messages can be concatenated into a single transaction by the client.

![Screenshot 2023-01-31 at 10 45 07 AM](https://user-images.githubusercontent.com/6496257/215807687-3dca764a-5178-4eb9-8503-7c360c5e0954.png)

### Types of Pools
### Types of Pairs

The `pool_type` parameter refers to the asset that the pool holds:
The `pair_type` parameter refers to the asset that the pair holds:

- A `Token` pool has funglible tokens that it is willing to give to traders in exchange for NFTs. This is similar to a buy limit order.
- An `Nft` pool has NFTs that it is willing to give to traders in exchange for tokens. This is similar to a sell limit order.
- A `Trade` pool allows for both TOKEN-->NFT and NFT-->TOKEN swaps. This is similar to a double-sided order book. This type is the only type that supports swap fees.
- A `Token` pair has funglible tokens that it is willing to give to traders in exchange for NFTs. This is similar to a buy limit order.
- An `Nft` pair has NFTs that it is willing to give to traders in exchange for tokens. This is similar to a sell limit order.
- A `Trade` pair allows for both TOKEN-->NFT and NFT-->TOKEN swaps. This is similar to a double-sided order book. This type is the only type that supports swap fees.

### Types of bonding curves

- A `Linear` bonding curve has a constant slope, meaning that the price of an NFT increases or decreases by a constant amount with each NFT that is bought or sold to the pool.
- A `Exponential` bonding curve has a slope that increases or decreases by a percentage with each NFT that is bought or sold to the pool.
- A `Linear` bonding curve has a constant slope, meaning that the price of an NFT increases or decreases by a constant amount with each NFT that is bought or sold to the pair.
- A `Exponential` bonding curve has a slope that increases or decreases by a percentage with each NFT that is bought or sold to the pair.
- A `Constant Product` bonding curve specifies that the product of two reserve assets remains constant after every trade.

### Performing Swaps

Traders can buy and sell NFTs from the pool. The price of the NFTs is determined by the bonding curve and the assets held by the pool. The price of the NFTs will change as the pool is traded.
Traders can buy and sell NFTs from the pair. The price of the NFTs is determined by the bonding curve and the assets held by the pair. The price of the NFTs will change as the pair is traded.

The user flow for performing swaps is as follows:

Expand All @@ -78,8 +78,8 @@ The user flow for performing swaps is as follows:

These are the types of swaps that can be performed by the contract. Note that each swap can be be run as an ExecuteMsg or a QueryMsg. When run as an ExecuteMsg the full swap is performed and assets are transferred to their proper destination. When run as a query, the swap is performed in simulation mode and the results are returned to the client, but assets are not transferred.

- `DirectSwapNftsForTokens` - Swap NFTs for tokens directly with a specified pool
- `DirectSwapNftsForTokens` - Swap NFTs for tokens directly with a specified pair
- `SwapNftsForTokens` - Swap NFTs for tokens at optimal sale prices
- `DirectSwapTokensForNfts` - Swap tokens for NFTs directly with a specified pool
- `DirectSwapTokensForNfts` - Swap tokens for NFTs directly with a specified pair
- `SwapTokensForSpecificNfts` - Swap tokens for specific NFTs at optimal purchase prices
- `SwapTokensForAnyNfts` - Swap tokens for any NFTs at optimal purchase prices
2 changes: 1 addition & 1 deletion contracts/infinity-builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use cosmwasm_std::{
Instantiate2AddressError, MessageInfo, StdError, StdResult, WasmMsg,
};
use cw2::set_contract_version;
use infinity_factory::InstantiateMsg as InfinityFactoryInstantiateMsg;
use infinity_factory::msg::InstantiateMsg as InfinityFactoryInstantiateMsg;
use infinity_global::{GlobalConfig, InstantiateMsg as InfinityGlobalInstantiateMsg};
use infinity_index::msg::InstantiateMsg as InfinityIndexInstantiateMsg;
use infinity_router::msg::InstantiateMsg as InfinityRouterInstantiateMsg;
Expand Down
13 changes: 13 additions & 0 deletions contracts/infinity-factory/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use cosmwasm_std::Instantiate2AddressError;
use cosmwasm_std::StdError;

use thiserror::Error;

#[derive(Error, Debug, PartialEq)]
pub enum ContractError {
#[error("{0}")]
Std(#[from] StdError),

#[error("{0}")]
Instantiate2AddressError(#[from] Instantiate2AddressError),
}
71 changes: 71 additions & 0 deletions contracts/infinity-factory/src/execute.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use crate::helpers::generate_salt;
use crate::msg::ExecuteMsg;
use crate::state::{INFINITY_GLOBAL, SENDER_COUNTER};
use crate::ContractError;

use cosmwasm_std::{to_binary, DepsMut, Env, MessageInfo, WasmMsg};
use infinity_global::load_global_config;
use infinity_pair::msg::InstantiateMsg as InfinityPairInstantiateMsg;
use sg_std::Response;

#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::CreatePair {
pair_immutable,
pair_config,
} => {
let infinity_global = INFINITY_GLOBAL.load(deps.storage)?;
let global_config = load_global_config(&deps.querier, &infinity_global)?;

let response = Response::new().add_message(WasmMsg::Instantiate {
admin: Some(env.contract.address.into()),
code_id: global_config.infinity_pair_code_id,
label: "Infinity Pair".to_string(),
msg: to_binary(&InfinityPairInstantiateMsg {
infinity_global: infinity_global.to_string(),
pair_immutable,
pair_config,
})?,
funds: info.funds,
});

Ok(response)
},
ExecuteMsg::CreatePair2 {
pair_immutable,
pair_config,
} => {
let infinity_global = INFINITY_GLOBAL.load(deps.storage)?;
let global_config = load_global_config(&deps.querier, &infinity_global)?;

let counter =
SENDER_COUNTER.may_load(deps.storage, info.sender.clone())?.unwrap_or_default();
let salt = generate_salt(&info.sender, counter);
SENDER_COUNTER.save(deps.storage, info.sender.clone(), &(counter + 1))?;

let response = Response::new().add_message(WasmMsg::Instantiate2 {
admin: Some(env.contract.address.into()),
code_id: global_config.infinity_pair_code_id,
label: "Infinity Pair".to_string(),
msg: to_binary(&InfinityPairInstantiateMsg {
infinity_global: infinity_global.to_string(),
pair_immutable,
pair_config,
})?,
funds: info.funds,
salt,
});

Ok(response)
},
}
}
34 changes: 34 additions & 0 deletions contracts/infinity-factory/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use crate::ContractError;

use cosmwasm_std::{instantiate2_address, Addr, Binary, Deps, Env};
use sha2::{Digest, Sha256};

pub fn generate_salt(sender: &Addr, counter: u64) -> Binary {
let mut hasher = Sha256::new();
hasher.update(sender.as_bytes());
hasher.update(&counter.to_be_bytes());
hasher.finalize().to_vec().into()
}

pub fn generate_instantiate_2_addr(
deps: Deps,
env: &Env,
sender: &Addr,
counter: u64,
code_id: u64,
) -> Result<(Addr, Binary), ContractError> {
let code_res = deps.querier.query_wasm_code_info(code_id)?;

let salt = generate_salt(&sender, counter);

// predict the contract address
let addr_raw = instantiate2_address(
&code_res.checksum,
&deps.api.addr_canonicalize(env.contract.address.as_str())?,
&salt,
)?;

let addr = deps.api.addr_humanize(&addr_raw)?;

Ok((addr, salt))
}
30 changes: 30 additions & 0 deletions contracts/infinity-factory/src/instantiate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use crate::msg::InstantiateMsg;
use crate::state::INFINITY_GLOBAL;

use cosmwasm_std::StdError;
use cosmwasm_std::{DepsMut, Env, MessageInfo};
use cw2::set_contract_version;
use sg_std::Response;

#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;

pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, StdError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;

INFINITY_GLOBAL.save(deps.storage, &deps.api.addr_validate(&msg.infinity_global)?)?;

Ok(Response::new()
.add_attribute("action", "instantiate")
.add_attribute("contract_name", CONTRACT_NAME)
.add_attribute("contract_version", CONTRACT_VERSION))
}
93 changes: 8 additions & 85 deletions contracts/infinity-factory/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,87 +1,10 @@
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{to_binary, Addr, Binary, Deps, DepsMut, Empty, Env, MessageInfo, StdResult};
use cosmwasm_std::{StdError, WasmMsg};
use cw2::set_contract_version;
use cw_storage_plus::Item;
use infinity_global::load_global_config;
use infinity_pair::msg::InstantiateMsg as InfinityPairInstantiateMsg;
use infinity_pair::state::{PairConfig, PairImmutable};
use sg_std::Response;
pub mod execute;
pub mod helpers;
pub mod instantiate;
pub mod msg;
pub mod query;
pub mod state;

#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
mod error;

pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

pub const INFINITY_GLOBAL: Item<Addr> = Item::new("g");

#[cw_serde]
pub struct InstantiateMsg {
/// The address of the infinity global contract
pub infinity_global: String,
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, StdError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;

INFINITY_GLOBAL.save(deps.storage, &deps.api.addr_validate(&msg.infinity_global)?)?;

Ok(Response::new()
.add_attribute("action", "instantiate")
.add_attribute("contract_name", CONTRACT_NAME)
.add_attribute("contract_version", CONTRACT_VERSION))
}

#[cw_serde]
pub enum ExecuteMsg {
CreatePair {
/// The immutable parameters of the pair
pair_immutable: PairImmutable<String>,
/// The user configurable parameters of the pair
pair_config: PairConfig<String>,
},
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, StdError> {
match msg {
ExecuteMsg::CreatePair {
pair_immutable,
pair_config,
} => {
let infinity_global = INFINITY_GLOBAL.load(deps.storage)?;
let global_config = load_global_config(&deps.querier, &infinity_global)?;

let response = Response::new().add_message(WasmMsg::Instantiate {
admin: Some(env.contract.address.into()),
code_id: global_config.infinity_pair_code_id,
label: "InfinityPair".to_string(),
msg: to_binary(&InfinityPairInstantiateMsg {
infinity_global: infinity_global.to_string(),
pair_immutable,
pair_config,
})?,
funds: info.funds,
});

Ok(response)
},
}
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(_deps: Deps, _env: Env, _msg: Empty) -> StdResult<Binary> {
unimplemented!()
}
pub use crate::error::ContractError;
41 changes: 41 additions & 0 deletions contracts/infinity-factory/src/msg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::{Addr, Binary};
use infinity_pair::state::{PairConfig, PairImmutable};

#[cw_serde]
pub struct InstantiateMsg {
/// The address of the infinity global contract
pub infinity_global: String,
}

#[cw_serde]
pub enum ExecuteMsg {
CreatePair {
/// The immutable parameters of the pair
pair_immutable: PairImmutable<String>,
/// The user configurable parameters of the pair
pair_config: PairConfig<String>,
},
CreatePair2 {
/// The immutable parameters of the pair
pair_immutable: PairImmutable<String>,
/// The user configurable parameters of the pair
pair_config: PairConfig<String>,
},
}

#[cw_serde]
pub struct NextPairResponse {
pub sender: Addr,
pub pair: Addr,
pub salt: Binary,
}

#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
#[returns(NextPairResponse)]
NextPair {
sender: String,
},
}
Loading

0 comments on commit 47e8592

Please sign in to comment.