Quipuswap
  • introduction
    • What is QuipuSwap?
    • Participants
    • QuipuSwap subprojects
      • QuipuSwap Farms
      • Quipuswap Stable DEX
      • Token to Token Swaps
      • Governance (text-only)
  • Get Started
    • Install Wallet
    • How to get TEZ
    • How to find my tokens
    • Connect wallet
    • FAQ
  • Dex Guides
    • Overview
    • Types of the exchange (Token/TEZ, Token/Token)
    • How to use the DEX
      • Trade
      • How to add liquidity to an existing liquidity pool
      • How to create a new liquidity pool
      • How to remove liquidity
      • How to vote for a baker
      • How to ban/veto a baker
  • Tezos Tokens
    • What is a Token?
    • What is the difference between FA1.2 and FA2 standards?
    • QUIPU Tokenomics
  • Smart Contracts
    • Dex token edition
      • Overview
      • Dex
      • Exceptions
    • QuipuSwap stable swap DEX
      • 🛠️Developer module
        • 📄Storage & action types
        • 🔵Developer setter entrypoints
          • set_dev_address
          • set_dev_fee
      • 🏠Standalone DEX
        • 📄Storage and types overview
        • 🟡Initialization
          • set_admin_function
          • set_dev_function
          • set_dex_function
          • set_token_function
        • 🟠Add new dex
          • add_pool
        • 🔵DEX methods
          • invest
          • swap
          • 📤Divesting
            • divest
            • divest_imbalanced
            • divest_one_coin
          • 🤑DEX rewards
            • claim_referral
            • stake
        • 🛠️Developer methods
          • claim_developer
          • Dev module entrypoints
        • 🛑Admin methods
          • add_rem_managers
          • ramp_A
          • set_admin
          • set_fees
          • stop_ramp_A
      • 🏭Factory
        • 📄Storage and types overview
        • 🟡Initial setup
          • set_init_function
          • set_dev_function
          • DEX compiled codebase setup
            • set_admin_function
            • set_dex_function
            • set_token_function
        • 🟠Initialize new DEX flow
          • add_pool
          • start_dex
        • 💱Deployed from factory DEX
          • 📄Storage and types overview
          • 🟡Initialization
            • copy_dex_function
            • freeze
          • 🔵DEX methods
          • 🛠️Claim developer rewards
          • 🛑Admin methods
        • 🛑Developer methods
          • claim_rewards
          • 🧑‍💻Factory management
            • 🟢Factory params
              • set_burn_rate
              • set_price
              • set_whitelist
            • 🔵Dev module entrypoints
    • Dex 2.0
      • ⁉️Errors overview
      • 🥐BakerRegistry contract
        • Storage and types overview
        • Entrypoints overview
          • validate
          • register
      • ⚙️FlashSwapsProxy contract
        • Storage and types overview
        • Entrypoints overview
          • default
      • 🧺Bucket contract
        • Storage and types overview
        • Entrypoints overview
          • fill
          • pour_out
          • pour_over
          • withdraw_rewards
          • ban_baker
          • vote
          • default
        • On-chain views overview
          • is_banned_baker
          • get_tez_balance
          • get_user_candidate
      • ⚖️Auction contract
        • Storage and types overview
        • Entrypoints overview
          • Auction entrypoints
            • receive_fee
            • launch_auction
            • place_bid
            • claim
          • Admin entrypoints
            • set_admin
            • confirm_admin
            • set_baker
            • set_fees
            • set_auction_duration
            • set_min_bid
            • update_whitelist
            • withdraw_dev_fee
            • withdraw_public_fee
            • burn_bid_fee
      • 🏦DexCore contract
        • Storage and types overview
        • Entrypoints overview
          • DEX entrypoints
            • launch_exchange
            • invest_liquidity
            • divest_liquidity
            • swap
            • withdraw_profit
            • claim_interface_fee
            • claim_interface_tez_fee
            • withdraw_auction_fee
            • vote
          • Admin entrypoints
            • set_admin
            • confirm_admin
            • set_flash_swaps_proxy
            • set_auction
            • add_managers
            • set_fees
            • set_collecting_period
            • update_token_metadata
            • ban
          • Permits' entrypoints
            • permit
            • set_expiry
          • FA2 entrypoints
            • transfer
            • update_operators
            • balance_of
          • Callbacks
            • launch_callback
            • flash_swap_callback
            • close
        • On-chain views overview
          • check_is_banned_baker
          • get_reserves
          • get_total_supply
          • get_swap_min_res
          • get_toks_per_share
          • get_cumulative_prices
          • get_collecting_period
    • Trusted contracts
    • Farming
      • Referral system overview
      • Fees overview
      • Rewards precision overview
      • BakerRegistry contract
        • Storage and types overview
        • Entrypoints overview
          • validate
          • register
      • Burner contract
        • Storage and types overview
        • Entrypoints overview
          • default
          • burn_callback
      • ProxyMinter contract
        • Storage and types overview
        • Entrypoints overview
          • Admin entrypoints
            • add_minter
            • withdraw_tokens
            • set_admin
            • confirm_admin
          • Minter entrypoint
            • mint_tokens
      • QFarm contract
        • Storage and types overview
        • Entrypoints overview
          • Farming entrypoints
            • deposit
            • withdraw
            • harvest
          • FA2 entrypoints
            • transfer
            • update_operators
            • balance_of
          • Admin entrypoints
            • set_admin
            • confirm_admin
            • set_fees
            • set_reward_per_second
            • set_burner
            • set_proxy_minter
            • set_baker_registry
            • set_is_v1_lp
            • ban_bakers
            • add_new_farm
            • pause_farms
            • burn_tez_rewards
            • withdraw_farm_depo
            • update_token_metadata
          • Other entrypoints
            • burn_farm_rewards
            • default
      • TFarm contract
        • Storage and types overview
        • Entrypoints overview
          • Farming entrypoints
            • deposit
            • withdraw
            • harvest
          • FA2 entrypoints
            • transfer
            • update_operators
            • balance_of
          • Admin entrypoints
            • set_admin
            • confirm_admin
            • set_fees
            • set_reward_per_second
            • set_burner
            • set_baker_registry
            • set_is_v1_lp
            • ban_bakers
            • add_new_farm
            • pause_farms
            • burn_tez_rewards
            • claim_farm_rewards
            • withdraw_farm_depo
            • update_token_metadata
          • Other entrypoints
            • default
  • Brand and Logos
Powered by GitBook
On this page
  • Swap
  • Call parameters
  • Usage
  • Errors
  • Flash swap
  • Call parameters
  • Usage
  • Lambda function example
  • Errors
  1. Smart Contracts
  2. Dex 2.0
  3. DexCore contract
  4. Entrypoints overview
  5. DEX entrypoints

swap

In the current implementation, under the hood, all swaps are actually flash swaps. This simply means that contract sends output tokens to the recipient before enforcing that enough input tokens have been received. This is slightly atypical, as one might expect a pair to ensure it's received payment before delivery. However, because Tezos transactions are atomic, we can roll back the entire swap if it turns out that the contract hasn't received enough tokens to make itself whole by the end of the transaction.

Below you can find detailed description of both use cases: simple swap and flash swap.

Swap

An entrypoint that executes swaps in different liquidity pools (pairs).

All possible routes for swaps are allowed. For example: FA1.2->TEZ, TEZ->FA1.2, FA2->TEZ, TEZ->FA2, FA1.2->FA1.2, FA2->FA2, FA1.2->FA2, FA2->FA1.2.

Multi token routes are allowed too. For example: FA1.2->FA2->TEZ->FA2, TEZ->FA2->FA1.2->TEZ, FA2->TEZ->FA2->TEZ->FA1.2.

Call parameters

type token_id_t         is nat

type swap_direction_t   is
| A_to_b
| B_to_a

type swap_slice_t       is [@layout:comb] record [
  direction               : swap_direction_t;
  pair_id                 : token_id_t;
]

type swap_t             is [@layout:comb] record [
  lambda                  : option(unit -> list(operation));
  swaps                   : list(swap_slice_t);
  deadline                : timestamp;
  receiver                : address;
  referrer                : address;
  amount_in               : nat;
  min_amount_out          : nat;
]

swap_slice_t

Field
Type
Description

direction

swap_direction_t

Swap direction: A->B or B->A

pair_id

token_id_t (nat)

ID of a pair in which swap will be executed

get_swap_min_res_t

Field
Type
Description

lambda

option(unit -> list(operation))

Users's lambda function that doesn't accept any parameters (unit) and returns a list of operations (transactions, calls). Must be None in case of simple swap

swaps

A route of a swap

deadline

timestamp

The time until which the transaction remains valid and will not be rejected

receiver

address

The receiver of exchanged tokens

referrer

address

Referrer to whom interface fee will be paid

amount_in

nat

Amount of tokens to swap from

min_amount_out

nat

The minimum number of outgoing tokens that the user agrees to

Usage

You need to pass positive TEZ/mutez amount to the send() method in case of TEZ->FA1.2 or TEZ -> FA2 swaps (see example below).

const dexCoreAddress = "KT1...";
const parmas = {
    lambda: undefined, // or null
    swaps: [
        {
            direction: {
                a_to_b: undefinded,
            },
            pair_id: 1,
        },
        ...
    ],
    deadline: String(Date.parse((await tezos.rpc.getBlockHeader()).timestamp) / 1000 + 100),
    receiver: "tz1.../KT1...",
    referrer: "tz1.../KT1...",
    amount_in: 1000,
    min_amount_out: 998,
};
const dexCore = await tezos.contract.at(dexCoreAddress);
const operation = await dexCore.methodsObject.swap(parmas).send({ amount: parmas.amount_in, mutez: true });

await operation.confirmation();

Errors

  • 108 - pair (pool) with the specified token_id not listed.

  • 109 - pair doesn't have a liquidity.

  • 116 - high expectations of output tokens.

  • 117 - empty route of swaps.

  • 118 - zero amount in was passed as the parameter.

  • 119 - wrong route of a swap.

  • 120 - wrong TEZ amount were passed to the transaction.

  • 130 - referring on yourself is forbidden.

  • 136 - reentrancy.

  • 139 - too few swaps.

  • 144 - action outdated (the time until which the transaction remained valid was passed).

  • 412 - non payable entrypoint (can't accept TEZ tokens during call of an entrypoint). Only in case of swapping NOT from TEZ token.

Flash swap

An entrypoint that allows to make a flash swaps. QuipuSwap flash swaps allows you to exchange up to the full reserves of any FA1.2/FA2/TEZ token on QuipuSwap and execute arbitrary logic at no upfront cost, provided that by the end of the transaction you will pay for the withdrawn FA1.2/FA2/TEZ tokens with the corresponding pair tokens.

All possible routes for swaps are allowed. Also, supports multi token routes.

Call parameters

type token_id_t         is nat

type swap_direction_t   is
| A_to_b
| B_to_a

type swap_slice_t       is [@layout:comb] record [
  direction               : swap_direction_t;
  pair_id                 : token_id_t;
]

type swap_t             is [@layout:comb] record [
  lambda                  : option(unit -> list(operation));
  swaps                   : list(swap_slice_t);
  deadline                : timestamp;
  receiver                : address;
  referrer                : address;
  amount_in               : nat;
  min_amount_out          : nat;
]

swap_slice_t

Field
Type
Description

direction

swap_direction_t

Swap direction: A->B or B->A

pair_id

token_id_t (nat)

ID of a pair in which swap will be executed

get_swap_min_res_t

Field
Type
Description

lambda

option(unit -> list(operation))

Users's lambda function that doesn't accept any parameters (unit) and returns a list of operations (transactions, calls)

swaps

A route of a swap

deadline

timestamp

The time until which the transaction remains valid and will not be rejected

receiver

address

The receiver of exchanged tokens

referrer

address

Referrer to whom interface fee will be paid

amount_in

nat

Amount of tokens to swap from

min_amount_out

nat

The minimum number of outgoing tokens that the user agrees to

Usage

import { execSync } from "child_process";

function parseSwaps(swaps) {
    let result = "list [ ";

    for (const swap of swaps) {
        const direction =
          Object.keys(swap.direction)[0].charAt(0).toUpperCase() +
          Object.keys(swap.direction)[0].substring(1);
 
        result += `record [ direction = ${direction}; pair_id = ${swap.pair_id.toString()}n; ]; `;
    }

    return result + " ]";
}

const dexCoreAddress = "KT1...";
const mutezAmount = 100;
const params = {
    lambda: undefined,
    swaps: [{ direction: { a_to_b: undefined }, pair_id: 0 }],
    deadline: String(Date.parse((await tezos.rpc.getBlockHeader()).timestamp) / 1000 + 100),
    receiver: "KT1...", // a contract that will execute arbitrary logic or do smth with received tokens
    referrer: "tz1...",
    amount_in: 1000,
    min_amount_out: 1,
};
const stdout = execSync(
    `${ligo} compile parameter ${lambda_file} 'Use(Swap(record [ lambda = Some(${lambda_name}); swaps = ${parseSwaps(
      params.swaps
    )}; deadline = (${params.deadline} : timestamp); receiver = ("${
      params.receiver
    }" : address); referrer = ("${
      params.referrer
    }" : address); amount_in = ${params.amount_in.toString()}n; min_amount_out = ${params.min_amount_out.toString()}n ] ))' -p hangzhou --michelson-format json`,
    { maxBuffer: 1024 * 500 }
).toString();
const operation = await tezos.contract.transfer({
    to: dexCoreAddress,
    amount: mutezAmount,
    mutez: true,
    parameter: {
        entrypoint: "use",
        value: JSON.parse(stdout).args[0],
    },
    fee: 1000000,
    gasLimit: 1040000,
    storageLimit: 20000,
});

await operation.confirmation();

Lambda function example

FlashSwapAgent - contract that implements different arbitrary logic.

const agent : address = ("KT1LZjpR3hysVYyji1bfgNHJAuZhiQApUd71" : address);
const val : nat = 100n;

function get_flash_swap_agent_default_entrypoint(
  const agent           : address)
                        : contract(nat) is
  Tezos.get_contract_with_error(agent, "FlashSwapAgent/default-entrypoint-404")

function lambda(const _ : unit) : list(operation) is
  list [
    Tezos.transaction(
      val,
      0mutez,
      get_flash_swap_agent_default_entrypoint(agent)
    )
  ]

Errors

  • 108 - pair (pool) with the specified token_id not listed.

  • 109 - pair doesn't have a liquidity.

  • 116 - high expectations of output tokens.

  • 117 - empty route of swaps.

  • 118 - zero amount in was passed as the parameter.

  • 119 - wrong route of a swap.

  • 120 - wrong TEZ amount were passed to the transaction.

  • 130 - referring on yourself is forbidden.

  • 136 - reentrancy.

  • 139 - too few swaps.

  • 144 - action outdated (the time until which the transaction remained valid was passed).

  • 412 - non payable entrypoint (can't accept TEZ tokens during call of an entrypoint). Only in case of swapping NOT from TEZ token.

Previousdivest_liquidityNextwithdraw_profit

Last updated 3 years ago

list()

Also don't forget to add the contract as the operator for your FA2 tokens or make an approve for spending of FA1.2 tokens in time of FA1.2/FA2->FA1.2/FA2/TEZ swaps.

After execution of user's lambda, entrypoint will be executed (only in case of TEZ tokens loan).

list()

all errors from the entrypoint.

🏦
DexCore
flash_swap_callback
flash_swap_callback
swap_slice_t
swap_slice_t