Castore  DeRose

Castore DeRose

1665472980

Top 10 Insurance Crypto Projects

Insurance covers damage inflicted by unpredictable events. Highly volatile cryptocurrency often makes headlines as the target of multimillion-dollar hacks, leading to investors losing millions and the sector shedding billions.

Among the high-profile thefts include hackers who stole about $615 million from a blockchain project connected to the popular game Axie Infinity, and $23.3 million from Ronin, a network that facilitates the transfer of crypto coins across different blockchains, according to Reuters.

In this article you will see Top 10 Insurance Crypto Projects by Volume, 11/10/2022

1. Wrapped NXM - WNXM

DescribePrice overviewWebsite

WrappedNXM (wNXM) is a 1-to-1 backed token generated by wrapping genuine NXM. In brief, wrapped tokens are the cryptocurrencies that are pegged or attached to the value of another crypto or assets. Thus, it bypasses the limitation of transferring native coins, i.e., tokens that reside on native blockchains.

NXM is an ERC20-compatible token of the Nexus Mutual protocol, a decentralized alternative to insurance. Nexus Mutual is a digital cooperative that complies with the relevant laws and regulations of the country from where it accepts members.

The project aims to provide the community members with simple, transparent, accessible, and affordable financial protection against their risks. Although fully tradable, wNXM cannot be used within the Nexus Mutual platform. Since NXM is traded only among members, only Nexus Mutual members can wrap/unwrap NXM.

Get WNXM
Link

2. InsurAce - INSUR

DescribePrice overviewWebsite

InsurAce.io is a decentralized protocol that aims to offer reliable insurance services. The protocol provides decentralized finance (DeFi) assets with flexible and reliable coverage. The claimed benefits for users include low insurance premiums, high return on investment, cross-chain coverage and wallet availability.

InsurAce.io is both a DeFi and an insurance protocol. Thus, it has two platforms: insurance and investment. They function in a synergetic manner to provide stable profit to the insured, the insurer and the investor and offer what the platform calls zero-premium insurance.

According to the developers, portfolio-based product design and a unique pricing model coupled with sustainable investment returns, allows users to achieve ultra-low premiums that are close to zero

Users have the option to remain anonymous, avoiding a KYC process.

Buy INSUR
Link

3. inSure - SURE

DescribePrice overviewWebsite

inSure DeFi is a community-based crypto asset insurance ecosystem, where users can insure their crypto-portfolio by buying SURE tokens with fiat and other cryptocurrencies. inSure is designed to distribute crypto ownership risks amongst a liquidity pool, with insurance premiums determined by a Dynamic Pricing Model that leverages Chainlink.

inSure DeFi is a Decentralized Insurance Ecosystem, trusted by thousands of community members to protect their crypto portfolios from scams, exchange closures, and drastic devaluations. inSure DeFi provides insurance solutions for the crypto space to stabilize and secure Crypto & DeFi portfolios.

Buy SURE
Link

4. Nsure.Network - NSURE

DescribePrice overviewWebsite

Nsure is an open insurance platform for Open Finance. The project borrows the idea of Lloyd’s London, a market place to trade insurance risks, where premiums are determined by a Dynamic Pricing Model.

Capital mining will be implemented to secure capital required to back the risks at any point of time.

A 3-phase crowd voting mechanism is used to ensure every claim is handled professionally.

Buy NSURE
Link

5. Tidal Finance - TIDAL

DescribePrice overviewWebsite

TIDAL is a Balancer-like insurance market built upon Polkadot that allows users to create custom insurance pools for one or more assets.

By rewarding pool creators with a portion of the return from their deposits, the maximization of capital efficiency attracts LP’s, while the offering of a competitive insurance premium attracts buyers.

Buy TIDAL
Link

6. Uno Re - UNO

DescribePrice overviewWebsite

UnoRe will be the world’s first reinsurance trading platform powered by Polkadot. We will allow the community to invest and achieve sizable returns from one of the safest asset classes in the world.

The platform will remove barriers to entry for investors with regards to capital and regulations, while also encouraging the people to take part in the process of insurance and reinsurance.

UnoRe will allow the community to design innovative insurance products thus propelling a new generation of Insuretech based companies on the UnoRe ecosystem.

Buy UNO
Link

7. Helmet.insure - HELMET

DescribePrice overviewWebsite

Helmet allows users to create an insurance policy for any crypto asset in the market, protecting DeFi users against the risk of price fluctuations. Policy trading on Helmet is market-oriented without complex mathematics. There are two kinds of policy on Helmet: SHORT Tokens and LONG tokens.

Helmet also adds a mining part in its hedging tool, allowing DeFi users to enjoy yield farming while trading. Helmet supports different tokens like Ether (ETH), CAKE and BNB. Users can swap the tokens by connecting their wallets to the platform.
 

Buy HELMET
Link

8. Bridge Mutual - BMI

DescribePrice overviewWebsite

Bridge Mutual is a decentralized, discretionary p2p/p2b insurance platform that provides coverage for stablecoins, centralized exchanges, and smart contracts.

Its platform allows users to provide insurance coverage, decide on insurance payouts, and get compensated for taking part in the ecosystem.
 

Buy BMI
Link

9. CoverCompared - CVR

DescribePrice overviewWebsite

Founded in late 2019, Polkacover is working towards creating the world’s leading cryptocurrency-friendly insurance purchase & policy issuance marketplace with the aim to be the one stop-shop for crypto & personal insurance need..

At Polkacover, we will connect users & multi-national insurance providers with all global insurance products such as crypto related protection, health, life, education & family insurance plans to start with and would be working towards adding more products in the longer run. The platform would providing several tokenized incentives making upto 40% cheaper than any traditional insurance channel.

Buy CVR
Link

10. Etherisc DIP Token - DIP

DescribePrice overviewWebsite

Etherisc claims to be building a platform for decentralized insurance applications.

The project aims to use blockchain technology to help make the purchase and sale of insurance more efficient, enable lower operational costs, provide greater transparency into the industry and democratize access to reinsurance investments.

Buy DIP
Link

11. iTrust Governance - ITG

DescribePrice overviewWebsite

iTrust.finance creates mutually beneficial relationships between stakers and insurance protocols by maximising rewards and growing cover capacity for all participants of the DAO, and the wider DeFi ecosystem.

From launch, the iTrust platform will build a bridge to optimised staking for $wNXM token holders who cannot receive rewards via the Nexus Mutual platform, and $NXM holders who have been reluctant to stake or have been staking inefficiently.

The resulting increase in staked tokens and engaged stakers will allow the underlying cover protocols to unlock cover capacity.

Buy ITG
Link

Data sources: Coinmarketcap


How and Where to Buy Insurance tokens ?

You will have to first buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

We will use Binance Exchange here as it is one of the largest crypto exchanges that accept fiat deposits.

Once you finished the KYC process. You will be asked to add a payment method. Here you can either choose to provide a credit/debit card or use a bank transfer, and buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

☞ SIGN UP ON BINANCE

Once finished you will then need to make a BTC/ETH/USDT/BNB deposit to the exchange from Binance depending on the available market pairs. After the deposit is confirmed you may then purchase Coin/Token from the Binance exchange.

Read more: Top Coins of Centralized Exchange (CEX) by Volume

Thank you for reading !

#blockchain #bitcoin #cryptocurrency #coin #token #dex 

Top 10 Insurance Crypto Projects
Castore  DeRose

Castore DeRose

1664858400

Top 30 tokens of Decentralized Exchange (DEX)

In this article you will see Top 30 tokens of Decentralized Exchange (DEX) by Volume, date: 4/10/2022

Name/Coin/TokenDescribePrice overviewWebsite
Uniswap - UNI

Uniswap is a popular decentralized trading protocol, known for its role in facilitating automated trading of decentralized finance (DeFi) tokens.

An example of an automated market maker (AMM), Uniswap launched in November 2018, but has gained considerable popularity this year thanks to the DeFi phenomenon and associated surge in token trading.

By automating the process of market making, the protocol inceventizes activity by limiting risk and reducing costs for all parties. The mechanism also removes identity requirements for users, and technically anyone can create a liquidity pool for any pair of tokens.

Uniswap is not just a decentralized exchange; it attempts to solve the issues that platforms such as EtherDelta experienced with liquidity.

Uniswap aims to keep token trading automated and completely open to anyone who holds tokens, while improving the efficiency of trading versus that on traditional exchanges.

Buy UNI
Link
PancakeSwap - CAKE

PancakeSwap is an automated market maker (AMM) — a decentralized finance (DeFi) application that allows users to exchange tokens, providing liquidity via farming and earning fees in return.

PancakeSwap uses an automated market maker model, meaning that there are no order books and liquidity pools are used instead. A user can earn income by becoming a liquidity provide; by adding their tokens to the liquidity pool they can farm LP tokens and stake their CAKE to earn rewards. They can also try their luck with the lotteries and non-fungible tokens.

The PancakeSwap token CAKE is a BEP20 token that originally launched on Binance Smart Chain. The main function of CAKE is to incentivize the liquidity provision to the PancakeSwap platform.

Users can stake their tokens to earn rewards, which is done by depositing Liquidity Provider tokens and locking them up. This is known as farming and is rewarded by the system with CAKE tokens. The tokens can be un-staked with zero holding time. CAKE gives users the opportunity to invest and increase returns in the future but comes with risks.

CAKE can be used to enter a lottery on PancakeSwap. Each lottery session takes 6 hours. A single ticket costs 10 CAKE and comes with a random combination of four numbers between 1 and 14, for example, 8-6-4-13. To win the jackpot, which equals 50% of the entire lottery pool, the numbers in your ticket need to match all four of the numbers in the winning ticket.

Buy CAKE
Link
DODO - DODO

DODO is a DeFi protocoldecentralized finance (DeFi) protocol and on-chain liquidity provider whose unique proactive market maker (PMM) algorithm aims to offer better liquidity and price stability than automated market makers (AMM).

The PMM pricing mechanism, which mimics human trading, utilizes oracles to gather highly accurate market prices for assets. It then provides enough liquidity close to these prices in order to stabilize the portfolios of liquidity providers (LP), lower price slippage and negate impermanent loss by allowing arbitrage trading as reward.

The PMM collects funds near market prices to establish enough liquidity, which drops quickly the further the price moves from the market price. DODO automatically adjusts market prices in order to attract arbitrage that will help keep liquidity provider portfolios stable.

For traders, DODO offers sufficient liquidity comparable to that of centralized exchanges (CEX), which can be natively used by smart contracts for on-chain transactions such as liquidation and auctions. Arbitrageurs can also take advantage of price differences between DODO and other exchanges.

Liquidity providers are not required to make a minimum deposit and are not restricted on the type of asset they provide. LPs can create their own trading pairs, deposit their own tokens to negate price risk and also collect a portion of DODO transaction fees as rewards.

DODO also attracts new crypto projects with a free listing as an Initial DODO Offering (IDO). Unlike AMM protocols, DODO does not require quote tokens, and IDO projects only need to deposit their own tokens to the liquidity pool, after which the PMM creates its own ask-side depth. To start an IDO, a project needs to only set the oracle price to a constant. Liquidity is improved by depositing more quote tokens.

Buy DODO
Link
SushiSwap - SUSHI

SushiSwap (SUSHI) is an example of an automated market maker (AMM). An increasingly popular tool among cryptocurrency users, AMMs are decentralized exchanges which use smart contracts to create markets for any given pair of tokens.

SushiSwap launched in September 2020 as a fork of Uniswap, the AMM which has become synonymous with the decentralized finance (DeFi) movement and associated trading boom in DeFi tokens.

The platform takes a 0.3% cut from transactions occurring in its liquidity pools, while its SUSHI token is used to reward users portions of those fees. SUSHI also entitles users to governance rights.

SushiSwap aims to diversify the AMM market and also add additional features not previously present on Uniswap, such as increased rewards for network participants via its in-house token, SUSHI.

Buy SUSHI
Link
1inch - 1INCH

The 1inch Network unites decentralized protocols whose synergy enables the most lucrative, fastest, and protected operations in the DeFi space.

The 1inch Network's first protocol is a decentralized exchange (DEX) aggregator solution that searches deals across multiple liquidity sources, offering users better rates than any individual exchange.

The 1inch Aggregation Protocol incorporates the Pathfinder algorithm for finding the best paths across over 240+ liquidity sources on Ethereum, BNB Chain, Polygon, Avalanche, Optimistic Ethereum, Arbitrum, Fantom and Gnosis Chain. In just over two years the 1inch DEX aggregator has reached 1M users and surpassed $150B in overall volume on the Ethereum network alone.

The 1inch Liquidity Protocol is a next-generation automated market maker (AMM) that protects users from front-running attacks and offers attractive opportunities to liquidity providers.

The 1inch Limit Order Protocol facilitates the most innovative and flexible limit order swap opportunities in DeFi. The protocol’s features, such as dynamic pricing, conditional orders, and extra RFQ support, power various implementations, including stop-loss and trailing stop orders, as well as auctions.

The 1inch Wallet is a multichain mobile platform that provides an easy-to-navigate interface with secure storing, transaction, and staking capabilities. This versatile wallet was built from the ground up to streamline interacting with 1inch’s features.

The 1inch Network's governance token 1INCH is used to vote on protocol parameters under the decentralized autonomous organization (DAO) model.

Buy 1INCH
Link
Synthetix - SNX

Synthetix is a decentralized exchange (DEX) and a platform for synthetic assets. The protocol is designed in a way that exposes users to the underlying assets via synths, without having to hold the underlying asset.

The platform allows users to autonomously trade and exchange synths. It also has a staking pool where holders can stake their SNX tokens and are rewarded with a share of the transaction fees on the Synthetix Exchange.

The platform tracks the underlying assets using smart contract price delivery protocols called oracles. Synthetix allows users to trade synths seamlessly, without liquidity/slippage issues. It also eliminates the need for third-party facilitators.

SNX tokens are used as collateral for the synthetic assets that are minted. This means that whenever synths are issued, SNX tokens are locked up in a smart contract.

Buy SNX
Link
Curve DAO Token - CRV

Curve is a decentralized exchange for stablecoins that uses an automated market maker (AMM) to manage liquidity.

Curve has gained considerable attention by following its remit as an AMM specifically for stablecoin trading.

The launch of the DAO and CRV token brought in further profitability, given CRV’s use for governance, as it is awarded to users based on liquidity commitment and length of ownership.

The explosion in DeFi trading has ensured Curve’s longevity, with AMMs turning over huge amounts of liquidity and associated user profits.

As such, Curve caters to anyone involved in DeFi activities such as yield farming and liquidity mining, as well as those looking to maximize returns without risk by holding notionally non-volatile stablecoins.

The platform makes money by charging a modest fee which is paid to liquidity providers.

Buy CRV
Link
THORChain - RUNE

THORChain is a decentralized liquidity protocol that allows users to easily exchange cryptocurrency assets across a range of networks without losing full custody of their assets in the process.

With THORChain, users can simply swap one asset for another in a permissionless setting, without needing to rely on order books to source liquidity. Instead, market prices are maintained through the ratio of assets in a pool

Buy RUNE
Link
Loopring - LRC

The main idea behind Loopring is to combine elements of centralized and decentralized cryptocurrency exchanges to create a protocol that will enjoy their unique advantages and eliminate inefficiencies.

Loopring protocol seeks to keep the advantages of decentralized exchanges while reducing or eliminating their inefficiencies via innovative hybrid solutions.

Through managing orders in a centralized manner but settling the trades on-blockchain, and combining up to 16 orders into circular trades instead of allowing strictly one vs. one trading pairs, Loopring expects to increase the efficiency of order execution, as well as enhance the liquidity of DEXs.

Buy LRC
Link
Kyber Network - KNC

Kyber Network is a hub of liquidity protocols that aggregates liquidity from various sources to provide secure and instant transactions on any decentralized application (DApp). The main goal of Kyber Network is to enable DeFi DApps, decentralized exchanges (DEXs) and other users easy access to liquidity pools that provide the best rates.

All transactions on Kyber are on-chain, which means they can be easily verified using any Ethereum block explorer. Projects can build on top of Kyber to utilize all the services offered by the protocol, such as the instant settlement of tokens, liquidity aggregation, and a customizable business model.

KNC holders can stake their tokens in the KyberDAO to help govern the platform and vote on important proposals --- and earn staking rewards in Ethereum (ETH) that come from trading fees.

Buy KNC
Link
Injective Protocol - INJ

Injective enables access to unlimited decentralized finance markets. Users can create any financial market on Injective’s fast, cross-chain, zero gas fee, secure, and fully decentralized exchange protocol.

The Injective Chain is custom built to support Ethereum-compatible DeFi applications that reach instant finality, sub 2 second block times, and lightning fast transaction speeds (10,000+ TPS).

The trading infrastructure of Injective is supported entirely by a central limit order book that integrates the user-friendly interface and speed of centralized exchanges with the transparency of decentralized exchanges. Injective unique decentralized ordebrook exchange protocol is able to support cross-chain trading of crypto, perpetuals, futures, synthetics, and exotic assets across distinct blockchains such as Ethereum, BSC, and Cosmos.

Buy INJ
Link
Balancer - BAL

Balancer is similar to Uniswap and Curve, in that it enables anyone to create pools of tokens. The pool adjusts itself to keep the tokens equally weighted regardless of changes in their price. However, one unique feature of Balancer is that more than one token can be added and ETH isn’t required.

Although, Balancer isn’t the first DeFi protocol to make use of AMMs, however, it has brought a new face and approach to liquidity. The unique feature of the protocol is that it allows Liquidity providers to have up to eight assets per market which are weighted by percentage and rebalanced automatically.

With Balancer, users don’t have to deposit 50% of the desired asset, but are allowed to decide how much of a supported asset they wish to deposit. Another unique feature of Balancer Lab is that users can make a high return on assets that are in low demand through arbitrage opportunities and slippage-reduction. 

Buy BAL
Link
0x - ZRX

Unlike many other Ethereum decentralized exchange protocols, 0x supports both fungible (ERC20) and non-fungible (ERC-723) tokens. This means it can be used for the permissionless trading of a wide range of assets, giving holders a way to buy, sell and exchange the vast majority of Ethereum assets through more than a dozen different apps.

The 0x protocol can be applied to a wide range of use cases, including eBay-style marketplaces for digital goods and services, OTC trading desks, exchange functionality for DeFi protocols and plain-old decentralized exchanges.

Although 0x can be used to build highly flexible exchange products, it can also be built into products where asset exchange is a secondary feature — such as for in-game purchases and portfolio management platforms.

On the 0x protocol, liquidity takers pay a fee in the form of ZRX tokens — this fee is used to incentivize market maker (relayer) liquidity. Users also need to pay a protocol fee in the form of Ether (ETH), which is used to pay for the gas used in any transactions they complete. 

Buy ZRX
Link
Serum - SRMFlamingo - FLM

Flamingo is a decentralized finance (DeFi) platform based on the Neo blockchain and the Poly Network interoperability protocol. It combines several DeFi applications into a single ecosystem: a cross-blockchain asset gateway (wrapper), an on-blockchain liquidity pool (swap), a blockchain asset vault, a perpetual contract trading platform (perp) and a decentralized governance organization (DAO).

Flamingo’s unique advantage comes from the fact that it’s aiming to combine all the key financial instruments for the Neo cryptocurrency token (token wrapping, liquidity pooling, asset vault and contract trading) and make them available via a single platform that will be governed by its own users in a decentralized way.

Buy FLM
Link
Raydium - RAY

Raydium is an automated market maker (AMM) and liquidity provider built on the Solana blockchain for the Serum decentralized exchange (DEX).

Unlike any other AMMs, Raydium provides on-chain liquidity to a central limit orderbook meaning that funds deposited into Raydium are converted into limit orders which sit on Serum’s orderbooks.

This gives Raydium LPs access to all of Serum’s order flow as well as their existing liquidity.
 

Buy RAY
Link
BakeryToken - BAKE

BakerySwap, a Binance Smart Chain-based AMM, offers liquidity pools for altcoins such as LINK, DOT and others. It works through initial liquidity pools. BakerySwap has two types of liquidity pools: with BAKE rewards and without them. This is done in order to facilitate the creation of new liquidity pools by the community.

Only designated pools will have BAKE rewards. The reward multiplier for each will vary based on the value they provide to BAKE holders.

BakerySwap charges a 0.30% fee on all swaps and trades, out of which 0.25% go to liquidity providers.

The liquidity providers are then given liquidity pool tokens that represent their share of each pool. Through these tokens, they can earn a portion of the fees that are collected in the pools when removing the liquidity. Liquidity providers can then stake Bakery LP tokens to farm BAKE token rewards.

Buy BAKE
Link
Linear - LINA

Linear is a decentralized delta-one asset protocol capable of instantly creating synthetic assets with unlimited liquidity. The project opens traditional assets like commodities, forex, market indices and other thematic sectors to cryptocurrency users by supporting the creation of “Liquids” — Linear’s synthetic asset tokens.

The protocol consists of various products like Linear.Buildr, a DApp used to manage Liquids using Linear (LINA) and other tokens as collateral. The exchange is specifically created to enable trading of a variety of Liquids with rapid confirmation times and robust security.

LINA is an ERC-20 token built on the Ethereum network whose main purpose is as collateral for Liquids (using Buildr) and for community governance of the protocol. All token holders have access to the Linear DAO, enabling them to vote on different initiatives and proposals, helping to shape the development of the Linear ecosystem.

The main goal of Linear is to provide a superior user experience with better scalability and greater speed thanks to the cross-chain capabilities of the protocol. Linear Finance intends to provide a simple solution for users that want exposure to traditional assets while still benefiting from the features enabled only by blockchain technology.

Buy LINA
Link
QuickSwap - QUICKQuickSwap is a fork of the originator of Automated Market Makers in the now rapidly expanding DeFi sector of the Cryptocurrency industry, Uniswap. 
 
Buy QUICK
Link
Osmosis - OSMO

Osmosis (OSMO) is an automated market maker protocol (AMM) for the ATOM ecosystem. Osmosis was inspired by Balancer and Uniswap and wants to provide tools that go beyond traditional token swaps and offer users DeFi functionality for a cross-chain world.

Osmosis's vision is to build a cross-chain native DEX that connects to all Cosmos ecosystem chains. Later, it plans to expand to non-IBC chains like Ethereum and chains similar to Bitcoin.

In this fashion, Osmosis will transfer its unique customizability like custom-curve AMMs, dynamic adjustments of swap fees, and multi-token liquidity pools beyond blockchains in the Cosmos ecosystem.

Buy OSMO
Link
Bitgert - BRISE

Bitgert offers an alternative to the popular DEX platform PancakeSwap. BRISE Wallet DApp is the main gateway to the ecosystem, allowing users to securely send, receive, store and exchange various crypto assets.

BRISE is Bitgert's native token, allowing investors to benefit from staking and earning rewards in BUSD.

All smart contracts on Brise Chain feature a buyback mechanism. To be more precise, Bitgert directs 5% of every transaction fee for buyback, 3% for marketing and 4% for staking rewards. According to the team, buyback is meant to support the price of BRISE token making it a deflationary asset.

Buy BRISE
Link
VVS Finance - VVS

VVS Finance is designed with the goal of bringing amazing protocols to the masses. It is the simplest DeFi platform for everyone to swap tokens, earn high yields, and, most importantly, have fun.

VVS Finance is an Automated Market Maker Decentralized Exchange, so there are no middlemen or order books involved unlike a traditional centralized exchange.

VVS Finance has fine-tuned its Token Economics to offer incentives for all parties involved to foster the platform’s long-term sustainability and thriving. VVS Token is the governance token of the VVS Finance protocol highlighting the features of Bling Swap, Crystal Farms, Glitter Mines, and the upcoming Initial Gem Offering (IGO).

Buy VVS
Link
Bancor - BNT

Bancor is the only decentralized staking protocol that allows you to earn money with single-token exposure and full protection from impermanent loss. Launched in 2017, Bancor was the first DeFi protocol.

Today, it generates millions in fees per month for depositors, offering up to 60% APR on tokens like ETH, WBTC, LINK, MATIC, AAVE & more. Bancor is owned by its community as a decentralized autonomous organization (Bancor DAO).

The protocol token used on the network is the “Bancor Network Token,” BNT. The protocol’s token allows traders to provide liquidity for the pools available on the network. Anyone can contribute liquidity to the pools. When liquidity providers contribute liquidity to a pool, they are eligible to receive fees for trades that pass through the pool. Liquidity providers will receive pool tokens that represent their share of liquidity, fees, and Liquidity Mining rewards in the pool.

Buy BNT
Link
Auto - AUTO

Autofarm is a cross-chain yield aggregator that enables users to get a high return on their assets from yield farming pools by staking in Autofarm vaults.

Autofarm aims to be a leading DEX and yield aggregator on the Binance Smart Chain (BSC) by incorporating yield optimization and AMM aggregation as a single product: this allows users to have two products within a single platform, solving the problem of registering on multiple protocols.

The AUTO token can be used for proposals voting and will receive fees earned from the protocol. AUTO initiated a community-fair-launched token distribution by ensuring that only vault users will have an opportunity to participate in the AUTO token vault mining programme.

Buy AUTO
Link
Biswap - BSW

Biswap (BSW) is a decentralized exchange (DEX) for BEP-20 tokens on Binance Smart Chain (BSC). Biswap promises the lowest transaction fees of any BSC exchange at 0.1% and vows to be committed to innovation in DeFi through its high-quality products and services. Its referral system allows users to invite others and receive referral fees from farms, launch pools, swaps, and a lottery.

Biswap also has its own NFTs called NFT Earn, consisting of an NFT Launchpad, an NFT Staking Pool, an NFT Boost, and an NFT Level Upgrade. Users can buy so-called “Robi NFTs” and stake or boost them to make a profit.

Buy BSW
Link
JOE - JOE

JOE (JOE) is the native token of Trader Joe, a decentralized exchange (DEX) on the Avalanche (AVAX) blockchain that offers DeFi services, including swapping, staking and yield farming.

Trader Joe provides all the functionality of a modern DEX and offers a convenient user interface, combined with speedy and cheap transactions. Users can provide liquidity by participating in one of its yield farms and earn JOE (JOE) as a reward token, which can later be staked and used to vote in governance proposals.

Its lending protocol Banker Joe, based on the Compound (COMP) protocol, allows users to borrow and lend funds in a non-custodial manner. Moreover, users can also open leveraged positions on their provided or borrowed funds.

To increase the utility and adoption of the JOE token, Trader Joe is working on introducing several new options, which are aimed at transforming the project into the main DeFi platform within the Avalanche ecosystem. First of all, users will be able to use JOE as collateral to borrow against. Moreover, Trader Joe also plans to facilitate limit orders, options and futures trading on its platform. 

Buy JOE
Link
Mdex - MDX

MDEX is an automated market making (AMM) decentralized exchange protocol that operates on the concept of fund pools, sharing some similarities with standard DEXs, but differentiating itself from competitors by using a dual-chain model modeled on both the Ethereum network and the Huobi Ecological Chain (HECO), which gives it access to the liquidity of the Ethereum ecosystem.

A trading platform built on top of HECO, MDEX has an estimated cost for token swaps at $0.001 for each trade, with a transaction speed of three seconds.

Buy MDX
Link
Polkastarter - POLS

Polkastarter offers a low risk alternative for traditional retail investors but limiting the allocation amount, meaning projects also gain a larger loyal following but distributing tokens across a wide audience.

Polkastarter's main offering is its fixed-swap smart contract, which allows projects to easily launch liquidity pools that execute orders at a fixed price — rather than using the AMM model made popular by Uniswap, reducing risk to the retail investor.

The platform is designed to handle fixed-swap pools. This makes it suitable for cryptocurrency projects looking to raise funds publicly and also privately. Beyond this, other key features of the platform include permissionless listings, anti-scam capabilities and KYC integration.

Buy POLS
Link
PolkaBridge - PBRPolkaBridge is a decentralized cross-chain protocol designed to act as the primary bridge between Polkadot and other blockchains. It will also introduce supporting DeFi features, to complement the bridging services. 
Buy PBR
Link
IDEX - IDEX

Idex claims to be the first hybrid liquidity DEX that combines an order book model with an automated market maker. It blends the performance and features of a traditional order book model with the security and liquidity of an AMM. Idex takes an innovative approach to decentralized exchanges by combining an off-chain trading engine with on-chain trade settlement. Users benefit from that in several ways.

Idex uses smart contracts to decentralize fund custody and trade settlement. To enable the order book model, the smart contract executes trades off-chain but trades are settled on-chain with a delay. The smart contract acts as escrow and restricts the movement of funds until the settlement is finished.

Furthermore, trades are sequenced, and a special function in the smart contract ensures funds cannot be restricted indefinitely. Moreover, the smart contract enforces ownership and authorization, meaning users maintain custody and can make markets without additional infrastructure.

Buy IDEX
Link
BurgerCities - BURGERBurgerCities aims to create a unified and standardized metaverse world of Web3 via integrating DeFi, NFT to the wider Metaverse. In this world, users could carry out daily events such as social, gaming, etc. Meanwhile, they could experience DeFi and NFT functions with their own avatars such as trading, staking, NFT exhibitions or Gamefi, etc.
 
Buy BURGER
Link
Position Exchange - POSI

Position Exchange is the new Decentralized Trading Protocol, powered by a vAMM and operating on Binance Smart Chain initially, aiming to bridge the gap between people and the cryptocurrency markets and enhance trading experiences.

The protocol offers easy and accessible Derivatives Trading in which users can trade Crypto Derivatives Products fully on-chain transparently and trustless, with high security, and privacy with a plan to expand into other assets in the future. The platform is designed to deliver all the advantages of Decentralized Finance whilst bringing the traditional Centralized Finance experience and tools onboard. To mention High leverage, low slippage, and low costs as well as limit orders all while solving the liquidity issue using the vAMM.

Moreover, Position Exchange's team designed a user-friendly and attractive interface allowing traders of all kinds to trade with ease. The platform is empowered by the POSI token, its native deflationary utility token serving as the backbone of its Ecosystem.

Buy POSI
Link
BitShares - BTS 

One of BitShares’ major distinguishing features is its integrated decentralized cryptocurrency exchange platform (DEX), which allows users to trade regular cryptocurrencies, as well as more traditional financial instruments (via BitAssets) without middlemen.

Because of its native DEX and support for synthetic assets (BitAssets), BitShares is often touted as the world’s first DeFi capable blockchain.

As we previously touched on, BitShares uses distributed autonomous companies (DACs) to produce a self-governing, self-financing system that allows BTS holders to set the business rules that govern the BitShares ecosystem through a secure proposal and voting procedure.

BitShares is also one of the few blockchain platforms to completely do away with addresses. Instead, it uses simple memos to distinguish users, making it one of the more accessible crypto platforms. It is also built around a popular referral program that is used to incentivize the growth of the network by distributing upgrade fees between referrers and the BitShares network.

It was the first blockchain to use self-governed delegated proof-of-stake (DPoS) technology and has an ~3-second processing time for transactions, making it one of the fastest blockchains currently operating.

Buy BTS
Link
Bounce Token - AUCTION

Bounce is a leading all-in-one DeFi marketplace platform with a full suite of products, including: Bounce’s esteemed Auction Protocol, Fangible NFT Marketplace, Metalents Web3 Freelancing Marketplace, and an upcoming “on-chain customizable spaces'' project!

Furthermore, Bounce is building a “Metaverse City', which will host their full suite of products and provide a fully immersive user experience within DeFi.

Buy AUCTION
Link
Bonfida - FIDA

Bonfida bridges the gap between Serum, Solana, and the user. It is the flagship Serum GUI and brings Solana Data analytics to the field. Bonfida API is used by some of the largest market makers in the space and has seen a growth of requests of 25% week over week.

Bonfida will likely include a limited governance model based on the FIDA token. Some parameters such as product fees may be changed through a governance vote of FIDA tokens.

Buy FIDA
Link
Ooki Protocol - OOKI

Ooki is a powerful and fully decentralized margin trading, borrowing, and lending platform with a ton of features.

Ooki is a protocol for margin trading, borrowing, lending and staking. Ooki Protocol allows anyone to build applications that enable lenders, borrowers, and traders to interact with the most flexible decentralized finance protocol on multiple blockchains. Ooki is a fully decentralized, community-run project, governed by the community vote for all major changes to the protocol.

Buy OOKI
Link
Wombat Exchange - WOM

Wombat Exchange is a multi-chain stableswap built natively on the BNB Chain. Wombat adopts the concepts of asset-liability management and coverage ratio, enabling various stablecoins to be swapped at minimal slippage and the ability to single-stake stablecoins for sustainable yield.

Wombat’s algorithm allows the possibility of achieving a 100% capital utilization ratio with non-existent impermanent loss, where users can maximize capital utilization and enjoy better yields. Its single-token LP tokens will also serve as a foundation for everyone to build upon and activate the DeFi ecosystem.

Buy WOM
Link
Airswap - ASTAirSwap describes itself as a decentralized, peer-to-peer token trading network powered by Ethereum. AirSwap aims to make the buying and selling of tokens secure, simple, and without fees. Its mission is to empower people with global, frictionless trade. AirSwap implements the Swap protocol and currently has three products: Instant, Spaces, and DexIndex.
Buy AST
Link

Data sources: Coinmarketcap

How and Where to Buy token/coin ?

You will have to first buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

We will use Binance Exchange here as it is one of the largest crypto exchanges that accept fiat deposits.

Once you finished the KYC process. You will be asked to add a payment method. Here you can either choose to provide a credit/debit card or use a bank transfer, and buy one of the major cryptocurrencies, usually either Bitcoin (BTC), Ethereum (ETH), Tether (USDT), Binance (BNB)…

☞ SIGN UP ON BINANCE

Once finished you will then need to make a BTC/ETH/USDT/BNB deposit to the exchange from Binance depending on the available market pairs. After the deposit is confirmed you may then purchase Coin/Token from the Binance exchange.

Read more: Top Coins of Centralized Exchange (CEX) by Volume

Thank you for reading !

#blockchain #bitcoin #cryptocurrency #coin #token #dex 

Top 30 tokens of Decentralized Exchange (DEX)
Ben Taylor

Ben Taylor

1662795600

Decentralized Lending projects on Ethereum Network

In this article, you will see top 20 Decentralized Lending projects on Ethereum Network

1. Aave

NameDescribeTokenExchangeWebsite
Aave

Aave is an Open Source and Non-Custodial protocol to earn interest on deposits & borrow assets.

AAVE provides holders with discounted fees on the platform, and it also serves as a governance token — giving owners a say in the future development of the protocol.

AAVEBinancehttps://aave.com/

2. Compound

NameDescribeTokenExchangeWebsite
Compound

Compound is an open-source, autonomous protocol built for developers, enable algorithmic, efficient money markets on the Ethereum.

Compound is a DeFi lending protocol that allows users to earn interest on their cryptocurrencies by depositing them into one of several pools supported by the platform.

When a user deposits tokens to a Compound pool, they receive cTokens in return. These cTokens represent the individual’s stake in the pool and can be used to redeem the underlying cryptocurrency initially deposited into the pool at any time. For example, by depositing ETH into a pool, you will receive cETH in return. Over time, the exchange rate of these cTokens to the underlying asset increases, which means you can redeem them for more of the underlying asset than you initially put in — this is how the interest is distributed.

On the flip side, borrowers can take a secured loan from any Compound pool by depositing collateral. The maximum loan-to-value (LTV) ratio varies based on the collateral asset, but currently ranges from 50 to 75%. The interest rate paid varies by borrowed asset and borrowers can face automatic liquidation if their collateral falls below a specific maintenance threshold.

COMPBinancehttps://compound.finance/

3. Kava

Kava

Kava is a Layer-1 blockchain that combines the speed and interoperability of Cosmos with the developer power of Ethereum.

The Kava Network uses a developer-optimized co-chain architecture. The Ethereum Co-Chain enables support for EVM smart contracts while the Cosmos Co-Chain enables the lightning-fast Tendermint consensus engine and the Inter Blockchain Communication Protocol (IBC).

The two co-chains are connected by a translator module that enables them to interoperate seamlessly, bringing the two most used blockchain development environments together in a single, scalable network.

The Kava Network features a native governance and utility token, KAVA, that can be staked by validators or delegated to validator nodes. Stakers and delegators earn 37.5% of all KAVA emissions as a reward for securing the network. Kava stakers also have voting rights in network governance proposals.
 

KAVABinancehttps://www.kava.io/

4. Cream Finance

NameDescribeTokenExchangeWebsite
Cream Finance

CREAM Finance is a decentralized DeFi lending protocol for individuals, institutions and protocols to access financial services. Part of the yearn.finance ecosystem,

CREAM Finance is a permissionless, open source and blockchain agnostic protocol serving users on Ethereum, Binance Smart Chain Polygon and Fantom.

Users who are passively holding Ether or wBTC can deposit their assets on CREAM. to earn yield, similar to a traditional savings account. 

CREAMBinancehttps://cream.finance/

5. Maple

NameDescribeTokenExchangeWebsite
Maple

Maple is a decentralized corporate credit market. Maple offers borrowers transparent and efficient financing completed entirely on-chain.

For liquidity providers, Maple offers a sustainable yield source through lending to diversified pools of crypto’s premium institutions. The Pool Delegates that manage these pools perform diligence and set terms with Borrowers.

MPLGate.iohttps://maple.finance/ 

6. TrueFi

NameDescribeTokenExchangeWebsite
TrueFi

TrueFi is a protocol for creating interest-bearing pools with a high APR for liquidity providers. TrueFi includes utility and rewards mechanisms using TrustTokens (TRU) and rewards participants for maintaining stable, high APRs.

TRU is the native token of the TrueFi protocol and is used for: TrustToken holders ultimately have a say over who is a credible borrower in the prediction market.

TRUBinancehttps://truefi.io/

7. Wing Finance

NameDescribeTokenExchangeWebsite
Wing

Wing is a credit-based, decentralized platform designed for crypto-asset lending and cross-chain communication between decentralized finance (DeFi) projects. The project aims to make crypto lending services more inclusive through a credit evaluation module that removes the need for large collaterals. Wing is a decentralized autonomous organization (DAO) that allows users to take part in decision-making, product design and operations.

Wing uses decentralized governance coupled with a risk control mechanism to improve the relationships between creditors, borrowers and guarantors. This has led to an improvement in the number of and accessibility to DeFi projects utilizing the platform. One of the goals of Wing DAO is to solve the issue of over-collateralization that plagues the DeFi industry.

WING

 

Binancehttps://wing.finance/ 

8. Alchemix

NameDescribeTokenExchangeWebsite
AlchemixAlchemix is a future-yield-backed synthetic asset platform with flexible instant loans that repay themselves over time and community DAO. The platform advances your yield farming via a synthetic token representing a fungible claim on any underlying collateral in the Alchemix protocolALCXBinancehttps://alchemix.fi/

9. Liquity

NameDescribeTokenExchangeWebsite
Liquity

Liquity is a decentralized borrowing protocol that allows you to draw interest-free loans against Ether used as collateral.

Ether holders can draw loans in the form of LQTY with algorithmically adjusted redemption and loan issuance fees.

LQTYHuobihttps://www.liquity.org/

10. Goldfinch

NameDescribeTokenExchangeWebsite
Goldfinch

Goldfinch is a global credit protocol that offers sustainable, high-quality stablecoin yields that are generated by real-world economic activity and sheltered from DeFi's volatility.

GFI is an Ethereum token that governs Goldfinch, which ultimately aims to make DeFi lending more accessible by enabling loans that can use both on and off chain collateral.

GFIGate.iohttps://goldfinch.finance/

10. Unit protocol

NameDescribeTokenExchangeWebsite
Unit protocolUnit Protocol is a decentralized protocol that allows you to mint stablecoin $USDP using a variety of tokens as collateralDUCKGate.iohttps://unit.xyz/

12. Yield Protocol

NameDescribeTokenExchangeWebsite
Yield Protocol

Yield Protocol is an open source platform allowing anybody to create and execute yield farming & trading strategies on the Ethereum Defi ecosystem. Yield Protocol is designed to minimize smart contract risk by simplifying the abilities of each contract.

Yields Protocol's design allows anybody to design financial strategies that others can leverage without giving them access to their funds. Yield Protocols modular design allows for multitude of purposes.

Design and deploy yield farming strategies, algo trading, lending and everything in between. These aspects with ever growing arsenals of supporter protocols and pools, makes YieldProtocol the perfect solution.

YIELDGate.iohttps://yieldprotocol.org/

13. 88mph

NameDescribeTokenExchangeWebsite
88mph

88mph lets you lend your crypto assets at a fixed interest rate. 

Earn fixed-rate interest on your crypto. Earn MPH rewards. Get started by adding your crypto assets to the pools below.

MPHMEXChttps://88mph.app/

14. Notional

NameDescribeTokenExchangeWebsite
Notional

Notional is a fixed rate lending and borrowing platform on Ethereum.

Notional is the first decentralized, Ethereum-based protocol for borrowing and lending at fixed rates and fixed terms. With variable rate lending, DeFi can only serve a small segment of the crypto lending market because variable interest rates don’t provide the certainty that lenders and borrowers require.

Notional fixes this by creating a true market for lenders and borrowers that democratizes and empowers individual investors, business owners and institutional investors.

NOTECoinExhttps://notional.finance/

15. Oasis Borrow

NameDescribeWebsite
Oasis BorrowOasis Borrow allows you to lock your tokens as collateral to generate DAI, a decentralized stablecoin soft-pegged to 1 USD.https://oasis.app/#multiply

16. Fulcrum

NameDescribeWebsite
FulcrumFulcrum is the platform for tokenized margin trading and lending, enables users to lend assets for interest or enter into short/leveraged positions.https://fulcrum.trade/

17. Torque

NameDescribeWebsite
TorqueTorque is a powerful DeFi platform for borrowing assets with indefinite-term loans and fixed interest rates.https://torque.loans/

Top exchanges for token-coin trading on ETH ecosystem: ☞ BinancePoloniexBitfinexHuobiMXCProBITGate.io


Read more: DeFi Infrastructure & Dev Tooling projects on Ethereum Network

I hope this article will help you. Thank you for reading !

#blockchain #bitcoin #cryptocurrency #eth #ethereum #dex 

Decentralized Lending projects on Ethereum Network
Ben Taylor

Ben Taylor

1662698640

DEX projects on Ethereum Network

In this article, you will see top 20 (Decentralized exchanges) DEX projects on Ethereum Network
 

1. Curve

NameDescribeTokenExchangeWebsite
Curve

Curve is a decentralized exchange for stablecoins that uses an automated market maker (AMM) to manage liquidity on Ethereum

Curve launched a decentralized autonomous organization (DAO), with CRV as its in-house token. The DAO uses Ethereum-based creation tool Aragon to connect multiple smart contracts used for users’ deposited liquidity.

CRVBinancehttps://curve.fi/

2. Uniswap

NameDescribeTokenExchangeWebsite
Uniswap

Uniswap is an automated fully decentralized token exchange on Ethereum

Uniswap aims to keep token trading automated and completely open to anyone who holds tokens, while improving the efficiency of trading versus that on traditional exchanges.

Uniswap creates more efficiency by solving liquidity issues with automated solutions, avoiding the problems which plagued the first decentralized exchanges.

UNIBinancehttps://uniswap.org/

3. dYdX

NameDescribeTokenExchangeWebsite
dYdX

DYDX (dYdX) is the governance token for the layer 2 protocol of the eponymous non-custodial decentralized cryptocurrency exchange. It serves to facilitate the operation of layer 2 and allows traders, liquidity providers and partners to contribute to the definition of the protocol's future as a community.

Token holders are granted the right to propose changes on the dYdX’s layer 2, and are presented with an opportunity to profit through token staking and trading fee discounts.

Built on Starkwire’s StarkEx scalability engine, layer 2 is used for trading of cross-margined perpetuals on the platform. The scaling solution allows dYdX to increase transaction speed, eliminate gas costs, reduce trading fees and lower​​ minimum trade sizes on the protocol.

An open-source platform with smart contract functionality, dYdX is designed for users to lend, borrow and trade crypto assets. Although dYdX supports spot trading, the main focus of the platform is on derivatives and margin trading.

DYDXBinancehttps://dydx.community/dashboard

 

4. SushiSwap

NameDescribeTokenExchangeWebsite
SushiSwap

The SushiSwap exchange allows users to swap any ERC20 token into any other ERC20 token through automated liquidity pools.

SushiSwap (SUSHI) is an example of an automated market maker (AMM). An increasingly popular tool among cryptocurrency users, AMMs are decentralized exchanges which use smart contracts to create markets for any given pair of tokens.

SUSHIBinancehttps://sushi.com/

5. 1inch.exchange

NameDescribeTokenExchangeWebsite
1inch.exchange

The 1inch Network unites decentralized protocols whose synergy enables the most lucrative, fastest, and protected operations in the DeFi space.

The 1inch Network's first protocol is a decentralized exchange (DEX) aggregator solution that searches deals across multiple liquidity sources, offering users better rates than any individual exchange.

The 1inch Limit Order Protocol facilitates the most innovative and flexible limit order swap opportunities in DeFi. The protocol’s features, such as dynamic pricing, conditional orders, and extra RFQ support, power various implementations, including stop-loss and trailing stop orders, as well as auctions.

1INCHBinancehttps://1inch.io/

6. Balancer

NameDescribeTokenExchangeWebsite
BalancerBalancer is an automated market maker (AMM) that was developed on the Ethereum blockchain. Balancer protocol functions as a self-balancing weighted portfolio, price sensor and liquidity provider. It allows users to earn profits through its recently introduced token ($BAL) by contributing to customizable liquidity pools.BALBinancehttps://balancer.fi/

7. Dodo

NameDescribeTokenExchangeWebsite
Dodo

DODO is a DeFi protocoldecentralized finance (DeFi) protocol and on-chain liquidity provider whose unique proactive market maker (PMM) algorithm aims to offer better liquidity and price stability than automated market makers (AMM).

The PMM pricing mechanism, which mimics human trading, utilizes oracles to gather highly accurate market prices for assets. It then provides enough liquidity close to these prices in order to stabilize the portfolios of liquidity providers (LP), lower price slippage and negate impermanent loss by allowing arbitrage trading as reward.

DODO’s smart contract operates as an ERC20 token on the Ethereum network.

 Binancehttps://dodoex.io/

 

8. Bancor

NameDescribeTokenExchangeWebsite
BancorBancor is an on-chain liquidity protocol that enables automated, decentralized token exchange on Ethereum and across blockchains.BNTBinancehttps://home.bancor.network/

9. IDEX

NameDescribeTokenExchangeWebsite
IDEXIDEX is a non-custodial exchange that integrates with any custody solution and allows users to trade with one another without giving up control to a third-party custodianIDEXBinancehttps://idex.io/

10. Multichain

NameDescribeTokenExchangeWebsite
Multichain

Multichain (previously Anyswap) is a cross-chain router protocol (CRP), Multichain is an infrastructure for on-chain asset interoperability, envisioned to be the ultimate router for Web3.

The solutions developed by Multichain allow almost all blockchains to inter-operate. There is no restriction to Ethereum like chains (e.g. Binance Smart Chain), or different Layer 2 chains requiring finality to Ethereum (e.g. Polygon), or a network of Parachains (e.g. Moonbeam in the PolkaDot system), or Bitcoin types of chain (e.g. Litecoin), or COSMOS chains (e.g. Terra). 

MULTIBinancehttps://multichain.org/

More than …

RatingNameDescribeTokenExchangeWebsite
11AirSwapAirSwap describes itself as a decentralized, peer-to-peer token trading network powered by Ethereum. AirSwap aims to make the buying and selling of tokens secure, simple, and without fees. Its mission is to empower people with global, frictionless trade. AirSwap implements the Swap protocol and currently has three products: Instant, Spaces, and DexIndex.ASTBinancehttps://www.airswap.io/#/
12RhinoFiRhinoFi(previously DeversiFi) is a hybrid Ethereum exchange platform providing access to spot trading, margin trading, P2P funding & decentralized trading. Buy, trade and invest across all of your favourite blockchains from a single layer 2 wallet. Access hundreds of tokens effortlessly, and save gas on every single transaction.DVFBitfinexhttps://rhino.fi/
13KyberSwapKyberSwap allows anyone to convert tokens directly from their wallet in an instant, convenient and secure way.KNCBinancehttps://kyberswap.com/swap
14ParaSwapParaSwap aggregates decentralized exchanges and other DeFi services in one comprehensive interface to streamline and facilitate users' interactions with decentralized finance on Ethereum and EVM-compatible chainsPSPBybithttps://www.paraswap.io/
15CowSwapCowSwap is a trading interface built on top of Gnosis Protocol v2. It allows you to buy and sell tokens using gas-less orders that are settled peer-to-peer among its users or into any on-chain liquidity source while providing MEV protection.  https://cowswap.exchange
16DDEXDDEX is the decentralized exchange built on Hydro Protocol technology, offering real-time order matching with secure on-chain settlement.  https://ddex.io/
17DexGuruDexGuru is a trading platform for modern traders where on-chain analytics combined with trading capabilities.  https://dex.guru/
18MatchaMatcha is a crypto trading platform with smart order routing powered by 0x. Matcha aggregates liquidity from multiple sources, including 0x, Kyber, Uniswap, Oasis, Curve, and others  https://matcha.xyz/
19MesaMesa is an open source interface for Gnosis Protocol, a fully permissionless DEX that enables ring trades to maximize liquidity.  https://mesa.eth.link/
20OasisOasis is a decentralized, non-custodial exchange built on the OasisDEX Protocol enabling the trade of the tokens used in Multi-Collateral Dai (MCD).  https://oasis.app/#multiply

Read more: DeFi Infrastructure & Dev Tooling projects on Ethereum Network

I hope this article will help you. Thank you for reading !

#blockchain #bitcoin #cryptocurrency #eth #ethereum #dex 

DEX projects on Ethereum Network
Thierry  Perret

Thierry Perret

1657817305

Révéler Les Secrets De L'agrégateur De Recherche DODO

"Comment trouver l'enchère optimale pour les utilisateurs" est un élément essentiel de la finance décentralisée (DeFi). À l'heure actuelle, il existe de nombreux protocoles de DeFi sur le marché. Différents protocoles ont des algorithmes uniques. En raison des sources de liquidité relativement indépendantes de DeFi, différents pools auront différentes cotations pour la même devise. Les échanges décentralisés (DEX) ont conçu leur algorithme pour attirer les fournisseurs de liquidité (LP) afin d'obtenir une meilleure offre. D'autre part, les agrégateurs tels que 1inch et 0x ont choisi une autre voie : en recherchant les chemins formés par différents pools, nous pouvons trouver l'enchère optimale pour les utilisateurs sous contrôle du gaz.

Avec le développement du marché, les agrégateurs tels que 1inch et 0x auront également leurs sources de cotation uniques. DEX tels que Balancer et Uniswap V3 diviseront également une transaction de l'utilisateur en plusieurs chemins. La différence est que l'algorithme d'agrégation de DEX repose sur son pool de cotations, tandis que les agrégateurs utilisent pleinement la composabilité de DeFi. Un agrégateur peut fournir aux utilisateurs la meilleure cotation car il peut accéder à son pool et aux pools d'autres DEX, augmentant ainsi la source de liquidité de toute la chaîne.

DODO s'engage à fournir aux utilisateurs la meilleure expérience de trading. En plus de développer son pool PMM , DODO a développé indépendamment son algorithme d'agrégation. L'algorithme d'agrégation de DODO n'est pas l'algorithme de routage fractionné de DEX tel qu'Uniswap, mais l'algorithme d'agrégation similaire à celui de 1 pouce et 0x. DODO connectera non seulement ses pools mais également d'autres pools de DEX pour mieux utiliser les liquidités.

Cet article se compose de deux parties. La première partie introduira la modélisation des problèmes d'agrégation. La deuxième partie présentera l'algorithme d'agrégation de DODO et analysera les difficultés de conception de l'ingénierie d'agrégation.

1. Introduction à la modélisation et analyse de la solution

Une modélisation appropriée est un excellent début pour résoudre un problème. Commençons par le problème le plus simple : le routage linéaire.

1.1 Routage linéaire

Le routage linéaire est le processus de recherche d'un chemin de trading optimal offert pour le jeton cible où une paire de trading ne passe que par un pool. Par exemple, si un utilisateur a besoin d'échanger de l'ETH vers l'USDC, le chemin optimal trouvé par un routage linéaire est d'échanger de l'ETH vers l'USDT, puis il va à l'USDC, et non à [ACB] ou [ADB] (c'est-à-dire que l'actif A est pas divisé en deux parties et sélectionne des chemins différents). Le chemin choisi ne traverse que deux bassins. Ces deux pools peuvent provenir de protocoles différents. Par exemple, le protocole pour échanger ETH vers USDT provient du pool Uniswap V3, et le protocole USDT-USDC provient du pool Curve V1. DEX comme Uniswap V2 et PancakeSwap utilisent également ce modèle de routage. Cependant, leur source de liquidité est leur échange. Les routes Uniswap V2 ne passent que par les pools Uniswap V2, tandis que les routes PancakeSwap ne passent que par les pools PancakeSwap.

[Figure 2 : Le contenu dans la case rouge marquée dans la figure est le chemin de routage]

Supposons que les utilisateurs du jeton doivent vendre : fromToken , et le jeton qu'ils veulent acheter : toToken . Pour tout pool, baseToken est défini comme le jeton de vente et quoteToken comme le jeton d'achat. Le baseToken du premier pool doit être fromToken et le quoteToken du dernier pool doit être toToken , comme illustré dans la figure ci-dessous.

Il peut être directement résumé comme un problème de valeur maximale : il y a n actifs différents, il y a k autres pools différents, et le nombre de jetons échangés dans chaque pool peut être exprimé par un ensemble de fonctions

Étant donné que les pools de jetons doubles peuvent représenter tous les pools de 3 jetons ou multi-jetons, la fonction peut être encore abrégée comme suit :

où représente αi le numéro de l'actif iᵗʰ, αirereprésente le numéro de l'actif jᵗʰ et k représente le numéro du pool. Supposons que le nombre de fromToken de l'utilisateur soit αᶠ et enfin, le nombre de toToken αᵗ peut être obtenu. L'ensemble de jetons échangés au cours du processus est le suivant :

Il y a m-1 pools dans ce processus, et nous allons représenter cela comme thêta :

Alors,

Si nous pouvons trouver la solution aux problèmes ci-dessus, nous pouvons obtenir le chemin optimal.

Cette modélisation est encore trop abstraite, et on peut utiliser la théorie des graphes pour construire un autre modèle. Le baseToken de i à j représente le bord ρⁱʲᵏ et le bord de j à i est ρʲⁱᵏ Le poids du bord est défini sur α₀ divisé par le nombre de quoteTokens échangés par le pool αⱼ. α₀/αⱼ peut construire le graphe orienté suivant avec plusieurs arêtes et anneaux, comme indiqué ci-dessous :

Ensuite, le problème peut être résumé comme suit : à partir de l'origine F , c'est-à-dire, trouver un chemin depuis fromToken qui minimise le poids vers toToken .

À première vue, cela semble être un problème simple concernant le chemin le plus court, et il existe de nombreux algorithmes matures à titre de référence. Mais contrairement aux problèmes de chemin le plus court ordinaires, dans le processus de recherche du bord suivant, sous le poids d'un bord est associé au chemin devant la séquence du nœud. Par conséquent, dans le chemin optimal des nœuds rejoignant la file d'attente, chaque nœud a un état qui doit être maintenu en temps réel. Il fait correspondre les nœuds de séquence suivants de la longueur de chemin enregistrée à l'état des nœuds de séquence précédents. Et dans ce problème, le « poids minimum » final est calculé non pas en additionnant les poids de tous les bords sur le chemin, mais en calculant uniquement le poids d'entrée du nœud toToken . Cette caractéristique rend l'algorithme traditionnel du plus court chemin non entièrement applicable.

Lorsqu'il y a peu de nœuds, il est plus intuitif de rechercher directement avec l'algorithme Depth First Search (DFS), c'est-à-dire de parcourir chaque chemin et d'obtenir le prix final du toToken , afin de sélectionner le chemin optimal à échanger par les utilisateurs. L'itinéraire Uniswap V2 utilise cette méthode pour trouver le chemin optimal. La première version de la route Uniswap V3 utilise également cette méthode. Cependant, contrairement à V2, le prix de V2 peut être calculé directement via la chaîne. Et puis le multi-appel appelle le contrat du devis et obtient directement le résultat.

[Figure 5 : Code source de l'algorithme de routage Uniswap v2]

Le modèle mentionné ci-dessus n'est pas adapté à l'algorithme BFS. Supposons que l'algorithme BFS est exécuté en fonction de l'arête (c'est-à-dire que l'algorithme BFS est exécuté en fonction du pool). Dans ce cas, le pool non sélectionné dans cet état doit être maintenu de manière synchrone. L'étape suivante ne peut être étendue que dans le pool non sélectionné, ce qui n'a aucune différence avec la complexité de l'algorithme DFS mais augmente considérablement le coût de l'espace pour l'enregistrement. Cependant, un problème fatal surviendra si les nœuds sont étendus selon l'algorithme BFS : le nœud peut être traversé à plusieurs reprises. Par conséquent, il ne satisfait pas la condition de l'algorithme BFS.

De même, en raison de l'existence d'effet secondaire, la méthode d'élagage dans l'algorithme DFS n'a pas été envisagée pour le moment. La meilleure méthode suivante consiste à pré-trier la taille du pool et à supprimer certains pools avant d'entrer dans l'algorithme DFS, mais il existe certains risques liés à la suppression de pools, qui peuvent affecter l'optimalité.

L'application de l'algorithme DFS peut assurer le chemin optimal de fromToken à toToken du graphe courant. La complexité temporelle est liée au nombre de couches. Heureusement, pour assurer la rationalité du gaz, le nombre de couches récursives ne dépassera pas 4, donc la complexité temporelle est O(l ^3), et l est le nombre total d'arêtes.

1.2 Routage fractionné

Lors de l'examen de problèmes complexes, le choix du chemin de cotation optimal est également appelé routage fractionné. Dans le processus de recherche d'un chemin de négociation, une paire de négociation peut passer par différents pools, et les fonds de l'utilisateur sont alloués à différents pools pour être échangés dans une proportion optimale pour rendre l'offre de jetons cible optimale. De même, prenez ETH-USDC comme exemple. Le chemin de transaction passe toujours par ETH vers USDT puis vers USDC. ETH et USDT peuvent passer par deux pools. 30% des ETH sont convertis en USDT via Uniswap V3 et 70% en USDT via DODO V2. Lorsque l'USDT est échangé contre l'USDC lors de la prochaine transaction, l'USDT initial est la somme des deux parties ci-dessus de l'USDT, la répartition optimale de l'USDT vers l'USDC est trouvée.

Dans le chemin d'enchères optimal, le fromAmount complet peut être divisé en différents chemins ou pools à échanger en fonction de la proportion du montant du chemin. Un réseau de flux peut être défini dans le schéma d'origine, en fonction de la plus petite unité d'échelle utilisée pour le partitionnement. Une super-source peut être établie si le fromAmount peut être divisé en n parties. La limite supérieure du flux de la super-source au nœud fromToken est n , et la limite supérieure du flux des arêtes restantes est l'infini positif. α₀ divisé par le nombre de quoteTokens échangés par le pool αⱼ, α₀/αⱼ comme le coût du bord cⁱʲᵏ, en utilisant la méthode de simplification décrite ci-dessus, pool kne contient que des jetons i et j , qui peuvent être simplifiés en cʲᵏ. Ensuite, le problème est de trouver le débit maximum avec le coût minimum dans le graphique.

En particulier, les frais sont dynamiques. Plus précisément, pour assurer le respect de la limite de degré des nœuds, nous pouvons supposer que le flux n'augmente ou ne diminue pas (de x % du montant initial) lorsqu'il traverse le nœud, ce qui n'affecte que le coût. Étant donné que le coût de l'arête est lié à la quantité de baseToken et que la quantité est liée au chemin, le coût de chaque arête w peut être défini comme :

Où cⁱʲᵏ est le coût du chemin, baseToken est i , quoteToken est j et le numéro de pool est k . C'est une fonction de wⁱᵏ, qui est la fonction de citation du pool. 𝔲 est le chemin de 0 à I , wⁱᵏ est défini comme le trafic sur le nœud i qui passe par le chemin k . Il y a:

wⁱ est le trafic du nœud I . Étant donné que le seul facteur qui affecte la quantité de quoteToken est la quantité de baseToken , cⁱʲᵏ peut être encore simplifié comme suit :

Où cᵢₗ est le coût d'entrée du nœud i , ι∈ ∑ [1,…,q] est le nombre d'arêtes d'entrée. Pour résoudre le problème du rapport de partition, une idée courante est de diviser le flux possible en n parties puis de diviser l'arête Pⁱʲᵏ en n parties. Le flux a été divisé en n parties égales, notées wⁱᵏ=1,2…n. où

son arête correspondante P'ⁱʲᵏ, 0<o<n+1, alors cⁱʲᵏ est définie par :

Les sous-chemins séparés par le même groupe d'arêtes ne doivent pas être sélectionnés à plusieurs reprises.

De même, le coût minimum résolu au final n'est défini que par le coût d'entrée de toToken .

Étant donné que le coût dépend du chemin passé, l'algorithme de chemin généralement augmenté pour résoudre le flux maximum de coût minimum n'est pas applicable. Un autre problème est que cette méthode limite le même pool uniquement pour prendre l'un des sous-chemins divisés, de sorte que la somme entre les sous-chemins ne peut pas être calculée et que le chemin augmenté ne peut pas simplement inverser le flux.

Le problème appelle une autre solution. Comme ce problème est un problème d'optimisation lorsque la force et le temps de calcul sont suffisants, les paramètres de simulation aléatoires peuvent être considérés. Les paramètres d'estimation MCMC peuvent être utilisés par calcul direct. Les gens de l'industrie actuelle se soucient plus du temps et de la fiabilité que de la solution optimale au problème. Dans les sections suivantes, j'essaie d'analyser les solutions d'autres agrégateurs de l'industrie pour illustrer deux solutions simplifiées au problème.

1.3 Analyse d'agrégation

0x

Grâce à l'analyse du code source 0x et aux résultats renvoyés par l'API, 0x simplifie les questions en deux modèles indépendants, qui donnent respectivement la citation optimale, puis sélectionne la solution optimale à renvoyer aux utilisateurs.

Simplifiez la question 1 : le routage linéaire, qui résulte des sauts multiples renvoyés par l'API.

Simplifier la question 2 : Routage fractionné à saut unique. Seuls les pools fromToken toToken sont conservés.

Pour le routage fractionné à saut unique, chaque chemin peut être divisé en N sous-chemins en fonction du coefficient de dispersion N , et le coût de chaque sous-chemin est quoteToken lorsque le trafic est i , qui est également le prix unitaire de toToken , puis résolu.

En particulier, 0x appelle le contrat de route lors de la construction de chemins liés à SushiSwap ou Uniswap, il peut donc y avoir plusieurs sauts intermédiaires dans le chemin, comptant essentiellement les sauts comme un pool entier.

1 pouce/ParaSwap

Pour 1 pouce, le chemin de gaz optimal dans le 1 pouce v2 est un itinéraire linéaire.

Le routage fractionné du 1 pouce v2 met à jour l'algorithme Pathfinder, qui a la structure suivante :

De même, le Paraswap reprend le même modèle que le 1 pouce :

Le frontal n'affiche pas le chemin divisé dans le saut unique, mais l'API peut observer le résultat divisé

[Le champ bestRoute dans l'API enregistre les détails du chemin de routage. Comme le montre la figure, le ParaSwap a choisi ParaSwapPool7 et l'Uniswap V3 pour échanger des paires dans la paire d'échange USDT (0xdAC17F958D2ee523a2206206994597C13D831ec7) à ETH, représentant respectivement 38,46 % et 61,54 %]

Ce modèle peut être directement exprimé par :

Où Af représente le montant total du jeton de base et est divisé en n chemins pour la transaction. Soit At le nombre final de toToken obtenu, qui est aussi la somme de n chemins :

Chaque chemin peut rencontrer un nombre différent de pools/échanges et échanger différents jetons au milieu. En utilisant le modèle ci-dessus, ati peut être directement exprimé comme suit :

Cette solution peut être interprétée comme la recherche de trois chemins de coût minimum non répétitifs dans le problème, ce qui est plus proche de la solution optimale que l'algorithme 0x. Mais c'est aussi une version simplifiée qui considère le cas caché où deux chemins différents convergent vers le même nœud.

Bien que le Pathfinder 1 pouce n'exclue pas les nœuds en double (c'est-à-dire des chemins différents à travers la même devise) dans sa conception des chemins de sous-jetons, il évite le problème d'utiliser deux fois la même source de citation en attribuant différents sous-chemins à différentes sources de citation, dans certains cas, sa solution ne sera toujours pas optimale. La taille spécifique de l'impact peut être testée pour la sensibilité.

Cependant, comme le montre l'analyse, ce modèle est le plus proche du modèle original. Si la solution optimale au problème peut être donnée, la solution est plus proche du problème d'origine et donne la solution optimale (la perturbation du modèle peut être mesurée). Le seul effet est d'observer les paramètres de l'API et les résultats de 1 pouce. On peut en déduire que 1 pouce a discrétisé le nombre de copies spécifié, ce qui peut entraîner des erreurs de discrétisation. Lorsque vous regardez le rapport de division de ParaSwap, il semble être plus fin que 1 pouce. Dans certains cas, ParaSwap peut obtenir de meilleurs résultats que 1 pouce, ce qui peut y contribuer.

DODO

L'algorithme de routage auto-construit du DODO simplifie également le problème en se référant aux conceptions 1 pouce et 0x. Compte tenu de la consommation de gaz et du taux de réussite des transactions, nous avons simplifié la version v1 du routage dans le modèle suivant :

Le chemin du jeton est unique, mais pas le chemin du pool.

Dans le routage de la version V2, DODO fera référence à la conception du modèle de 1 pouce et au ParaSwap pour optimiser le routage fractionné du chemin multi-token et des sous-chemins multi-pool.

Cet article a partagé plusieurs approches de modélisation possibles pour les problèmes d'agrégation. Dans la partie suivante, nous présenterons une idée de conception technique possible basée sur l'algorithme de routage auto-construit de DODO.

Avis de non-responsabilité

Les informations contenues dans ce rapport de recherche sont dérivées d'informations rendues publiques et les opinions exprimées ici sont uniquement à des fins de recherche et ne représentent aucun conseil en investissement. Les opinions et prévisions exprimées dans ce rapport sont l'analyse et le jugement de la date d'émission et n'ont pas de validité permanente.

Link: https://blog.dodoex.io/dodo-research-reveal-the-secrets-of-the-aggregator-problem-analysis-and-model-building-ba0ead85948c

#blockchain #defi #dex #dodo

Révéler Les Secrets De L'agrégateur De Recherche DODO
Hoang  Kim

Hoang Kim

1657806420

Tiết Lộ Bí Mật Của Trang Tổng Hợp Nghiên Cứu DODO

“Cách tìm giá thầu tối ưu cho người dùng” là một phần thiết yếu của Tài chính phi tập trung (DeFi). Hiện tại, có rất nhiều giao thức DeFi trên thị trường. Các giao thức khác nhau có các thuật toán duy nhất. Do các nguồn thanh khoản tương đối độc lập của DeFi, các nhóm khác nhau sẽ có các báo giá khác nhau cho cùng một loại tiền tệ. Các sàn giao dịch phi tập trung (DEX) đã thiết kế thuật toán của mình để thu hút Nhà cung cấp thanh khoản (LP) để nhận được ưu đãi tốt hơn. Mặt khác, các công ty tổng hợp như 1inch và 0x đã chọn một cách khác: Bằng cách tìm kiếm các đường dẫn được hình thành bởi các nhóm khác nhau, chúng tôi có thể tìm thấy giá thầu tối ưu cho người dùng dưới sự kiểm soát của khí.

Với sự phát triển của thị trường, các trang web tổng hợp như 1inch và 0x cũng sẽ có những nguồn báo giá riêng. DEX như Balancer và Uniswap V3 cũng sẽ chia giao dịch của người dùng thành nhiều đường dẫn. Sự khác biệt là thuật toán tổng hợp của DEX dựa trên nhóm báo giá của nó, trong khi các trình tổng hợp sử dụng đầy đủ khả năng tổng hợp của DeFi. Một công ty tổng hợp có thể cung cấp cho người dùng báo giá tốt nhất vì nó có thể truy cập nhóm của nó và các nhóm của DEX khác, làm tăng nguồn thanh khoản của toàn bộ chuỗi.

DODO cam kết mang đến cho người dùng trải nghiệm giao dịch tốt nhất. Ngoài việc phát triển nhóm PMM của mình , DODO đã độc lập phát triển thuật toán tổng hợp của mình. Thuật toán tổng hợp của DODO không phải là thuật toán định tuyến phân tách của DEX như Uniswap, mà là thuật toán tổng hợp tương tự như của 1inch và 0x. DODO sẽ bổ sung không chỉ các nhóm của nó mà còn các nhóm DEX khác để sử dụng tính thanh khoản tốt hơn.

Bài báo này bao gồm hai phần. Phần đầu tiên sẽ giới thiệu về mô hình hóa các bài toán tập hợp. Phần thứ hai sẽ giới thiệu thuật toán tổng hợp của DODO và phân tích những khó khăn trong thiết kế kỹ thuật tổng hợp.

1. Giới thiệu mô hình và phân tích giải pháp

Mô hình hóa phù hợp là một khởi đầu tuyệt vời để giải quyết một vấn đề. Hãy bắt đầu với vấn đề đơn giản nhất: định tuyến tuyến tính.

1.1 Định tuyến tuyến tính

Định tuyến tuyến tính là quá trình tìm kiếm một đường dẫn giao dịch tối ưu được cung cấp cho mã thông báo mục tiêu trong đó một cặp giao dịch chỉ đi qua một nhóm. Ví dụ: nếu người dùng cần giao dịch ETH sang USDC, thì đường dẫn tối ưu mà A định tuyến tuyến tính tìm thấy là giao dịch ETH sang USDT, sau đó chuyển đến USDC, không phải [ACB] hoặc [ADB] (nghĩa là tài sản A là không chia thành hai phần và chọn các đường dẫn khác nhau). Con đường đã chọn chỉ đi qua hai vũng. Hai nhóm này có thể đến từ các giao thức khác nhau. Ví dụ: giao thức để giao dịch ETH sang USDT là từ nhóm Uniswap V3 và giao thức USDT-USDC là từ nhóm Curve V1. DEX như Uniswap V2 và PancakeSwap cũng sử dụng mô hình định tuyến này. Tuy nhiên, nguồn thanh khoản của họ là trao đổi của họ. Các tuyến Uniswap V2 chỉ đi qua các nhóm Uniswap V2, trong khi các tuyến PancakeSwap chỉ đi qua các nhóm PancakeSwap.

[Hình 2: Nội dung trong ô màu đỏ được đánh dấu trong hình là đường dẫn định tuyến]

Giả sử người dùng cần bán mã thông báo: fromToken và mã thông báo họ muốn mua: toToken . Đối với bất kỳ nhóm nào, baseToken được định nghĩa là mã thông báo bán và quoteToken là mã thông báo mua. BaseToken của nhóm đầu tiên phải là fromToken và quoteToken của nhóm cuối cùng phải là toToken , như thể hiện trong hình bên dưới.

Nó có thể được tóm tắt trực tiếp như một bài toán về giá trị tối đa: có n tài sản khác nhau, có k nhóm khác nhau và số lượng mã thông báo được trao đổi trong mỗi nhóm có thể được biểu thị bằng một tập hợp các hàm

Vì nhóm mã thông báo kép có thể đại diện cho tất cả nhóm 3 mã thông báo hoặc nhiều mã thông báo, nên hàm có thể được viết tắt thêm là:

trong đó αi đại diện cho số lượng nội dung thứ i, α đại diện cho số lượng nội dung jᵗʰ và k đại diện cho số nhóm. Giả sử số lượng fromToken của người dùng là αᶠ và cuối cùng, số lượng toToken αᵗ có thể thu được. Bộ mã thông báo được trao đổi trong quá trình này như sau:

Có các nhóm m-1 trong quá trình này và chúng tôi sẽ trình bày điều đó dưới dạng theta:

Sau đó,

Nếu chúng ta có thể tìm ra lời giải cho các vấn đề trên, chúng ta có thể có được con đường tối ưu.

Mô hình này vẫn còn quá trừu tượng và chúng ta có thể sử dụng lý thuyết đồ thị để xây dựng một mô hình khác. BaseToken từ i đến j đại diện cho cạnh ρⁱʲᵏ và cạnh từ j đến i là ρʲⁱᵏ Trọng số cạnh được đặt thành α₀ chia cho số lượng quoteTokens được trao đổi bởi nhóm αⱼ. α₀ / αⱼ có thể xây dựng đồ thị có hướng sau với nhiều cạnh và vành, như hình dưới đây:

Sau đó, vấn đề có thể được tóm tắt là: từ điểm gốc F , tức là, Tìm một đường dẫn từ fromToken để giảm thiểu trọng số đến toToken .

Thoạt nhìn, nó có vẻ là một bài toán đơn giản về đường đi ngắn nhất, và có rất nhiều thuật toán thuần thục để tham khảo. Nhưng không giống như các bài toán đường đi ngắn nhất thông thường, trong quá trình tìm kiếm cạnh tiếp theo, trọng số của một cạnh được liên kết với đường đi phía trước dãy nút. Do đó, trong đường dẫn tối ưu của các nút tham gia hàng đợi, mỗi nút có một trạng thái cần được duy trì trong thời gian thực. Nó làm cho các nút trình tự tiếp theo có độ dài đường dẫn đã ghi khớp với trạng thái của các nút trình tự trước đó. Và trong bài toán này, “trọng số tối thiểu” cuối cùng được tính không phải bằng cách tính tổng trọng số của tất cả các cạnh trên đường dẫn mà chỉ bằng cách tính trọng số đầu vào của nút toToken . Đặc điểm này làm cho thuật toán đường đi ngắn nhất truyền thống không áp dụng được hoàn toàn.

Khi có ít nút, sẽ trực quan hơn khi tìm kiếm trực tiếp bằng thuật toán Tìm kiếm đầu tiên (DFS) theo chiều sâu, nghĩa là đi qua mọi con đường và lấy giá toToken cuối cùng , để chọn con đường tối ưu cho người dùng trao đổi. Lộ trình Uniswap V2 sử dụng phương pháp này để tìm đường dẫn tối ưu. Phiên bản đầu tiên của lộ trình Uniswap V3 cũng sử dụng phương pháp này. Tuy nhiên, không giống như V2, giá của V2 có thể được tính trực tiếp thông qua chuỗi. Và sau đó đa cuộc gọi gọi đến hợp đồng trích dẫn và nhận kết quả trực tiếp.

[Hình 5: Mã nguồn thuật toán định tuyến Uniswap v2]

Mô hình được đề cập ở trên không phù hợp với thuật toán BFS. Giả sử thuật toán BFS được thực hiện theo cạnh (nghĩa là, thuật toán BFS được thực hiện theo nhóm). Trong trường hợp đó, hồ bơi không được chọn ở trạng thái này cần được bảo trì đồng bộ. Bước tiếp theo chỉ có thể được mở rộng trong nhóm không được chọn, điều này không có sự khác biệt với độ phức tạp của thuật toán DFS nhưng làm tăng đáng kể chi phí không gian để ghi. Tuy nhiên, một vấn đề nghiêm trọng sẽ xảy ra nếu các nút được mở rộng theo thuật toán BFS: nút có thể được duyệt lặp đi lặp lại. Do đó, nó không thỏa mãn điều kiện thuật toán BFS.

Tương tự, do sự tồn tại của hậu quả, phương pháp cắt tỉa trong thuật toán DFS vẫn chưa được xem xét trong thời điểm hiện tại. Phương pháp tốt nhất tiếp theo là sắp xếp trước kích thước nhóm và xóa một số nhóm trước khi nhập thuật toán DFS, nhưng có một số rủi ro nhất định trong việc xóa các nhóm, điều này có thể ảnh hưởng đến tính tối ưu.

Việc áp dụng thuật toán DFS có thể đảm bảo đường dẫn tối ưu từ fromToken đến toToken của đồ thị hiện tại. Độ phức tạp về thời gian liên quan đến số lớp. May mắn thay, để đảm bảo tính hợp lý của khí, số lớp đệ quy sẽ không vượt quá 4, do đó độ phức tạp về thời gian là O (l ^ 3), và l là tổng số cạnh.

1.2 Định tuyến phân chia

Khi xem xét các vấn đề phức tạp, việc chọn đường dẫn báo giá tối ưu còn được gọi là định tuyến phân tách. Trong quá trình tìm kiếm đường giao dịch, một cặp giao dịch có thể đi qua các nhóm khác nhau và tiền của người dùng được phân bổ cho các nhóm khác nhau để trao đổi theo tỷ lệ tối ưu để làm cho mã thông báo mục tiêu cung cấp tối ưu. Tương tự, hãy lấy ETH-USDC làm ví dụ. Đường dẫn giao dịch vẫn đi qua ETH đến USDT và sau đó đến USDC. ETH và USDT có thể đi qua hai nhóm. 30% ETH được chuyển đổi sang USDT thông qua Uniswap V3 và 70% thành USDT thông qua DODO V2. Khi USDT được đổi sang USDC trong giao dịch tiếp theo, USDT ban đầu là tổng của hai phần trên của USDT, sự phân chia tối ưu của USDT sang USDC được tìm thấy.

Trong đường dẫn đặt giá thầu tối ưu, toàn bộ fromAmount có thể được chia thành các đường dẫn hoặc nhóm khác nhau để giao dịch theo tỷ lệ của số tiền đường dẫn. Một mạng dòng chảy có thể được xác định trong sơ đồ ban đầu, tùy thuộc vào đơn vị tỷ lệ nhỏ nhất được sử dụng để phân vùng. Một siêu nguồn có thể được thiết lập nếu fromAmount có thể được chia thành n phần. Giới hạn trên của luồng từ siêu nguồn đến nút fromTokenn và giới hạn trên của luồng từ các cạnh còn lại là dương vô cùng. α₀ chia cho số lượng quoteTokens được trao đổi bởi nhóm αⱼ, α₀ / αⱼ là chi phí của cạnh cⁱʲᵏ, sử dụng phương pháp đơn giản hóa được mô tả ở trên, nhóm kchỉ chứa các mã thông báo ij , có thể được đơn giản hóa là cʲᵏ. Sau đó, vấn đề là tìm dòng chảy tối đa với chi phí tối thiểu trong đồ thị.

Đặc biệt, phí có tính năng động. Cụ thể, để đảm bảo tuân thủ mức độ ràng buộc của các nút, chúng ta có thể giả định rằng dòng chảy không tăng hoặc giảm ( x % của lượng ban đầu) khi nó đi qua nút, chỉ ảnh hưởng đến chi phí. Vì chi phí của cạnh liên quan đến số lượng baseToken và số lượng liên quan đến đường dẫn, chi phí của mỗi cạnh w có thể được định nghĩa là:

Trong đó cⁱʲᵏ là chi phí đường dẫn, baseTokeni , quoteTokenj và số nhóm là k . Nó là một hàm của wⁱᵏ, là hàm trích dẫn của pool. 𝔲 là đường đi từ 0 đến I , wⁱᵏ được định nghĩa là lưu lượng trên nút i đi qua đường dẫn k . Có:

wⁱ là lưu lượng của nút I. Bởi vì yếu tố duy nhất ảnh hưởng đến số lượng quoteToken là số lượng baseToken , cⁱʲᵏ có thể được đơn giản hóa thêm như sau:

Trong đó cᵢₗ là chi phí đầu vào của nút i , ι∈ ∑ [1,…, q] là số cạnh đầu vào. Để giải quyết vấn đề về tỷ lệ phân vùng, một ý tưởng phổ biến là chia dòng chảy có thể thành n phần và sau đó chia cạnh Pⁱʲᵏ thành n phần. Dòng chảy được chia thành n phần bằng nhau, ký hiệu là wⁱᵏ = 1,2… n. ở đâu

cạnh tương ứng của nó P'ⁱʲᵏ, 0 <o <n + 1, thì cⁱʲᵏ được định nghĩa là:

Không nên chọn lặp lại các đường dẫn con được phân tách bởi cùng một nhóm cạnh.

Tương tự, chi phí tối thiểu được giải quyết cuối cùng chỉ được xác định bởi chi phí đầu vào của toToken .

Vì chi phí phụ thuộc vào đường dẫn trong quá khứ, nên thuật toán đường dẫn tăng cường thường để giải quyết luồng chi phí tối đa tối thiểu không được áp dụng. Một vấn đề khác là phương pháp này giới hạn cùng một nhóm chỉ lấy một trong các đường dẫn con được phân tách, do đó không thể tính được tổng giữa các đường dẫn con và đường dẫn tăng cường không thể chỉ đơn giản đảo ngược dòng chảy.

Vấn đề đòi hỏi một giải pháp khác. Vì bài toán này là bài toán tối ưu khi đủ lực và thời gian tính toán nên có thể xét các thông số mô phỏng ngẫu nhiên. Các tham số ước lượng MCMC có thể được sử dụng bằng cách tính toán trực tiếp. Những người trong ngành thực tế quan tâm đến thời gian và độ tin cậy hơn là giải pháp tối ưu cho vấn đề. Trong các phần tiếp theo, tôi cố gắng phân tích các giải pháp của các công ty tổng hợp khác trong ngành để minh họa hai giải pháp đơn giản hóa cho vấn đề.

1.3 Phân tích tổng hợp

0x

Thông qua phân tích mã nguồn 0x và kết quả trả về của API, 0x đơn giản hóa các câu hỏi thành hai mô hình độc lập, đưa ra báo giá tối ưu tương ứng, sau đó chọn giải pháp tối ưu để trả lại cho người dùng.

Đơn giản hóa câu hỏi 1: Định tuyến tuyến tính, kết quả từ nhiều bước được API trả về.

Đơn giản hóa câu hỏi 2: Định tuyến tách bước đơn. Chỉ các nhóm fromToken đến toToken được giữ lại.

Đối với định tuyến tách một bước nhảy, mỗi đường dẫn có thể được chia thành N đường dẫn con theo hệ số phân tán N và chi phí của mỗi đường dẫn con là quoteToken khi lưu lượng truy cập là i , cũng là đơn giá của toToken , và sau đó được giải quyết.

Đặc biệt, 0x gọi hợp đồng tuyến khi xây dựng các đường dẫn liên quan đến SushiSwap hoặc Uniswap, vì vậy có thể có nhiều bước nhảy trung gian trong đường dẫn, về cơ bản tính các bước nhảy như một tổng thể.

1 inch / ParaSwap

Đối với 1 inch, đường dẫn khí tối ưu trong 1 inch v2 là một tuyến đường thẳng.

Định tuyến phân tách của 1inch v2 cập nhật thuật toán Pathfinder, có cấu trúc sau:

Tương tự, Paraswap sử dụng cùng một mô hình như 1 inch:

Giao diện người dùng không hiển thị đường dẫn phân chia trong bước nhảy đơn, nhưng API có thể quan sát kết quả được chia

[Trường bestRoute trong API ghi lại chi tiết của đường dẫn định tuyến. Như trong hình, ParaSwap đã chọn ParaSwapPool7 và Uniswap V3 cho các cặp giao dịch trong cặp giao dịch USDT (0xdAC17F958D2ee523a2206206994597C13D831ec7) thành ETH, lần lượt chiếm 38,46% và 61,54%]

Mô hình này có thể được biểu thị trực tiếp như sau:

Trong đó Af đại diện cho tổng số lượng mã thông báo cơ sở và được chia thành n đường dẫn cho giao dịch. Gọi số toToken cuối cùng thu được là At, cũng là tổng của n đường dẫn:

Mỗi con đường có thể trải qua một số nhóm / sàn giao dịch khác nhau và trao đổi các mã thông báo khác nhau ở giữa. Sử dụng mô hình trên, ati có thể được biểu diễn trực tiếp như sau:

Giải pháp này có thể được hiểu là tìm ba đường dẫn chi phí tối thiểu không lặp lại trong bài toán, giải pháp này gần với giải pháp tối ưu hơn so với thuật toán 0x. Nhưng nó cũng là một phiên bản đơn giản hóa xem xét trường hợp bí mật khi hai đường dẫn khác nhau hội tụ về cùng một nút.

Mặc dù Pathfinder 1 inch không loại trừ các nút trùng lặp (có nghĩa là, các đường dẫn khác nhau thông qua cùng một đơn vị tiền tệ) trong thiết kế các đường dẫn phụ, nó tránh được vấn đề sử dụng cùng một nguồn báo giá hai lần bằng cách chỉ định các đường dẫn phụ khác nhau cho các nguồn báo giá khác nhau, trong một số trường hợp, giải pháp của nó vẫn không tối ưu. Kích thước cụ thể của tác động có thể được kiểm tra độ nhạy.

Tuy nhiên, như phân tích cho thấy, mô hình này gần với mô hình ban đầu nhất. Nếu có thể đưa ra phương án tối ưu cho bài toán thì lời giải đó gần với bài toán ban đầu hơn và đưa ra lời giải tối ưu (có thể đo được độ nhiễu của mô hình). Tác dụng duy nhất là quan sát thông số API và kết quả 1inch. Có thể suy ra rằng 1inch đã tùy chỉnh số lượng bản sao được chỉ định, điều này có thể gây ra một số lỗi tùy chỉnh. Khi bạn nhìn vào tỷ lệ phân tách của ParaSwap, nó có vẻ nhỏ hơn 1 inch. Trong một số trường hợp, ParaSwap có thể nhận được kết quả tốt hơn 1 inch, điều này có thể đóng góp.

DODO

Thuật toán định tuyến tự xây dựng của DODO cũng đơn giản hóa vấn đề bằng cách tham khảo các thiết kế 1inch và 0x. Xem xét mức tiêu thụ khí và tỷ lệ giao dịch thành công, chúng tôi đã đơn giản hóa phiên bản v1 định tuyến thành mô hình sau:

Đường dẫn mã thông báo là duy nhất, nhưng đường dẫn nhóm thì không.

Trong quá trình định tuyến của phiên bản V2, DODO sẽ tham khảo thiết kế mô hình của 1inch và ParaSwap để tối ưu hóa việc định tuyến phân tách của đường dẫn đa mã thông báo và đường dẫn phụ đa nhóm.

Bài viết này đã chia sẻ một số cách tiếp cận mô hình hóa có thể có đối với các vấn đề về bộ tổng hợp. Trong phần tiếp theo, chúng tôi sẽ trình bày một ý tưởng thiết kế kỹ thuật khả thi dựa trên thuật toán định tuyến tự xây dựng của DODO.

Tuyên bố từ chối trách nhiệm

Thông tin trong báo cáo nghiên cứu này được lấy từ các thông tin được công bố công khai và các ý kiến ​​được trình bày ở đây chỉ nhằm mục đích nghiên cứu và không đại diện cho bất kỳ lời khuyên đầu tư nào. Các ý kiến ​​và dự báo được trình bày trong báo cáo này là phân tích và nhận định về ngày ban hành và không có giá trị vĩnh viễn.

Link: https://blog.dodoex.io/dodo-research-reveal-the-secrets-of-the-aggregator-problem-analysis-and-model-building-ba0ead85948c

#blockchain #defi #dex #dodo

Tiết Lộ Bí Mật Của Trang Tổng Hợp Nghiên Cứu DODO

Раскрываем секреты агрегатора исследований DODO

«Как найти оптимальные ставки для пользователей» — неотъемлемая часть децентрализованных финансов (DeFi). В настоящее время на рынке существует множество протоколов DeFi. Различные протоколы имеют уникальные алгоритмы. Из-за относительно независимых источников ликвидности DeFi разные пулы будут иметь разные котировки на одну и ту же валюту. Децентрализованные биржи (DEX) разработали свой алгоритм для привлечения поставщиков ликвидности (LP) для получения более выгодных предложений. С другой стороны, такие агрегаторы, как 1inch и 0x, пошли по другому пути: путем поиска путей, образованных разными пулами, мы можем найти оптимальные ставки для пользователей, находящихся под контролем газа.

С развитием рынка такие агрегаторы, как 1inch и 0x, также будут иметь свои уникальные источники котировок. DEX, такие как Balancer и Uniswap V3, также разделят транзакцию пользователя на несколько путей. Разница в том, что алгоритм агрегации DEX полагается на свой пул котировок, тогда как агрегаторы в полной мере используют компонуемость DeFi. Агрегатор может предоставить пользователям лучшую котировку, потому что он может получить доступ к своему пулу и пулам других DEX, увеличивая источник ликвидности всей цепочки.

DODO стремится предоставить пользователям лучший торговый опыт. Помимо разработки своего пула PMM , DODO самостоятельно разработала алгоритм агрегации. Алгоритм агрегации DODO — это не алгоритм разделенной маршрутизации DEX, такой как Uniswap, а алгоритм агрегации, аналогичный алгоритму 1inch и 0x. DODO будет подключать не только свои пулы, но и другие пулы DEX, чтобы лучше использовать ликвидность.

Эта статья состоит из двух частей. В первой части будет представлено моделирование проблем агрегации. Во второй части будет представлен алгоритм агрегатора DODO и проанализированы трудности проектирования агрегатора.

1. Введение в моделирование и анализ решения

Правильное моделирование — отличное начало решения проблемы. Начнем с самой простой задачи: линейной маршрутизации.

1.1 Линейная маршрутизация

Линейная маршрутизация — это процесс поиска оптимального торгового пути, предлагаемого для целевого токена, при котором торговая пара проходит только через пул. Например, если пользователю нужно обменять ETH на USDC, оптимальный путь, найденный линейной маршрутизацией A, — это обменять ETH на USDT, тогда он пойдет на USDC, а не на [ACB] или [ADB] (то есть актив A не разбивается на две части и выбирает разные пути). Выбранный путь проходит только через два пула. Эти два пула могут исходить из разных протоколов. Например, протокол обмена ETH на USDT принадлежит пулу Uniswap V3, а протокол USDT-USDC — пулу Curve V1. DEX, такие как Uniswap V2 и PancakeSwap, также используют эту модель маршрутизации. Однако источником их ликвидности является их биржа. Маршруты Uniswap V2 проходят только через пулы Uniswap V2, а маршруты PancakeSwap проходят только через пулы PancakeSwap.

[Рисунок 2: Содержимое в красной рамке, отмеченной на рисунке, представляет собой путь маршрутизации]

Предположим, пользователям токенов нужно продать: fromToken , а токен, который они хотят купить: toToken . Для любого пула baseToken определяется как токен продажи, а quoteToken — как токен покупки. BaseToken первого пула должен быть fromToken , а quoteToken последнего пула должен быть toToken , как показано на рисунке ниже.

Ее можно непосредственно сформулировать как проблему максимальной ценности: имеется n различных активов, имеется k других различных пулов, и количество токенов, обмениваемых в каждом пуле, может быть выражено набором функций

Поскольку пулы с двумя токенами могут представлять все пулы с 3 токенами или несколькими токенами, эта функция может быть дополнительно сокращена как:

где представляет αi номер актива iᵗʰ, αire представляет номер актива jᵗʰ, а k представляет номер пула. Предположим, что номер fromToken пользователя равен αᶠ, и, наконец, можно получить номер toToken αᵗ. Набор токенов, которым обмениваются в процессе, выглядит следующим образом:

В этом процессе есть m-1 пулов, и мы собираемся представить это как тета:

Затем,

Если мы сможем найти решение вышеуказанных проблем, мы сможем получить оптимальный путь.

Это моделирование все еще слишком абстрактно, и мы можем использовать теорию графов для построения другой модели. BaseToken от i до j представляет ребро ρⁱʲᵏ, а ребро от j до i равно ρʲⁱᵏ. Вес ребра устанавливается равным α₀, деленному на количество кавычек , которыми обменивается пул αⱼ. α₀/αⱼ можно построить следующий ориентированный граф с несколькими ребрами и кольцами, как показано ниже:

Тогда задачу можно резюмировать следующим образом: от источника F , т. е. найти путь от fromToken , который минимизирует вес до toToken .

На первый взгляд кажется, что это простая задача о кратчайшем пути, и существует множество зрелых алгоритмов для справки. Но в отличие от обычных задач поиска кратчайшего пути, в процессе поиска следующего ребра под весом ребра связывается путь перед последовательностью узла. Следовательно, в оптимальном пути узлов, присоединяющихся к очереди, каждый узел имеет состояние, которое необходимо поддерживать в режиме реального времени. Это заставляет последующие узлы последовательности записанной длины пути соответствовать состоянию предыдущих узлов последовательности. И в этой задаче итоговый «минимальный вес» вычисляется не путем суммирования весов всех ребер на пути, а путем вычисления только веса входа узла toToken . Эта характеристика делает традиционный алгоритм поиска кратчайшего пути не полностью применимым.

Когда узлов немного, удобнее искать с помощью алгоритма поиска в глубину (DFS) напрямую, то есть пройти каждый путь и получить окончательную цену toToken , чтобы выбрать оптимальный путь для обмена пользователями. Маршрут Uniswap V2 использует этот метод для поиска оптимального пути. Этот метод также используется в первой версии маршрута Uniswap V3. Однако, в отличие от V2, цену V2 можно рассчитать напрямую через цепочку. А затем множественный вызов вызывает контракт котировщика и получает результат напрямую.

[Рисунок 5: Исходный код алгоритма маршрутизации Uniswap v2]

Упомянутая выше модель не подходит для алгоритма BFS. Допустим, алгоритм BFS выполняется по ребру (то есть алгоритм BFS выполняется по пулу). В этом случае пул, не выбранный в этом состоянии, необходимо поддерживать синхронно. Следующий шаг может быть расширен только в невыбранном пуле, что ничем не отличается от сложности алгоритма DFS, но резко увеличивает стоимость места для записи. Однако, если узлы расширяются по алгоритму BFS, возникает фатальная проблема: узел можно обходить многократно. Следовательно, он не удовлетворяет условию алгоритма BFS.

Точно так же из-за наличия последействия метод обрезки в алгоритме DFS пока не рассматривался. Следующий лучший метод — предварительно отсортировать размер пула и удалить некоторые пулы перед входом в алгоритм DFS, но при удалении пулов есть определенные риски, которые могут повлиять на оптимальность.

Применение алгоритма DFS может обеспечить оптимальный путь от fromToken к toToken текущего графа. Временная сложность связана с количеством слоев. К счастью, для обеспечения рациональности газа число рекурсивных слоев не будет превышать 4, поэтому временная сложность равна O(l ^ 3), а l — общее количество ребер.

1.2 Раздельная маршрутизация

При рассмотрении сложных задач выбор оптимального пути котировки также называют раздельной маршрутизацией. В процессе поиска торгового пути торговая пара может проходить через разные пулы, и средства пользователя распределяются по разным пулам для обмена в оптимальной пропорции, чтобы целевое предложение токена было оптимальным. Точно так же возьмем в качестве примера ETH-USDC. Путь транзакции по-прежнему проходит через ETH в USDT, а затем в USDC. ETH и USDT могут проходить через два пула. 30% ETH конвертируется в USDT через Uniswap V3 и 70% в USDT через DODO V2. Когда USDT обменивается на USDC в следующей транзакции, начальный USDT представляет собой сумму двух вышеуказанных частей USDT, оптимальное разделение USDT на USDC находится.

В оптимальном пути торгов полная сумма fromAmount может быть разделена на разные пути или пулы для торговли в соответствии с пропорцией суммы пути. Поточная сеть может быть определена на исходной диаграмме в зависимости от наименьшей единицы масштаба, используемой для разделения. Супер-источник может быть установлен, если fromAmount можно разделить на n частей. Верхний предел потока от супер-источника к узлу fromToken равен n , а верхний предел потока из остальных ребер — положительная бесконечность. α₀ разделить на количество кавычек , которыми обменивается пул αⱼ, α₀/αⱼ как стоимость ребра cⁱʲᵏ, используя метод упрощения, описанный выше, пул kсодержит только токены i и j , которые можно упростить как cʲᵏ. Тогда задача состоит в том, чтобы найти в графе максимальный поток с минимальной стоимостью.

В частности, сборы динамичны. В частности, чтобы обеспечить соблюдение ограничения степени узлов, мы можем предположить, что поток не увеличивается и не уменьшается (на x % от исходной суммы) при прохождении через узел, а влияет только на стоимость. Поскольку стоимость ребра связана с количеством baseToken, а количество связано с путем, стоимость каждого ребра w может быть определена как:

Где cⁱʲᵏ — стоимость пути, baseTokeni , quoteTokenj , а номер пула — k . Это функция wⁱᵏ, которая является функцией котировки пула. 𝔲 — это путь от 0 до I , wⁱᵏ определяется как трафик на узле i , проходящий через путь k . Есть:

wⁱ — трафик узла I. Поскольку единственным фактором, влияющим на количество quoteToken, является количество baseToken , cⁱʲᵏ можно упростить следующим образом:

Где cᵢₗ — входная стоимость узла i , ι∈ ∑ [1,…,q] — количество входных ребер. Чтобы решить проблему коэффициента разделения, общая идея состоит в том, чтобы разделить возможный поток на n частей, а затем разделить ребро Pⁱʲᵏ на n частей. Поток был разделен на n равных частей, обозначенных как wⁱᵏ=1,2…n. куда

соответствующее ему ребро P'ⁱʲᵏ, 0<o<n+1, то cⁱʲᵏ определяется как:

Подпути, разделенные одной и той же группой ребер, не должны выбираться повторно.

Точно так же минимальная стоимость, решаемая в конце, определяется только входной стоимостью toToken .

Поскольку стоимость зависит от прошлого пути, обычно алгоритм расширенного пути для решения максимального потока с минимальной стоимостью неприменим. Другая проблема заключается в том, что этот метод ограничивает один и тот же пул только одним из разделенных подпутей, поэтому сумма между подпутями не может быть рассчитана, а расширенный путь не может просто реверсировать поток.

Проблема требует другого решения. Поскольку эта задача является задачей оптимизации, когда сил и времени расчета достаточно, можно рассмотреть случайные параметры моделирования. Параметры оценки MCMC можно использовать путем прямого расчета. Людей в реальной отрасли больше волнуют время и надежность, чем оптимальное решение проблемы. В следующих разделах я попытаюсь проанализировать решения других агрегаторов в отрасли, чтобы проиллюстрировать два упрощенных решения проблемы.

1.3 Агрегаторный анализ

0x

Благодаря анализу исходного кода 0x и возвращенным API результатам, 0x упрощает вопросы, превращая их в две независимые модели, которые соответственно дают оптимальную котировку, а затем выбирают оптимальное решение для возврата пользователям.

Упростите вопрос 1: линейная маршрутизация, которая является результатом множественных переходов, возвращаемых API.

Упростите вопрос 2: маршрутизация с разделением на один переход. Сохраняются только пулы fromToken to toToken .

Для маршрутизации с разделением на один переход каждый путь может быть разделен на N подпутей в соответствии с коэффициентом дисперсии N , а стоимость каждого подпути равна quoteToken , когда трафик равен i , что также является ценой toToken за единицу . а потом решил.

В частности, 0x вызывает контракт маршрута при построении путей, связанных с SushiSwap или Uniswap, поэтому в пути может быть несколько промежуточных переходов, по существу подсчитывающих переходы как целый пул.

1 дюйм/паразамена

Для 1 дюйма оптимальный путь газа в 1 дюйме v2 — это линейный путь.

Раздельная маршрутизация 1inch v2 обновляет алгоритм Pathfinder, который имеет следующую структуру:

Точно так же Paraswap использует ту же модель, что и 1 дюйм:

Внешний интерфейс не показывает разделенный путь в одном прыжке, но API может наблюдать разделенный результат.

[Поле bestRoute в API записывает сведения о пути маршрутизации. Как показано на рисунке, ParaSwap выбрал ParaSwapPool7 и Uniswap V3 для торговых пар в торговой паре USDT (0xdAC17F958D2ee523a2206206994597C13D831ec7) к ETH, что составляет 38,46% и 61,54% соответственно]

Эта модель может быть прямо выражена как:

Где Af представляет собой общую сумму базового токена и делится на n путей для транзакции. Пусть окончательное число полученных toToken равно At, что также является суммой n путей:

Каждый путь может иметь разное количество пулов/обменов и обмениваться разными токенами посередине. Используя приведенную выше модель, ати можно напрямую выразить как:

Это решение можно интерпретировать как нахождение трех неповторяющихся путей с минимальной стоимостью в задаче, что ближе к оптимальному решению, чем алгоритм 0x. Но это также упрощенная версия, которая рассматривает скрытый случай, когда два разных пути сходятся к одному и тому же узлу.

Хотя 1-дюймовый Pathfinder не исключает повторяющиеся узлы (то есть разные пути через одну и ту же валюту) в своем дизайне путей субтокенов, он позволяет избежать проблемы использования одного и того же источника котировок дважды, назначая разные подпути разным источникам котировок. в некоторых случаях его решение все же будет отставать от оптимального. Конкретный размер удара можно проверить на чувствительность.

Однако, как показывает анализ, эта модель наиболее близка к исходной модели. Если оптимальное решение проблемы может быть дано, решение ближе к исходной задаче и дает оптимальное решение (возмущение модели может быть измерено). Единственный эффект заключается в наблюдении за параметрами API и результатами 1inch. Можно сделать вывод, что 1inch дискретизировал указанное количество копий, что может вызвать некоторые ошибки дискретизации. Когда вы смотрите на коэффициент разделения ParaSwap, кажется, что он меньше 1 дюйма. В некоторых случаях ParaSwap может дать лучшие результаты, чем 1 дюйм, что может внести свой вклад.

ДОДО

Самостоятельный алгоритм маршрутизации DODO также упрощает проблему, ссылаясь на конструкции 1inch и 0x. Учитывая потребление газа и процент успешных транзакций, мы упростили версию маршрутизации v1 до следующей модели:

Путь токена уникален, а путь пула — нет.

В маршрутизации версии V2 DODO будет ссылаться на дизайн модели 1inch и ParaSwap для оптимизации разделенной маршрутизации пути с несколькими маркерами и подпутей с несколькими пулами.

В этой статье представлены несколько возможных подходов к моделированию проблем с агрегаторами. В следующей части мы представим возможную идею инженерного проектирования, основанную на самостоятельном построении алгоритма маршрутизации DODO.

Отказ от ответственности

Информация в этом исследовательском отчете получена из общедоступной информации, а мнения, выраженные в нем, предназначены только для исследовательских целей и не представляют собой каких-либо инвестиционных рекомендаций. Мнения и прогнозы, выраженные в этом отчете, являются анализом и суждением на дату публикации и не имеют постоянной силы.

Link: https://blog.dodoex.io/dodo-research-reveal-the-secrets-of-the-aggregator-problem-analysis-and-model-building-ba0ead85948c

#blockchain #defi #dex

Раскрываем секреты агрегатора исследований DODO
井上  康弘

井上 康弘

1657784586

揭示 DODO 研究聚合器的秘密

“如何為用戶找到最優的出價”是去中心化金融(DeFi)的重要組成部分。目前市面上的 DeFi 協議比較多。不同的協議具有獨特的算法。由於 DeFi 的流動性來源相對獨立,不同的礦池對同一種幣種會有不同的報價。去中心化交易所(DEX)設計了它的算法來吸引流動性提供者(LP)以獲得更好的報價。另一方面,1inch、0x等聚合器選擇了另一種方式:通過搜索不同礦池形成的路徑,在gas的控制下找到用戶的最優出價。

隨著市場的發展,1inch、0x等聚合商也將擁有其獨特的報價來源。Balancer 和 Uniswap V3 等 DEX 也會將用戶的一筆交易拆分成多條路徑。不同的是,DEX 的聚合算法依賴於其報價池,而聚合器則充分利用了 DeFi 的可組合性。聚合器可以為用戶提供最優報價,因為它可以訪問自己的礦池和其他 DEX 的礦池,增加了整個鏈的流動性來源。

DODO致力於為用戶提供最佳的交易體驗。DODO除了開發PMM池外,還自主開發了聚合算法。DODO 的聚合算法不是 Uniswap 等 DEX 的拆分路由算法,而是類似於 1inch 和 0x 的聚合算法。DODO 不僅會插入其池,還會插入其他 DEX 池,以更好地利用流動性。

本文由兩部分組成。第一部分將介紹聚合問題的建模。第二部分將介紹DODO的聚合器算法,分析聚合器工程設計的難點。

1. 建模介紹及解決方案分析

正確的建模是解決問題的良好開端。讓我們從最直接的問題開始:線性路由。

1.1 線性路由

線性路由是尋找為目標代幣提供的最佳交易路徑的過程,其中交易對僅通過池。例如,如果用戶需要將 ETH 交易到 USDC,A 線性路由找到的最優路徑是將 ETH 交易到 USDT,那麼它去 USDC,而不是 [ACB] 或 [ADB](即資產 A 是不分成兩部分並選擇不同的路徑)。選擇的路徑只經過兩個池。這兩個池可能來自不同的協議。例如,ETH 到 USDT 的交易協議來自 Uniswap V3 礦池,USDT-USDC 協議來自 Curve V1 礦池。Uniswap V2 和 PancakeSwap 等 DEX 也使用這種路由模型。但是,他們的流動性來源是他們的交易所。Uniswap V2 路由僅通過 Uniswap V2 池,而 PancakeSwap 路由僅通過 PancakeSwap 池。

【圖2:圖中紅框內的內容為路由路徑】

假設用戶需要出售的代幣:fromToken,想要購買的代幣:toToken。對於任何礦池,baseToken被定義為賣出代幣, quoteToken被定義為買入代幣。第一個礦池的 baseToken 必須是fromToken ,最後一個礦池的 quoteToken 必須是toToken,如下圖所示。

可以直接概括為一個最大值問題:有n種不同的資產,還有k種其他不同的池子,每個池子中兌換的代幣數量可以用一組函數來表示

由於雙代幣池可以代表所有三代幣或多代幣池,所以函數可以進一步簡寫為:

其中,αi 表示 iᵗʰ 資產的數量,αi 表示 jᵗʰ 資產的數量,k表示池數。假設用戶的fromToken數量為αᶠ,最後可以得到toToken的數量αᵗ 過程中兌換的代幣集如下:

在這個過程中有 m-1 個池,我們將其表示為 theta:

然後,

如果我們能找到上述問題的解決方案,我們就可以得到最優路徑。

這個建模還是太抽象了,我們可以用圖論來構建另一個模型。從ijbaseToken表示邊 ρⁱʲᵏ,從ji的邊是 ρʲⁱᵏ 邊權重設置為 α₀ 除以池αⱼ交換的 quoteToken 數量。α₀/αⱼ可以構建如下多邊多環有向圖,如下圖:

那麼問題可以概括為:從原點F,即從fromToken中找到一條權重最小的路徑到toToken

乍一看,這似乎是一個關於最短路徑的直截了當的問題,並且有很多成熟的算法可供參考。但與普通最短路徑問題不同的是,在尋找下一條邊的過程中,一條邊的權重下與節點序列前面的路徑相關聯。因此,在節點加入隊列的最優路徑中,每個節點都有一個需要實時維護的狀態。它使記錄路徑長度的後續序列節點與前面序列節點的狀態相匹配。而在這個問題中,最終的“最小權重”不是通過對路徑上所有邊的權重求和來計算的,而是通過僅計算toToken節點的入口權重來計算的。這一特點使得傳統的最短路徑算法不能完全適用。

當節點較少時,直接用深度優先搜索(DFS)算法搜索更為直觀,即遍歷每條路徑,得到最終toToken價格,選擇最優路徑供用戶兌換。Uniswap V2 路由使用這種方法來尋找最優路徑。Uniswap V3 路由的第一個版本也使用這種方法。但是,與 V2 不同的是,V2 的價格可以直接通過鏈計算。然後multi-call調用quoter合約,直接得到結果。

【圖5:Uniswap v2路由算法源碼】

上述模型不適用於 BFS 算法。假設按照邊進行BFS算法(即按照池進行BFS算法)。這種情況下,該狀態下未被選中的池需要同步維護。下一步只能在未選中的池中進行擴展,這與DFS算法的複雜度沒有區別,但會大大增加記錄的空間成本。但是,如果按照 BFS 算法擴展節點,就會出現一個致命的問題:節點可以重複遍歷。因此,它不滿足 BFS 算法條件。

同樣,由於後效應的存在,暫時沒有考慮DFS算法中的剪枝方法。下一個最好的方法是在進入 DFS 算法之前預先對池大小進行排序並刪除一些池,但是刪除池存在一定的風險,可能會影響最優性。

DFS算法的應用可以保證當前圖的fromTokentoToken的最優路徑。時間複雜度與層數有關。好在為了保證gas的合理性,遞歸層數不會超過4,所以時間複雜度為O(l^3),l為總邊數。

1.2 拆分路由

在考慮複雜問題時,選擇最優報價路徑也稱為拆分路由。在尋找交易路徑的過程中,一個交易對可能會經過不同的池子,用戶的資金以最優的比例分配到不同的池子中進行兌換,從而使目標代幣的報價最優。同樣,以 ETH-USDC 為例。交易路徑仍然是通過 ETH 到 USDT 再到 USDC。ETH 和 USDT 可能會經過兩個池子。30% 的 ETH 通過 Uniswap V3 轉換為 USDT,70% 通過 DODO V2 轉換為 USDT。下次交易將USDT兌換為USDC時,初始USDT為以上兩部分USDT之和,找到USDT與USDC的最優拆分。

在最優出價路徑中,完整的fromAmount可以根據路徑金額的比例分成不同的路徑或池子進行交易。可以在原始圖中定義流網絡,具體取決於用於分區的最小比例單位。如果fromAmount可以分為n部分,則可以建立超級源。從超級源到fromToken節點的流量上限為n,其餘邊的流量上限為正無窮大。α₀除以池αⱼ交換的quoteToken數量, α₀ /αⱼ作為邊cⁱʲᵏ的成本,使用上述簡化方法,池k僅包含ij標記,可以簡化為 cʲᵏ。那麼問題就是在圖中找到成本最小的最大流量。

特別是,費用是動態的。具體來說,為了確保符合節點的度數界限,我們可以假設流量在通過節點時不會增加或減少(原始數量的x %),只會影響成本。由於邊的成本與baseToken的數量有關,而數量與路徑有關,所以每條邊的成本w可以定義為:

其中 cⁱʲᵏ 是路徑成本,baseTokeniquoteTokenj,池數是k。它是 wⁱᵏ 的函數,它是池的報價函數。𝔲 是從0I的路徑,wⁱᵏ 定義為節點i上經過路徑k的流量。有:

wⁱ 是節點I的流量。因為影響quoteToken數量的唯一因素是baseToken數量,所以 cⁱʲᵏ 可以進一步簡化為:

其中 cᵢₗ 是節點i的輸入成本,ι∈ ∑ [1,…,q] 是輸入邊的數量。解決分割比的問題,一個常見的思路是把可能的流分成n份,然後把Pⁱʲᵏ邊分成n份。流量被分成 n 個相等的部分,表示為 wⁱᵏ=1,2…n。在哪裡

其對應的邊 P'ⁱʲᵏ,0<o<n+1,則 cⁱʲᵏ 定義為:

由同一組邊分隔的子路徑不應重複選擇。

同樣,最終解決的最小成本僅由toToken的輸入成本定義。

由於代價依賴於過去的路徑,通常用於求解最小代價最大流量的增廣路徑算法並不適用。另一個問題是,這種方法限制同一個池只能取其中一個拆分的子路徑,因此無法計算子路徑之間的總和,增廣後的路徑也不能簡單地反向流動。

這個問題需要另一種解決方案。因為這個問題是一個優化問題,在計算力和時間足夠的情況下,可以考慮隨機的模擬參數。MCMC估計參數可以直接計算使用。實際行業中的人們更關心時間和可靠性,而不是問題的最佳解決方案。在以下部分中,我將嘗試分析業內其他聚合器的解決方案,以說明該問題的兩種簡化解決方案。

1.3 聚合器分析

0x

0x通過0x源碼分析和API返回結果,將問題簡化為兩個獨立的模型,分別給出最優報價,然後選擇最優解返回給用戶。

簡化問題 1:線性路由,由 API 返回的多跳產生。

簡化問題 2:單跳拆分路由。僅保留fromTokentoToken池。

對於單跳拆分路由,每條路徑可以根據離散係數N拆分為N條子路徑,當流量為i時,每條子路徑的成本為quoteToken,也是toToken的單價,然後解決了。

特別是 0x 在構建 SushiSwap 或 Uniswap 相關路徑時會調用路由合約,因此路徑中可能存在多個中間躍點,本質上將這些躍點計算為整個池。

1英寸/ParaSwap

對於 1inch,1inch v2 中的最佳氣路是線性路線。

1inch v2的分割路由更新了Pathfinder算法,其結構如下:

同樣,Parswap 使用與 1inch 相同的型號:

前端不顯示單跳中的分割路徑,但API可以觀察分割結果

【API中的bestRoute字段記錄了路由路徑的詳細信息。如圖所示,在交易對USDT(0xdAC17F958D2ee523a2206206994597C13D831ec7)轉ETH交易對中,ParaSwap選擇ParaSwapPool7和Uniswap V3交易對,佔比分別為38.46%和61.54%]

該模型可以直接表示為:

其中 Af 表示基礎代幣的總量,分為n條路徑進行交易。設最終得到的toToken個數為At,也就是n條路徑之和:

每條路徑可能會經歷不同數量的池/交易所,並在中間交換不同的代幣。使用上述模型,ati 可以直接表示為:

這個解可以理解為在問題中找到三個不重複的最小代價路徑,比0x算法更接近最優解。但它也是一個簡化版本,考慮了兩條不同路徑匯聚到同一個節點的隱蔽情況。

1inch Pathfinder雖然在子通證路徑的設計中沒有排除重複節點(即通過同一種貨幣的不同路徑),但通過將不同的子路徑分配給不同的報價源,避免了重複使用相同報價源的問題,在某些情況下,它的解決方案仍將達不到最佳狀態。可以測試影響的具體大小的敏感性。

但是,如分析所示,該模型最接近原始模型。如果能給出問題的最優解,則解更接近原問題並給出最優解(模型擾動可測)。唯一的作用就是觀察1inch的API參數和結果。可以推斷,1inch已經離散化了指定的份數,這可能會導致一些離散化錯誤。當你看 ParaSwap 的分光比時,它似乎比 1inch 更精細。在某些情況下,ParaSwap 可以獲得比 1inch 更好的結果,這可能會有所貢獻。

渡渡鳥

DODO的自建路由算法也通過參考1inch和0x的設計來簡化問題。考慮到gas消耗和交易成功率,我們將路由v1版本簡化為以下模型:

令牌路徑是唯一的,但池路徑不是。

在 V2 版本的路由中,DODO 會參考 1inch 的模型設計和 ParaSwap 來優化多代幣路徑和多池子路徑的拆分路由。

本文分享了幾種可能的聚合器問題建模方法。在下一部分,我們將提出基於DODO自建路由算法的一種可能的工程設計思路。

免責聲明

本研究報告中的信息來源於公開披露的信息,此處表達的觀點僅用於研究目的,不代表任何投資建議。本報告所表達的意見和預測是對出具日的分析判斷,不具有永久有效性。

Link: https://blog.dodoex.io/dodo-research-reveal-the-secrets-of-the-aggregator-problem-analysis-and-model-building-ba0ead85948c

#blockchain #defi #dex #dodo

揭示 DODO 研究聚合器的秘密
Best of Crypto

Best of Crypto

1657460880

1inch Protocol | Fully on-chain DeFi Aggregation Protocol

First ever fully on-chain DEX aggregator protocol by 1inch

Integration

Latest version is always accessible at 1split.eth (beta on 1proto.eth)

Start with checking out solidity interface: IOneSplit.sol

How it works

This smart contract allows to get best price for tokens by aggregating prices from several DEXes.

So far the service works with 2 types of exchages: split and wrap.

List of split exchanges:

let splitExchanges = [
    "Uniswap",
    "Kyber",
    "Bancor",
    "Oasis",
    "Curve Compound",
    "Curve USDT",
    "Curve Y",
    "Curve Binance",
    "Curve Synthetix",
    "Uniswap Compound",
    "Uniswap CHAI",
    "Uniswap Aave",
    "Mooniswap",
    "Uniswap V2",
    "Uniswap V2 ETH",
    "Uniswap V2 DAI",
    "Uniswap V2 USDC",
    "Curve Pax",
    "Curve renBTC",
    "Curve tBTC",
    "Dforce XSwap",
    "Shell",
    "mStable mUSD",
    "Curve sBTC",
    "Balancer 1",
    "Balancer 2",
    "Balancer 3",
    "Kyber 1",
    "Kyber 2",
    "Kyber 3",
    "Kyber 4"
]

List of wrap exchanges:

let wrapExchanges = [
    "CHAI",
    "BDAI",
    "Aave",
    "Fulcrum",
    "Compound",
    "Iearn",
    "Idle",
    "WETH",
    "mUSD"
]

How it works

How to use it

To use this service you have to call methods at OneSplitAudit

How to use it

To swap tokens you have to figure out way from left to right points by one of paths on scheme above.

For example, first of all call method getExpectedReturn (see methods section), it returns distribution array. Each element of this array matches element of splitExchanges (see above) and represents fraction of trading volume.
Then call getExpectedReturnWithGas to take into account gas when splitting. This method returns more profitable distribution array for exchange.
Then call method swap or swapWithReferral (see methods section) with param distribution which was recieved earlier from method getExpectedReturn.

Swap may be customized by flags (see flags section). There are 2 types of swap: direct swap and swap over transitional token.

In case of direct swap each element of distribution array matches element of splitExchanges and represents fraction of trading off token as alerady described above.

In case of swap with transitional token each element of distribution (256 bits) matches 2 swaps: second bytes are equal to swap to transitional token, lowest bytes are equal to swap to the desired token.

Supported DEXes

Methods

If you need Ether instead of any token use address(0) or address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) as param fromToken/destToken

getExpectedReturn

function getExpectedReturn(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 parts,
    uint256 flags
)
    public
    view
    returns(
        uint256 returnAmount,
        uint256[] memory distribution
    )

Calculate expected returning amount of desired token

ParamsTypeDescription
fromTokenIERC20Address of trading off token
destTokenIERC20Address of desired token
amountuint256Amount for fromToken
partsuint256Number of pieces source volume could be splitted (Works like granularity, higly affects gas usage. Should be called offchain, but could be called onchain if user swaps not his own funds, but this is still considered as not safe)
flagsuint256Flags for enabling and disabling some features (default: 0), see flags description

Return values:

ParamsTypeDescription
returnAmountuint256Expected returning amount of desired token
distributionuint256[]Array of weights for volume distribution

Notice: This method is equal to getExpectedReturnWithGas(fromToken, destToken, amount, parts, flags, 0)

Example:

let Web3 = require('web3')

let provider = new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/YOUR_TOKEN')
let web3 = new Web3(provider)

let ABI = [{"inputs":[{"internalType":"contract IOneSplitMulti","name":"impl","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newImpl","type":"address"}],"name":"ImplementationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20","name":"fromToken","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"destToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"fromTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"destTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"minReturn","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"flags","type":"uint256[]"},{"indexed":false,"internalType":"address","name":"referral","type":"address"},{"indexed":false,"internalType":"uint256","name":"feePercent","type":"uint256"}],"name":"Swapped","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":true,"inputs":[],"name":"chi","outputs":[{"internalType":"contract IFreeFromUpTo","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"claimAsset","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"parts","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"}],"name":"getExpectedReturn","outputs":[{"internalType":"uint256","name":"returnAmount","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"parts","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"uint256","name":"destTokenEthPriceTimesGasPrice","type":"uint256"}],"name":"getExpectedReturnWithGas","outputs":[{"internalType":"uint256","name":"returnAmount","type":"uint256"},{"internalType":"uint256","name":"estimateGasAmount","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256[]","name":"parts","type":"uint256[]"},{"internalType":"uint256[]","name":"flags","type":"uint256[]"},{"internalType":"uint256[]","name":"destTokenEthPriceTimesGasPrices","type":"uint256[]"}],"name":"getExpectedReturnWithGasMulti","outputs":[{"internalType":"uint256[]","name":"returnAmounts","type":"uint256[]"},{"internalType":"uint256","name":"estimateGasAmount","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"oneSplitImpl","outputs":[{"internalType":"contract IOneSplitMulti","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IOneSplitMulti","name":"impl","type":"address"}],"name":"setNewImpl","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256","name":"flags","type":"uint256"}],"name":"swap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256[]","name":"flags","type":"uint256[]"}],"name":"swapMulti","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referral","type":"address"},{"internalType":"uint256","name":"feePercent","type":"uint256"}],"name":"swapWithReferral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256[]","name":"flags","type":"uint256[]"},{"internalType":"address","name":"referral","type":"address"},{"internalType":"uint256","name":"feePercent","type":"uint256"}],"name":"swapWithReferralMulti","outputs":[{"internalType":"uint256","name":"returnAmount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
let CONTRACT_ADDRESS = "0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E"

let contract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS)
contract.methods.getExpectedReturn(
    "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
    "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359",
    100,
    10, 
    0
).call().then(data => {
    console.log(`returnAmount: ${data.returnAmount.toString()}`)
    console.log(`distribution: ${JSON.stringify(data.distribution)}`)
}).catch(error => {
    // TO DO: ...
});

getExpectedReturnWithGas

function getExpectedReturnWithGas(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 parts,
    uint256 flags,
    uint256 destTokenEthPriceTimesGasPrice
)
    public
    view
    returns(
        uint256 returnAmount,
        uint256 estimateGasAmount,
        uint256[] memory distribution
    )

Calculate expected returning amount of desired token taking into account how gas protocols affect price

ParamsTypeDescription
fromTokenIERC20Address of trading off token
destTokenIERC20Address of desired token
amountuint256Amount for fromToken
partsuint256Number of pieces source volume could be splitted (Works like granularity, higly affects gas usage. Should be called offchain, but could be called onchain if user swaps not his own funds, but this is still considered as not safe)
flagsuint256Flags for enabling and disabling some features (default: 0), see flags description
destTokenEthPriceTimesGasPriceuint256returnAmount * gas_price, where returnAmount is result of getExpectedReturn(fromToken, destToken, amount, parts, flags)

Return values:

ParamsTypeDescription
returnAmountuint256Expected returning amount of desired token
estimateGasAmountuint256Expected gas amount of exchange
distributionuint256[]Array of weights for volume distribution

Example:

 // TO DO: ...

getExpectedReturnWithGasMulti

function getExpectedReturnWithGasMulti(
    IERC20[] memory tokens,
    uint256 amount,
    uint256[] memory parts,
    uint256[] memory flags,
    uint256[] memory destTokenEthPriceTimesGasPrices
)
    public
    view
    returns(
        uint256[] memory returnAmounts,
        uint256 estimateGasAmount,
        uint256[] memory distribution
    )

Calculate expected returning amount of first tokens element to last tokens element through and the middle tokens with corresponding parts, flags and destTokenEthPriceTimesGasPrices array values of each step.
The length of each array (parts, flags and destTokenEthPriceTimesGasPrices) should be 1 element less than tokens array length. Each element from parts, flags and destTokenEthPriceTimesGasPrices corresponds to 2 neighboring elements from tokens array.

ParamsTypeDescription
tokensIERC20[]The sequence of tokens swaps (tokens[0] -> tokens[1] -> ...)
amountuint256Amount for tokens[0]
partsuint256[]The sequence of number of pieces source volume could be splitted (Works like granularity, higly affects gas usage. Should be called offchain, but could be called onchain if user swaps not his own funds, but this is still considered as not safe)
flagsuint256[]The sequence of flags for enabling and disabling some features (default: 0), see flags description
destTokenEthPriceTimesGasPriceuint256[]The sequence of numbers returnAmount * gas_price, where returnAmount is result of getExpectedReturn(fromToken, destToken, amount, parts, flags)

Return values:

ParamsTypeDescription
returnAmountuint256[]Expected returning amounts of desired tokens in tokens array
estimateGasAmountuint256Expected gas amount of exchange
distributionuint256[]Array of weights for volume distribution

Example:

 // TO DO: ...

swap

function swap(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 minReturn,
    uint256[] memory distribution,
    uint256 flags
) public payable returns(uint256)

Swap amount of fromToken to destToken

ParamsTypeDescription
fromTokenIERC20Address of trading off token
destTokenIERC20Address of desired token
amountuint256Amount for fromToken
minReturnuint256Minimum expected return, else revert transaction
distributionuint256[]Array of weights for volume distribution (returned by getExpectedReturn)
flagsuint256Flags for enabling and disabling some features (default: 0), see flags description

Notice: Make sure the flags param coincides flags param in getExpectedReturn method if you want the same result

Notice: This method is equal to swapWithReferral(fromToken, destToken, amount, minReturn, distribution, flags, address(0), 0)

Return values:

ParamsTypeDescription
returnAmountuint256Recieved amount of desired token

Example:

 // TO DO: ...

swapMulti

function swapMulti(
    IERC20[] memory tokens,
    uint256 amount,
    uint256 minReturn,
    uint256[] memory distribution,
    uint256[] memory flags
) public payable returns(uint256)

Swap amount of first element of tokens to the latest element.
The length of flags array should be 1 element less than tokens array length. Each element from flags array corresponds to 2 neighboring elements from tokens array.

ParamsTypeDescription
tokensIERC20[]Addresses of tokens or address(0) for Ether
amountuint256Amount for tokens[0]
minReturnuint256Minimum expected return, else revert transaction
distributionuint256[]Array of weights for volume distribution (returned by getExpectedReturn)
flagsuint256[]The sequence of flags for enabling and disabling some features (default: 0), see flags description

Notice: Make sure the flags param coincides flags param in getExpectedReturnWithGasMulti method if you want the same result

Notice: This method is equal to swapWithReferralMulti(fromToken, destToken, amount, minReturn, distribution, flags, address(0), 0)

Return values:

ParamsTypeDescription
returnAmountuint256Recieved amount of desired token

Example:

 // TO DO: ...

swapWithReferral

function swapWithReferral(
    IERC20 fromToken,
    IERC20 destToken,
    uint256 amount,
    uint256 minReturn,
    uint256[] memory distribution,
    uint256 flags,
    address referral,
    uint256 feePercent
) public payable returns(uint256)

Swap amount of fromToken to destToken

ParamsTypeDescription
fromTokenIERC20Address of trading off token
destTokenIERC20Address of desired token
amountuint256Amount for fromToken
minReturnuint256Minimum expected return, else revert transaction
distributionuint256[]Array of weights for volume distribution (returned by getExpectedReturn)
flagsuint256Flags for enabling and disabling some features (default: 0), see flags description
referraladdressReferrer's address (exception with flag FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP)
feePercentuint256Fees percents normalized to 1e18, limited to 0.03e18 (3%)

Notice: Make sure the flags param coincides flags param in getExpectedReturn method if you want the same result

Return values:

ParamsTypeDescription
returnAmountuint256Recieved amount of desired token

Example:

 // TO DO: ...

swapWithReferralMulti

function swapWithReferralMulti(
    IERC20[] memory tokens,
    uint256 amount,
    uint256 minReturn,
    uint256[] memory distribution,
    uint256[] memory flags,
    address referral,
    uint256 feePercent
) public payable returns(uint256 returnAmount)

Swap amount of first element of tokens to the latest element.
The length of flags array should be 1 element less than tokens array length. Each element from flags array corresponds to 2 neighboring elements from tokens array.

ParamsTypeDescription
tokensIERC20[]Addresses of tokens or address(0) for Ether
amountuint256Amount for tokens[0]
minReturnuint256Minimum expected return, else revert transaction
distributionuint256[]Array of weights for volume distribution (returned by getExpectedReturn)
flagsuint256[]The sequence of flags for enabling and disabling some features (default: 0), see flags description
referraladdressReferrer's address (exception with flag FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP)
feePercentuint256Fees percents normalized to 1e18, limited to 0.03e18 (3%)

Notice: Make sure the flags param coincides flags param in getExpectedReturnWithGasMulti method if you want the same result

Return values:

ParamsTypeDescription
returnAmountuint256Recieved amount of desired token

Example:

 // TO DO: ...

makeGasDiscount

function makeGasDiscount(
    uint256 gasSpent,
    uint256 returnAmount,
    bytes calldata msgSenderCalldata
)

In case developer wants to manage burning GAS or CHI tokens with developer's own smartcontract one should implement this method and use FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP flag. 1proto.eth will call makeGasDiscount in developer's smartcontract.

ParamsTypeDescription
gasSpentuint256How many gas was spent
returnAmountuint256Recieved amount of desired token
msgSenderCalldatabytesArguments from swap, swapWithReferral or swapWithReferralMulti method

Notice: There is no such method in 1proto.eth.

Flags

Flag types

There are basically 3 types of flags:

Exchange switch
This flags allow 1split.eth to enable or disable using exchange pools for swap. This can be applied for exchanges in genereral, for example: split, wrap, or this can be applied for a specific exchange type, for example: bancor, oasis.
This flags may be used in any combination.
 

Transitional token selector
This flags provide to swap from fromToken to destToken using transitional token.
This flags cann't be used in combination with the same type. 
 

Functional flags
This flags provide some additional features.
This flags may be used in any combination.

Flags description

flags param in 1split.eth methods is sum of flags values, for example:

flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_KYBER + ...

Exchange switch (Split exchanges)

FlagValueDescription
FLAG_DISABLE_UNISWAP0x01Exclude Uniswap exchange from swap
FLAG_ENABLE_KYBER_UNISWAP_RESERVE0x100000000Permit Kyber use Uniswap, by default it is forbidden
FLAG_ENABLE_KYBER_OASIS_RESERVE0x200000000Permit Kyber use Oasis, by default it is forbidden
FLAG_ENABLE_KYBER_BANCOR_RESERVE0x400000000Permit Kyber use Bancor, by default it is forbidden
FLAG_DISABLE_BANCOR0x04Exclude Bancor exchange from swap
FLAG_DISABLE_OASIS0x08Exclude Oasis exchange from swap
FLAG_DISABLE_CURVE_COMPOUND0x1000Exclude CurveCompound exchange from swap
FLAG_DISABLE_CURVE_USDT0x2000Exclude CurveUsdt exchange from swap
FLAG_DISABLE_CURVE_Y0x4000Exclude CurveY exchange from swap
FLAG_DISABLE_CURVE_BINANCE0x8000Exclude CurveBinance exchange from swap
FLAG_DISABLE_CURVE_SYNTHETIX0x40000Exclude CurveSynthetix exchange from swap
FLAG_DISABLE_UNISWAP_COMPOUND0x100000Forbid Uniswap use Compound, by default it is permitted. Works only when one of assets is ETH
FLAG_DISABLE_UNISWAP_CHAI0x200000Forbid Uniswap use Chai, by default it is permitted. Works only when ETH<>DAI
FLAG_DISABLE_UNISWAP_AAVE0x400000Forbid Uniswap use Aave, by default it is permitted. Works only when one of assets is ETH
FLAG_DISABLE_MOONISWAP0x1000000Exclude Mooniswap exchange from swap
FLAG_DISABLE_UNISWAP_V2_ALL0x1E000000Exclude all exchanges with UniswapV2 prefix from swap
FLAG_DISABLE_UNISWAP_V20x2000000Exclude UniswapV2 exchange from swap
FLAG_DISABLE_UNISWAP_V2_ETH0x4000000Exclude UniswapV2ETH exchange from swap
FLAG_DISABLE_UNISWAP_V2_DAI0x8000000Exclude UniswapV2DAI exchange from swap
FLAG_DISABLE_UNISWAP_V2_USDC0x10000000Exclude UniswapV2USDC exchange from swap
FLAG_DISABLE_ALL_SPLIT_SOURCES0x20000000Exclude all split exchages from swap. Inverts split tokens flag values
FLAG_DISABLE_CURVE_PAX0x80000000Exclude CurvePax exchange from swap
FLAG_DISABLE_CURVE_RENBTC0x100000000Exclude CurveRenBtc exchange from swap
FLAG_DISABLE_CURVE_TBTC0x200000000Exclude CurveTBtc exchange from swap
FLAG_DISABLE_DFORCE_SWAP0x4000000000Exclude DforceSwap exchange from swap
FLAG_DISABLE_SHELL0x8000000000Exclude Shellexchangers exchange from swap
FLAG_DISABLE_MSTABLE_MUSD0x20000000000Exclude pool MUSD in mStable exchange from swap
FLAG_DISABLE_CURVE_SBTC0x40000000000Exclude pool SBTC in Curve exchange from swap
FLAG_DISABLE_DMM0x80000000000Exclude DMM exchange from swap
FLAG_DISABLE_UNISWAP_ALL0x100000000000Exclude all pools in Uniswap exchange from swap
FLAG_DISABLE_CURVE_ALL0x200000000000Exclude all pools in Curve exchange from swap
FLAG_DISABLE_BALANCER_ALL0x1000000000000Exclude all pools in Balancer exchange from swap
FLAG_DISABLE_BALANCER_10x2000000000000Exclude the first best pool in Balancer exchange from swap
FLAG_DISABLE_BALANCER_20x4000000000000Exclude the second best pool in Balancer exchange from swap
FLAG_DISABLE_BALANCER_30x8000000000000Exclude the third best pool in Balancer exchange from swap
FLAG_DISABLE_KYBER_ALL0x200000000000000Exclude all pools in Kyber exchange from swap
FLAG_DISABLE_KYBER_10x400000000000000Exclude the first multi-token Kyber reserve (exchange of any token to any is possible) from swap (see KyberReserves)
FLAG_DISABLE_KYBER_20x800000000000000Exclude the second multi-token Kyber reserve (exchange of any token to any is possible) from swap (see KyberReserves)
FLAG_DISABLE_KYBER_30x1000000000000000Exclude the third multi-token Kyber reserve (exchange of any token to any is possible) from swap (see KyberReserves)
FLAG_DISABLE_KYBER_40x2000000000000000Exclude the single-token Kyber reserve (single-token reserves does not intersect and the one that fits is selected) from swap (see KyberReserves)

Example:

let Web3 = require('web3')

let provider = new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/YOUR_TOKEN')
let web3 = new Web3(provider)

let ABI = [{"inputs":[{"internalType":"contract IOneSplitMulti","name":"impl","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newImpl","type":"address"}],"name":"ImplementationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract IERC20","name":"fromToken","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"destToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"fromTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"destTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"minReturn","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"flags","type":"uint256[]"},{"indexed":false,"internalType":"address","name":"referral","type":"address"},{"indexed":false,"internalType":"uint256","name":"feePercent","type":"uint256"}],"name":"Swapped","type":"event"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"constant":true,"inputs":[],"name":"chi","outputs":[{"internalType":"contract IFreeFromUpTo","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"claimAsset","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"parts","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"}],"name":"getExpectedReturn","outputs":[{"internalType":"uint256","name":"returnAmount","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"parts","type":"uint256"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"uint256","name":"destTokenEthPriceTimesGasPrice","type":"uint256"}],"name":"getExpectedReturnWithGas","outputs":[{"internalType":"uint256","name":"returnAmount","type":"uint256"},{"internalType":"uint256","name":"estimateGasAmount","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256[]","name":"parts","type":"uint256[]"},{"internalType":"uint256[]","name":"flags","type":"uint256[]"},{"internalType":"uint256[]","name":"destTokenEthPriceTimesGasPrices","type":"uint256[]"}],"name":"getExpectedReturnWithGasMulti","outputs":[{"internalType":"uint256[]","name":"returnAmounts","type":"uint256[]"},{"internalType":"uint256","name":"estimateGasAmount","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"oneSplitImpl","outputs":[{"internalType":"contract IOneSplitMulti","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IOneSplitMulti","name":"impl","type":"address"}],"name":"setNewImpl","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256","name":"flags","type":"uint256"}],"name":"swap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256[]","name":"flags","type":"uint256[]"}],"name":"swapMulti","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20","name":"fromToken","type":"address"},{"internalType":"contract IERC20","name":"destToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256","name":"flags","type":"uint256"},{"internalType":"address","name":"referral","type":"address"},{"internalType":"uint256","name":"feePercent","type":"uint256"}],"name":"swapWithReferral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"contract IERC20[]","name":"tokens","type":"address[]"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minReturn","type":"uint256"},{"internalType":"uint256[]","name":"distribution","type":"uint256[]"},{"internalType":"uint256[]","name":"flags","type":"uint256[]"},{"internalType":"address","name":"referral","type":"address"},{"internalType":"uint256","name":"feePercent","type":"uint256"}],"name":"swapWithReferralMulti","outputs":[{"internalType":"uint256","name":"returnAmount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
let CONTRACT_ADDRESS = "0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E"

let splitExchanges = [
    "Uniswap", "Kyber", "Bancor", "Oasis", "CurveCompound", "CurveUsdt", "CurveY", "CurveBinance", "CurveSynthetix", "UniswapCompound", "UniswapChai", "UniswapAave", "Mooniswap", "UniswapV2", "UniswapV2ETH", "UniswapV2DAI", "UniswapV2USDC", "CurvePax", "CurveRenBtc", "CurveTBtc", "DforceSwap", "Shellexchangers"
]

let parts = 10

let contract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS)
contract.methods.getExpectedReturn(
    "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
    "0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359",
    100,
    parts, 
    0x04
).call().then(data => {

    data.distribution.forEach(function(value, index) {
        console.log(`${splitExchanges[index]}: ${value*100/parts}%`)
    })
}).catch(error => {
    // TO DO: ...
});

Exchange switch (Wrap exchanges)

FlagValueDescription
FLAG_DISABLE_COMPOUND0x10Exclude Compound exchange from swap
FLAG_DISABLE_FULCRUM0x20Exclude Fulcrum exchange from swap
FLAG_DISABLE_CHAI0x40Exclude Chai exchange from swap
FLAG_DISABLE_AAVE0x80Exclude Aave exchange from swap
FLAG_DISABLE_SMART_TOKEN0x100Exclude SmartToken exchange from swap
FLAG_DISABLE_BDAI0x400Exclude Bdai exchange from swap
FLAG_DISABLE_IEARN0x800Exclude Iearn exchange from swap
FLAG_DISABLE_WETH0x80000Exclude Weth exchange from swap
FLAG_DISABLE_IDLE0x800000Exclude Idle exchange from swap
FLAG_DISABLE_ALL_WRAP_SOURCES0x40000000Exclude all wrap exchages from swap. Inverts wrap tokens flag values

Transitional token selector

FlagValueDescription
FLAG_DISABLE_UNISWAP_COMPOUND0x100000Exclude Uniswap pools with cTokens
FLAG_DISABLE_UNISWAP_CHAI0x200000Exclude Uniswap pools with Chai
FLAG_DISABLE_UNISWAP_AAVE0x400000Exclude Uniswap pools with aTokens

Functional flags

FlagValueDescription
FLAG_ENABLE_CHI_BURN0x10000000000Burns CHI token to save gas. Make sure to approve CHI token to 1split.eth smart contract
FLAG_ENABLE_CHI_BURN_BY_ORIGIN0x4000000000000000This flag extends the functionality of FLAG_ENABLE_CHI_BURN flag. Burns CHI token from address which sign swap transaction instead of address which call swap method
FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP0x80000000000000Turning on this flag means that parameter referral (methods swapWithReferral and swapWithReferralMulti) matches the address of the user smartcontract which has makeGasDiscount method. So this method can burn GAS token, CHI token by itself or it can add other functionality.

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/1inchProtocol
License: MIT license

#1inch #blockchain #dex #solidity

1inch Protocol | Fully on-chain DeFi Aggregation Protocol
Best of Crypto

Best of Crypto

1657453380

Gnosis 1inch DApp Written in Typescript

GnosisApp

This project was generated with Angular CLI version 9.0.7.

Development server

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Code scaffolding

Run ng generate component component-name to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module.

Build

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

Running unit tests

Run ng test to execute the unit tests via Karma.

Running end-to-end tests

Run ng e2e to execute the end-to-end tests via Protractor.

Further help

To get more help on the Angular CLI use ng help or go check out the Angular CLI README.

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/gnosis.1inch.exchange
License: MIT license

#1inch #blockchain #dex #typescript

Gnosis 1inch DApp Written in Typescript
Best of Crypto

Best of Crypto

1657446060

OneHop | CDP Migration Aggregator for 1inch Written in Solidity

OneHop

This project was generated with Angular CLI version 9.0.3.

Development server

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Code scaffolding

Run ng generate component component-name to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module.

Build

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

Running unit tests

Run ng test to execute the unit tests via Karma.

Running end-to-end tests

Run ng e2e to execute the end-to-end tests via Protractor.

Further help

To get more help on the Angular CLI use ng help or go check out the Angular CLI README.

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/1hop
License: MIT license

#1inch #blockchain #dex #typescript #solidity

OneHop | CDP Migration Aggregator for 1inch Written in Solidity
Best of Crypto

Best of Crypto

1657438680

1inch Liquidity Protocol | AMM with A Beautiful Mind

liquidity protocol

AMM with a beautiful mind

Mainnet Contract Addresses

Mooniswap Factory Referral Fee Receiver

Swap

/**
* @param src address of the source token to exchange
* @param dst token address that will received
* @param amount amount to exchange
* @param minReturn minimal amount of the dst token that will receive (if result < minReturn then transaction fails)
* @param referral 1/20 from LP fees will be minted to referral wallet address (in liquidity token) (in case of address(0) no mints) 
* @return result received amount
*/
function swap(address src, address dst, uint256 amount, uint256 minReturn, address referral) external payable returns(uint256 result);

Deposit

/**
* @dev provide liquidity to the pool and earn on trading fees
* @param amounts [amount0, amount1] for liquidity provision (each amount sorted by token0 and token1) 
* @param minAmounts minimal amounts that will be charged from sender address to liquidity pool (each amount sorted by token0 and token1) 
* @return fairSupply received liquidity token amount
*/
function deposit(uint256[2] calldata amounts, uint256[2] calldata minAmounts) external payable returns(uint256 fairSupply);

Withdraw

/**
* @dev withdraw liquidity from the pool
* @param amount amount to burn in exchange for underlying tokens
* @param minReturns minimal amounts that will be transferred to sender address in underlying tokens  (each amount sorted by token0 and token1) 
*/
function withdraw(uint256 amount, uint256[] memory minReturns) external;

Create new pool

/**
* @dev tokens will be sorted and stored according to token0 < token1
* @param tokenA 
* @param tokenB 
* @return pool created pool address
*/
function deploy(address tokenA, address tokenB) public returns(address pool);

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/liquidity-protocol
License: MIT license

#1inch #blockchain #dex #javascript #solidity

1inch Liquidity Protocol | AMM with A Beautiful Mind
Best of Crypto

Best of Crypto

1657431300

1inch Farming | Give Rewards to Users Holding Specific Tokens

Farming contracts

Overview

About

1inch farming contract offers protocols to give rewards to users holding specific tokens. The repository offers two ways to get rewards

  • A user can hold ERC20Farmable token on its account without staking or depositing it to any contract. User should join a farm and hold tokens on its account to get rewards.
  • A user can stake/deposit specific tokens to FarmingPool smart contract. It is less convenient way and is only used for backward compatibility for those smart contracts that have been deployed and there are no way to change it.

Math

Farming reward is distributed uniformly across the whole farming period and depends on number of participants. Actually, the reward is a piecewise linear function which is set by formula

where $R_p$ - total farming reward for a farming participant

R - total reward locked for farming

t - time period duration (between farm’s joins and/or exits)

T - total farming duration

V - participant’s farmable tokens share

$V_{total}$ - total number of farmable tokens joined the farm

Example

Given $72 000 reward is locked for 5 weeks in a farm and there are three farmers

  • Farmer 1 joins at week 1 with 100 farmable tokens on his balance but exits at week 2 and rejoins at week 3. At week 4 he increases his balance up to 200 farmable tokens
  • Farmer 2 joins at week 2 with 300 farmable tokens and exits after week 3
  • Farmer 3 joins at week 2 with 300 farmable tokens but decreases his farmable token balance after week 3 down to 100 and exits at week 4
72000$ rewardWeek 1Week 2Week 3Week 4
Farmer 1100 100200
Farmer 2 300300 
Farmer 3 300100 

The resulting reward distribution would be the following

 Week 1Week 2Week 3Week 4
Farmer 118000 360018000
Farmer 2 900010800 
Farmer 3 90003600 

More examples are here @1inch/farming/TESTS.md#deposit

ERC20Farmable and Farm usage

Concept

To start new farming owner should deploy (or use already deployed) farming for a pair of tokens and initialize it.

  1. Deploy farm and set farmable and reward token
  2. Start farming
    • Set distributor
    • From distributor account send reward amount and set farming period

When farming is started users holding farmable tokens may join the farm to accumulate rewards. After joining a farm, a user starts to get farm rewards for the whole amount of farmable tokens he owns. When a user’s balance changes the reward share is changed automatically.

If a user wants to stop participating in farming he should exit the farm with. Rewards for previous farming periods may be claimed any time with claim function regardless if a user is still farming or has already exited the farm.

ERC20Farmable and Farm concept

A user may join several farms which provide rewards for the same token.

To prevent new farmings from starting an owner may set a distributor address to zero.

Installation

$ npm install @1inch/farming

or

$ yarn add @1inch/farming

Usage

Once installed, you can use the contracts in the library by importing them. Just use ERC20Farmable instead of ERC20 to derive from

pragma solidity ^0.8.0;

import "@1inch/farming/contracts/ERC20Farmable.sol";

contract AMMPoolToken is ERC20Farmable {
    constructor() ERC20("AMMPoolToken", "AMM") {
    }
}

Optimizations

Storage access:

  • 1 storage slot for farming params, updated only on farming restarting:
uint40 public finished;
uint32 public duration;
uint184 public reward;
  • 1 storage slot for farming state, updated only on changing number of farming tokens:
uint40 public checkpoint;
uint216 public farmedPerTokenStored;
mapping(address => int256) public corrections;

FarmingPool usage

The FarmingPool usage is almost the same but a farmer has to deposit farmable tokens to farm account and withdraw it after the farming is completed.

Farming pool concept

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/farming
License: MIT license

#1inch #blockchain #dex

1inch Farming | Give Rewards to Users Holding Specific Tokens
Best of Crypto

Best of Crypto

1657431000

1inch Embedded Swap Widget

Library for integrating 1inch swap widget.

Installation

Node

npm install @1inch/embedded-widget

Yarn

yarn add @1inch/embedded-widget

Usage

import {setup1inchWidget} from '@1inch/embedded-widget';

const iframeJsonRpcManager = setup1inchWidget({
    chainId: 137,
    sourceTokenSymbol: '1INCH',
    destinationTokenSymbol: 'DAI',
    hostElement: host,
    provider: window.ethereum,
    theme: 'light',
    sourceTokenAmount: '15'
});

iframeJsonRpcManager.destroy() // Will remove iframe from the page and stop postMessage listening

iframeJsonRpcManager.onIframeLoad(() => { // Will call a callback when 1inch swap widget is fully loaded
    console.log('1inch swap widget is loaded')
})

Configuration

OptionTypeExampleDescription
chainIdNumber11inch supports several chains, see the actual list on 1inch.io
sourceTokenSymbolStringUSDTSymbol of source token. See the full list of supported tokens on offical 1inch docs
destinationTokenSymbolStringDAISymbol of destination token. See the full list of supported tokens on offical 1inch docs
sourceTokenAmountString200Optional. Using this option, you can pre-set the number of source tokens for the swap
hostElementHTMLElementdocument.bodyThe DOM element where the widget will be placed. You can change the witget size by changing size of the hostElement
providerEthereumProviderwindow.ethereumEIP-1193 provider for json-rpc requests to the wallet
themelight / darklightOptional. Theme of 1inch widget UI. If not set, the widget will use the system theme

Demo

See the live example here and the source code here.

Statements

Test coverage

StatementsBranchesFunctionsLines
StatementsBranchesFunctionsLines

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/embedded-widget
License: MIT license

#1inch #blockchain #dex

1inch Embedded Swap Widget
Best of Crypto

Best of Crypto

1657423620

Spot Price Aggregator for 1inch Network

Spot Price Aggregator

The 1inch spot price aggregator is a set of smart contracts that extract price data for tokens traded on DEXes from the blockchain. To avoid price manipulations within a transaction, the spot price aggregator should ONLY be used off-chain. DO NOT use it on-chain. For off-chain usage see Examples section below.

Wrappers

To handle wrapped tokens, such as wETH, cDAI, aDAI etc., the 1inch spot price aggregator uses custom wrapper smart contracts that wrap/unwrap tokens at the current wrapping exchange rate.

Connectors

If no direct liquidity pair exists between two tokens, the spot price aggregator calculates rates for those coins using another token that has pairs with both of them – a connector token.

Supported Deployments

Ethereum Mainnet

Oracle 0x07D91f5fb9Bf7798734C3f606dB065549F6893bb

Supported DEXes

  • Mooniswap
  • 1inch Liquidity Protocol V1.1
  • Uniswap V1
  • Uniswap V2
  • Sushiswap
  • Equalizer.fi
  • Uniswap V3
  • Synthetix
  • Chainlink
  • Shibaswap

Supported wrappers

  • Aave V1
  • Aave V2
  • Compound
  • Fulcrum V1
  • Fulcrum V2
  • WETH
  • Cream

Supported connectors

  • ETH
  • WETH
  • DAI
  • USDC
  • USDT
  • WBTC
  • 1INCH

Binance Smart Chain

Oracle 0xfbD61B037C325b959c0F6A7e69D8f37770C2c550

Supported DEXes

  • 1inch Liquidity Protocol V1.1
  • Pancakeswap
  • Streetswap
  • Bakeryswap
  • Julswap
  • Demaxswap

Supported wrappers

  • Venus
  • WBNB

Supported connectors

  • BNB
  • WBNB
  • ETH
  • DAI
  • USDC
  • USDT
  • BUSD

Polygon

Oracle 0x7F069df72b7A39bCE9806e3AfaF579E54D8CF2b9

Supported DEXes

  • QuickSwap
  • ComethSwap
  • SushiSwap
  • Dfyn

Supported wrappers

  • AAVE
  • WMATIC

Supported connectors

  • MATIC
  • WMATIC

Kovan

Oracle 0x29BC86Ad68bB3BD3d54841a8522e0020C1882C22

Supported DEXes

  • 1inch Liquidity Protocol V1.1
  • Uniswap V2
  • Uniswap V1

Supported wrappers

  • Venus
  • WETH

Supported connectors

  • ETH
  • WETH

Optimism

Oracle 0x11DEE30E710B8d4a8630392781Cc3c0046365d4c

Supported DEXes

  • Uniswap V3
  • Synthetix

Arbitrum

Oracle 0x735247fb0a604c0adC6cab38ACE16D0DbA31295F

Supported DEXes

  • Uniswap V3
  • Sushiswap
  • Swapr

Avax

Oracle 0xBd0c7AaF0bF082712EbE919a9dD94b2d978f79A9

Supported DEXes

  • Trader Joe
  • Pangolin Exchange

xDai

Oracle 0x142DB045195CEcaBe415161e1dF1CF0337A4d02E

Supported DEXes

  • Honeyswap
  • Levinswap
  • Swapr
  • Sushiswap

Fantom

Oracle 0xE8E598A1041b6fDB13999D275a202847D9b654ca

Supported DEXes

  • SpookySwap
  • Solidex
  • SpiritSwap
  • Sushiswap

Aurora

Oracle 0xE4E0552452e5cC1306A2bF5B2Fd9b1eA19418795

Supported DEXes

  • Trisolaris
  • WannaSwap
  • NearPAD
  • AuroraSwap

Examples

Single token-to-ETH price usage

Multiple token-to-ETH prices usage

Download Details:
Author: 1inch
Source Code: https://github.com/1inch/spot-price-aggregator
License: MIT license

#1inch #blockchain #dex #javascript #solidity

Spot Price Aggregator for 1inch Network