Overview
Background
As stablecoins evolve, the popular TRC20-USDT is no longer alone on TRON. TRON's expanding stablecoin family has welcomed USDJ, TUSD, USDC, USDD, and other new members. The growing market share and variety of stablecoins have given rise to more complex demand for swapping between different stablecoins. Sun.io's StableSwap protocol is designed to provide swap services for stablecoins or tokens of equivalent value, and it offers lower fees and slippage than competitors in the market in the following ways:
Slippage of StableSwap can be reduced to zero when there are sufficient tokens in the liquidity pool;
StableSwap will increase the transaction price of a token to avoid depletion of its supply in the liquidity pool.
Mechanism
To maintain the transaction price at 1, the most straightforward way is to use the equation of a straight line with a slope of -1 (i.e. x + y = k). The price should also be able to adjust itself to avoid liquidity depletion, which requires the constant product formula x * y = k. The StableSwap protocol incorporates both constant sum and constant product. Its model can be simply regarded as the weighted sum of a constant sum and a constant product, as described by the market making formula in the SUN WhitePaper.
According to the above formula, token swaps have an impact on the value of . Take 2pool (USDD, USDT) as an example: suppose the amount before the transaction is . When a user swaps USDD for USDT, the value of will change to . Substitute into the above equation and you will get the new , and represents the amount of USDT the user will obtain. The values of both and remain unchanged during the calculation. is a constant, and the value of can be found with a given using Newton's Method.
Let , Substitute these expressions into the above equation and you can get:
The corresponding contract code is shown below:
def get_D(xp: uint256[N_COINS], amp: uint256) -> uint256:
S: uint256 = 0
for _x in xp:
S += _x
if S == 0:
return 0
Dprev: uint256 = 0
D: uint256 = S
Ann: uint256 = amp * N_COINS
for _i in range(255):
D_P: uint256 = D
for _x in xp:
D_P = D_P * D / (_x * N_COINS)
Dprev = D
D = (Ann * S + D_P * N_COINS) * D / ((Ann - 1) * D + (N_COINS + 1) * D_P)
if D > Dprev:
if D - Dprev <= 1:
break
else:
if Dprev - D <= 1:
break
return D
Last updated