[Rejected Design Concept] Pengv2j : Distributed Exchange

Elix Exo
22 min readMar 5, 2023

--

A proposed application for the Hybrid-Line on EVM/SCVM blockchains.

Disclaimer: This document was modified on 11/May/2023, specifically the section “Peer Trading”, original document can be found here.

Introduction

In considering a new design, market analysis is required, that is; knowing what’s on the market, what are the issues with those products/platforms and how they can be improved upon while negating new problems that may arise. Alternatively, you can skip to the heading “Pengv2j : Distributed Exchange” if you’re only interested in the design specs.

In the following post I will describe a possible Distributed Exchange design. Firstly; clarifying terms; a decentralized exchange or “DEX” can be used to denote a wide range of things, “decentralized” means the axises of control are spread out, there is no single group/person who controls/influences the system, rather you have a network of authorities, which ideally should reduce mismanagement [1].

This is different from a distributed system, in a distributed system there is no authority above the protocol which all participants must follow in perpetuity [2]. What makes DEXs decentralized is (2) fold; first is the front-end, and second is the smart contract owner keys. A DEX’s front-end is often but not always hosted in a manner that is under the control of the deployer, meaning they can make changes to it [3]. The front-end is not entirely necessary but it is the primary way most users would interact with the smart contract, the smart contract itself is (for all intents and purposes) immutable and on a distributed network (the smart contract virtual machine), however, the keys to contracts need to be owned by the exchange or a “DAO”, the range of actions they can perform is intentionally limited to prevent misuse, so things like liquidity are not under their direct control, [4].

However, this highlights why I needed to make the distinction between “distributed” and “decentralized”, to vote for future proposals or expenditures of the DEX token or make certain calls to the contract to modify how it functions; you need the DAO’s token to do so, more tokens = more voting power, this is why the vote is always swayed by large players [5]. A scenario that compounds this is when the DAO is exploited through a malicious entity using a majority stake or just whales being whales [6].

What’s on the Market

DEXs in relation to smart contract virtual machines and token swaps, are a pairing of smart contract + front-end (either distributed, self-hosted or cloud hosted), which facilitate the exchange of smart contract (SC) tokens under certain guidelines of price, fees and liquidity [7].

  • Price

Prices on DEXs are handled through a simple mechanism called “constant-market” algorithm, this means all tokens are paired with either the base layer token or another SC token. The value of the new token is derived from the amount in the pair; if you have 1AVAX paired to 1000TOKEN then the value of that token is 0.001, the DEX will often inform you of the dollar price of either token [8]. This is the same setup used for stablecoins in most cases albeit with lots of adding/subtracting of liquidity to maintain a particular dollar price [9](https://medium.com/bollinger-investment-group/constant-function-market-makers-defis-zero-to-one-innovation-968f77022159) [10]().

Another way to arrive at prices is through single sided liquidity, this means the two tokens are not paired, rather they are held separately by the smart contract, what the contract then does is exchange one token for another under predefined terms, such as; 1AVAX for 1TOKEN always. Or using an external price feed to determine what the dollar price is, then using that to determine how much AVAX to exchange for the token, this works best for stablecoins or price pegged tokens such as derivatives and synthetics [10.1], [11].

* Fees

Fees are what the exchange charges on top of each swap, meaning a small amount is deducted and held by the smart contract, what it does with the profit from fees differs between exchanges, mostly they distribute the rewards to investors of the token through “staking” [11.1].

  • Liquidity

Liquidity is a pool or pools of funds denominated in various tokens which allow users to exchange the tokens pooled, liquidity can be thought of as the lifeblood of a DEX, getting that liquidity is not easy, often DEXs employ “staking” as a means of generating liquidity, which means users create liquidity pairs and “stake” them, allowing the pair to be used on the exchange, and for their contribution they get a reward in minted tokens. The other route is generating funds through issued tokens, the funds raised are used for liquidity, the tokens themselves could be locked (i.e. preventing the investor from selling until a particular point in time) while granting the investor rewards either in new minted tokens over time or in profits from transactional fees [12].

Other DEXs incorporate the issuance of loans or convoluted mint/burn mechanics in order to raise liquidity [12.1]. Minting/Burning is necessary to control inflation, burning on some DEXs occurs per trade, on other DEXs there are allocated periods where users or the exchange itself will burn the DEX’s tokens, users can burn their DEX tokens for NFTs or other “prizes” [13] [14].

Burning alleviates selling pressure as it reduces the amount of the token in circulation, burning is only meaningful if the tokens burnt are deducted from a larger number of users/addresses which have the potential to otherwise sell [15].

So, let’s run by that again; DEX issues tokens to raise liquidity, issues more tokens as rewards, then burns a portion of the supply to control inflation.

Problems with Existing DEXs

The problems with DEXs are (3) fold;

* Faulty contract code

* Liquidity

* Staking

Faulty contract code

This point is not meant to say that there is something particularly wrong with the programmers of these projects, rather it is an underlying issue with smart contracts which for the most part allow them to be exploited rather easily. Many of these issues have been fixed through trial and error, knowing what works and what doesn’t, here is a list of some of the common ways smart contracts get exploited;

  • Reentrancy attacks
  • Owner Keys
  • Approvals

Reentrancy Attacks

This is the oldest and easiest form of attack to counter, it works by using a “callback” to essentially trick the contract into sending the same funds twice, that is; withdrawing funds to an external contract, then using the “Callback” to quickly reiterate that same order before the DEX contract has time to update the balance, this allows the hacker to spend the same balance twice [15].

Alternatively the user can use “Cross-function”, meaning to use two similar functions with the “callback”, so if they “transfer”, they can then quickly “withdraw”, this type of hack befell the original Ethereum DAO and also Uniswap v1 [16][17].

Reentrancy Attacks are easily countered by specifying that the contract needs to check/update balances before responding to a subsequent call [18].

Owner Keys

Owner Keys are by far the silliest way a contract can be exploited, but it is a way, this means that the contract is un-renounced and the hacker gains access to the deployer’s private key either through social engineering, phishing, physical access or virus on a vulnerable system etc. [19] [20].

Most DEXs will use a DAO but this is not always the case, in one scenario; the deployer for Rubic, a cross-chain swap protocol, was hacked and the owner keys were stolen, the keys were then used to drain a portion of the cross-chain liquidity for the protocol [21].

But bridges are much more complex and often centralized entities which come with their own problems, you can read more here. But with DEXs it is also possible for the owner keys to be abused if there are functions in the contract that allow things like withdrawing liquidity; as seen with the Arbiswap rug-pull wherein they used the keys to withdraw most of the liquidity on the platform [22].

Or if the contract has an owner that can upgrade it, thereby adding functions, this is how Bancor was hacked in 2022, by gaining access to the owner private key of some of their contracts which were upgradable [23].

Approvals

Whenever you interact with a contract, especially a DEX, you need to grant approval for said contract to move funds in your wallet, this is usually safe, except when you approve a token via the DEX, which grants a third-party contract access to any token you have previously approved, in this way the DEX acts as an unwitting gateway to the approval hack because any other contract approved through it can spend an infinite amount of the approved tokens. The DEX has no intention of robbing you, but the same can’t be said of every random doggy crap token you happen to pick up [24].

Another style of approval hack is using a “delegate-call” or a proxy or any other faulty functions that allow users or other contracts to issue instructions to the DEX contract, the hacker would then use this to manipulate the contract in any way allowed by the code. Note that this can also be done with the owner keys [25] [26].

This is the same type of hack used to exploit multi-chain Anyswap, where the hacker approved his contract via a proxy and bad R signature scheme, the hacker was able to approve his contract for every user of the cross-chain protocol, thereby stealing every token that had previously been approved. [27]

Other forms of attacks can be found here. Most of the issues with contracts can be negated by just not using them, apps built for systems like Bitcoin have suffered far fewer hacks because they aren’t built on a porous EVM with an extremely limited language like Solidity [27.1]. Apps built on non-EVM blockchains can still allow you to do basic things like stake, tip, create NFTs etc, a centralized exchange is arguably a type of Bitcoin app and is only susceptible to attacks involving intentionally bad design or careless management of private keys [27.2]. Bitcoin has had NFTs much longer than systems like Ethereum have existed, these existed in the form of OP_Return, these messages were sorted and managed through simple off-chain apps [28].

But of course, as you’ve already guessed there was a need for an immutable way to create apps that would ideally be safer and cheaper than hosting the app yourself.

liquidity

As mentioned, getting liquidity is hard, managing liquidity is supposed to be a straight-forward process, it’s supposed to be non-custodial, meaning the exchange has no access to it, however, the problem I want to highlight is not of how secure the liquidity is; but of how much liquidity there is for trades, that is; crossing that hurdle of acquiring liquidity in the first place [29].

Moreover, liquidity created on one DEX cannot be used on another DEX, this is a limit which makes it even harder to create a new DEX [30]. This means liquidity providers are tied into a particular DEX where they are incentivized to lock their funds for periods of time, meaning overtime a handful of DEXs become more and more profitable whereas newer ones struggle to compete. Liquidity needs to be locked to increase expectancy, meaning the DEX has an idea of how much liquidity it can maintain for a period of time.

As a result of this fragmentation, if a token is deployed to more than one DEX it will have two different prices which can then be arbitraged or exploited [31].

Another issue with liquidity is that it fundamentally differs from the way people normally think of tokens, take chuck-e-cheese as an example, chuck-e-cheese does not need liquidity for its tokens, it enforces specific prices and what can be bought using those tokens [32] [33], Now you may say “but Elix, chuck-e-cheese is kid’s play, we’re dealing with millions of dollars here”.

Except we’re dealing with companies that don’t necessarily have the liquidity and are accustomed to token systems where execution of sales is performed by edict, i.e., 1CHUCK token for $0.05, no negotiations. This limitation makes Fungible tokens undesirable since the only way to trade them is through liquidity pools. Which is why NFTs have been so popular the past (3) years, because they fit into the chuck-e-cheese structure of tokens which a lot of retail would prefer [34]. The problem with NFTs arise with price gouging, chuck-e-cheese can enforce the price, that’s something that can’t be done with NFTs and in many instances has led to people trying to buy up NFTs initially meant to be worth a few dollars but reselling them for thousands, making it impossible for people who actually wanted to use the token for the intended purpose [35] [36] [37].

If you wanted to create a decentralized game today, you’d have to raise millions in liquidity, if you wanted the price fixed, you’d have to create an elaborate price control mechanism which requires more liquidity or development costs.

Staking

Staking as previously explained is the primary means through which DEXs raise liquidity, but staking… is a double edged sword, people stake and stake and stake, nobody knows how much the token will be worth when you withdraw. And this is the problem, when you stake you are being rewarded in a token that is continuously inflating with only small opportunities to deflate the supply, even a burn tax is minuscule compared to how much gets minted, if you have a burn fee of 0.05% but your stakers are earning 2% on their stake, your token is inflationary by 1.95%, and you can’t increase the fees because then users would go elsewhere, but this is assuming the stake is only 2%, some DEXs at points in time have had APY on their tokens as high as 300% percent [38].

This is known as “degeneracy”, although it is important to note; anyone can create a staking system for their token using a DEX or using their own contracts.

The only way for anyone to make profit from staking is if the token can attract more buyers at a rate that is greater than the amount lost to inflation. Some protocols had taken it upon themselves to test the absolute limit of inflation, with Jade protocol starting out with 394,000,000% APY, that’s Three Hundred and ninety four Million percent, [39]. The rate goes down as more people stake of course, and the coin itself is rebase; meaning your balance is continuously adjusted by the smart contract to maintain the initial price you bought at, this and more was meant to create a sounder investment… but 394 million percent is still 394 million percent.

This brings us to the next issue; rate uncertainty, you’re never sure how much you’ll get over time from staking a new token, but you can be sure it will go down as it becomes more popular and more people begin to stake, which is how Jade Protocol went from 394 million percent to 8 Million to 1 million and so on [40], but the thing is; it doesn’t matter if the tokens you’re holding maintain a stable price, if the amount minted far outweighs the liquidity it won’t be possible to cash out in full or at all, so it becomes a game of musical chairs.

Pengv2j : Distributed Exchange

After examining everything on the market and what I believe are the limitations of the systems currently in use, I present the distributed exchange, which acts as a simple liquidity aggregator; it connects “traders” with “users” while providing additional rewards to keep the system lucrative.

So, to clear up a few things; this is a distributed network operating off-chain, which uses (5) things to exchange of a token;

  • Peer Trading
  • Trade Rewards
  • Burning
  • Smart Contract Escrows
  • Hybrid Network

Peer Trading

Peer trading means you have network peers who accept offers from users to exchange a token at a rate agreed upon by the network, and in exchange they receive a network-side token which they can then trade for AVAX or burn for other incentives.

These peers can automate their setup using “robots” to accept offers and instantly process them. If a user wishes to trade AVAX for TOKEN, they initiate an offer, if TOKEN has a liquidity pair on a DEX then the network will use that price to calculate the exchange, if the token does not then the network will use a novel “Price” field in the token contract, which is a fixed amount of AVAX which the token can be traded for, if the token has none of these it is untradable.

Once an offer is accepted for AVAX to TOKEN, the user sends their AVAX to an Escrow peer, Escrows in this sense are peers within the network who stake a certain amount of the Network’s token (This token is not blockchain based), and as a result are allowed to receive the same value divided by 2. Escrow peers have their nodes fully automated, once a trade is initiated it is stored in the pending list and once the counterparty completes the trade the correct addresses are settled.

So for example User-A sends 1000TOKEN to an Escrow peer, the pending list is updated and the counterparty needs to send 1AVAX, once the counterparty sends this AVAX the escrow peer will then settle them, using the AVAX to pay fees, so all trades must be at an amount high enough to cover fees.

If an Escrow peer’s operator uses their private key to move funds within the address at any point in time, then their stake is deducted and their address is blacklisted, the stake is credited to the affected user on Peng-v3j and a notification sent to them if they’re still interacting with the app at the time. This token can be exchanged for AVAX or any other blockchain token.
These safety measures limit how much can be transacted based on how liquidity traders have and how much is staked by various escrows. But as time goes on and more traders with more liquidity join the network, then larger trades will be possible.

Trade Rewards

Each time a trade occurs the trader receives tokens on the network side, not blockchain based tokens. The amount received is equal to the transaction fees used for both parties involved multiplied by a factor of (5). In order to limit spam, a trader cannot perform trades greater in volume than the average performed by the total number of traders, to become a trader one must run a node, meaning to manipulate the average one would need to run nodes equal to >51% of all nodes present and perform trades on all those nodes, because nodes are lightweight, this number could easily be in the thousands, if 1000 nodes are performing $500 worth of trades within the last day, then the exploiter would need to perform $600 trades on 501 nodes, funds don’t have to be spread out as they can reuse the liquidity.

When a trader needs to cash out their reward token they initiate a trade with other traders, this works different from swapping SC tokens, the seller sends AVAX to the specified address, and immediately after the network deducts the trade amount of reward tokens from the buyer’s network address to the seller’s address.

Burning

Obviously, this system would lead to inflation, though the price of the reward token is enforced directly by the system, if there is a huge amount of tokens being dumped on the market this will deteriorate trust and lead to some traders either leaving or creating dark-pools. To prevent this there will be a simple burn mechanism which is triggered by “market price” changes.

Market price is calculated by how many tokens are in circulation vs how much AVAX is held by traders, using constant-market algorithm the system will determine if the price peg is possible in an open market. If the “market price” is below -10% of the fixed price, then holders of Reward Token (RT) will be able to burn their tokens (this permanently deletes the amount) and in exchange receive an irreplicable digital asset (IDA) called “Reward Trophy”, this trophy can be exchanged for AVAX through other traders at a fixed price of the amount burnt + 5%, a minimum of 1AVAX is required. Once swapped, the new holder can exchange the token when the market price is above 10% of the fixed price, thereby minting more RT and burning the trophy, the amount minted is +5% of the previous value.

This means there is a constant incentive to burn the tokens. Though dark-pools would also achieve the same effect, since traders would be trying to arbitrage any parallel markets that may form, thereby leading to a stabilization of the price. But this burning system would be more effective and predictable.

Smart Contract Escrows

The smart contracts used for escrows only have (2) functions; “Pay Settlements” and “Reimburse”. The URI for “Pay Settlements” is compiled with the contract and cannot be updated, this is the same with “Reimburse”. “Reimburse” simply means that any trade not concluded in 30 seconds can have the amount that was deposited by one party returned to them. Both of these functions have to be called by network nodes, there is no withdrawal function or approval function or proxy or reentrancy risk or ownership. Anyone can call these functions at cost to themselves, the data which the contract uses for each computation is handled by the immutable ends of the network, meaning there’s no chance of it being altered or poisoned.

Hybrid Network

The Hybrid-Line-Bus or Hybrid-Line-Network is a layered system of p2p and web-based line bus. The p2p stack is immutable, similar to an EVM, states must be agreed upon for network participants to join/sync, this means any change to the underlying software would result in ejection from the network, these states are identified by hash, each “state” creates a different hash.

Many decentralized applications use this same setup to create immutable front-ends, in a similar way this is the routing/arbitration system of the second layer/stack. The second layer is a collection of nodes which must connect linearly, that means one parent to one child, at the top is the root node, the root is a de-facto “ruler” of the network, all user client requests are directed through the immutable p2p network to the latest non-delinquent root, the root then routes to a child node along a known “step” or incremental number.

Each transaction or operation requires consensus and confirmation, this means the serving node must request approval from the root, and the root must then request confirmation from the user client, if both the child request and user request match up then there is confirmation and the transaction passes. However; if the child node presents a transaction that is valid and the root rejects it, then the child declares the root delinquent, this declaration causes all other nodes and the p2p network to investigate the transaction and choose sides. If the p2p network sides with the root then the child is kicked from the network, however if the child is correct then the root is abandoned and the latest node who sided with the child becomes the new root.

This is important; if the network is star-shaped, then each contention would lead to dissolution and re-discovery, however, being line shaped, each contention can safely cut off the delinquent root or child and continue functioning as normal. But each contention halts the network either way, meaning no new user client requests are routed, but this may only last seconds in practice.

The network needs to have some form of authority which is why it is linear, a preceding node can kick a subsequent node since it is a child of theirs, this allows weeding out of bad actors.

Each transaction is further investigated through PKI, this means a message signed with the private key can be verified with the public key, this is definitive proof that hj4k…993e wants to send 6,000,000 harrypotterobamasonic10inu tokens to 339d…ka2p, but maybe he only has 400,000, well the system will just reject it as invalid.

All clients are lightweight by only storing certain operations for the period in time they are needed, for tokens; all accounts are stored as separate folders, each transaction is an individual json file with identifying variables, nonce and PKI proof. Only (2) prior transactions are needed to validate a new transaction, a transaction is not valid until it is agreed upon by all nodes and more so the p2p stack.

Each internal transaction stores the prior balance and new balance which is needed to update it, each transfer_to has an accompanying transfer_from, only the transfer_to needs to be proven, nonce is updated after every transaction, the proof is the PKI output and original code (random string of alphanumeric symbols). The “registry” is the public key.

The purpose of the second stack is to enable scalability, nodes process transactions as fast as their hardware and internet connection will allow, having a grace period of 10 seconds, meaning if you had a slow root node and much faster child nodes, the root would eventually be declared delinquent for being too slow, slow speed primarily affects the root and not the child nodes, so a slow node can reinstall their software to rejoin the network under a much faster new root node, this allows only the fastest root for routing but all child nodes can be at whatever speed so long as they can update their database within 10 seconds of a new transaction.

As more nodes join, more requests can be handled simultaneously, all user requests are routed to various nodes in the network, thereby distributing the work.

More information on the network can be found here.

Advantages of the Distributed Exchange

Now that we know the “how” of the system, let’s discuss the “why” of the system.

1. Saves Gas

Each time you perform an EVM computation you pay a fee, currently the fee for functions like “swap” is anything between is $0.10 and $0.15 [Citation Unavailable].

But with Peng, each transaction is just a set of transfers, which will cost between $0.04 and $0.08, this is assuming the cost per transaction is between $0.01 and $0.02, (4) transfers are performed with each swap.

2. No need for raising liquidity

Tokens can be created in such a way that their price is enforced directly into the contract and goes up or down based on the price of AVAX not based on demand. But can also be stated to use USD as the price denominator, effectively making it a stablecoin, this allows anyone to create a stable currency without needing any complicated setup or liquidity, each trader can customize their robot to only pick-up certain tokens, so if you create a new token that traders don’t know about there won’t be an incentive for them to trade it. However, you can run a node on the network and be your own trader, allowing you to sell your tokens yourself and also receive rewards from the network for doing so.

The implications of this are vast, on one hand selling crap tokens would be very easy, but if a token gets popular enough most traders will just pick it up anyways and the price won’t be affected by wild swings. So, there’s no gambling incentive for degenerates to go 1000x on a crap token. Though there is a way to allow this with future Dxes.

The incentive for the deployer is obviously to sell the tokens which they will have full supply control at launch, the incentive for the buyer is whatever additional functionalities the token may perform, for example if you wanted to create a web3 game without spending liquidity, you could launch a token same as normal but then become a trader on Peng, then sell your tokens to your players at a fixed rate, this fixed rate is important for gaming as well, games need stable economies to function.

You can also mint more tokens and create your own burning incentives, allowing you more flexibility on how the game is played, web2 games typically have high inflation but prices magically remain the same, this cannot be said of web3 games where the token is subject to market forces.

3. No points of weakness

Peng does not have authorities who can change the front-end to ban people or alter how the platform is used, nor does it have “owner keys” or a DAO that can be exploited. Every DEX has keys, these keys can be used to halt the smart contract, transfer ownership or approve external contracts, though for the most part this can only be done through a DAO.

4. Can trade any token from any DEX

As mentioned earlier, if you create a liquidity pool on one DEX you can’t swap that token on another DEX unless that DEX has its own separate pool, but this will lead to arbitrage of the token until both pools are leveled out or drained. But on Peng any token can be traded so long as it has some form of pricing.

5. EVM bloat

Does no one find it a bit absurd that you have one smart contract virtual machine for every single contract every deployed forever? The EVM grows by magnitudes of gigabytes per day, with terabytes of broadband needed to sync/run it per year.

Peng offers something akin to a “mini virtual machine” for every single contract with added benefit of rewards for those who run nodes, which is something that isn’t possible on the EVM. (EVM node operators cannot receive rewards directly).

6. No more approval hacks

Approval hacks are by far the easiest way to lose your vaxxies, that and phishing scams. DEXs are like super spreaders for these approvals, in the future all contract approvals can be safely ignored or even blocked directly from the wallet, meaning dust tokens won’t be an issue for newcomers.

7. No more liquidity locking

This sounds counter productive but bear with me for a moment, imagine if you could move liquidity freely between Dxes in a way that didn’t harm the overall performance of the Dx, imagine if you could use the same liquidity on two Dxs simultaneously. Liquidity is considered “removed” once a trader turns off their node, if there is still user demand for swaps then that vacuum will be quickly filled up, liquidity grows and shrinks based on demand.

8. No more pump and dump schemes

This sounds ambitious, but why would you create a token that needs to go up in price for you to make profit when you can just create a token and sell it directly, even if your project fails your users still have a stablecoin they can use for various things. But ideally you should be creating utility and using your own hybrid-line-network to facilitate things like; games, perpetuals, sport betting, etc.

9. No more impermanent loss

I will admit I don’t understand why people complain about “IL”, the times I have provided liquidity it just seemed like my pool went up and down with the value of the paired tokens, but I guess some people don’t want to hold a token that might be more volatile. With Peng you can just hold the token you’re interested in trading (and yes, I know single sided staking allows this).

# Conclusion

:|

--

--