It is my impression that almost nobody knows what is the exact formula determining the price of RAM in EOS.
After a very careful study of the formulas implemented in exchange_state.cpp,
Kyunghwan Kim, Hyunwoong Ji (both from EOS Seoul) and I (from EOS Argentina) concluded that after a RAM transaction, the quantity “E times R” remains constant, where E is the EOS balance of the connector (equal to the balance of eosio.ram plus 1,000,000 EOS) and R is the amount of available RAM. It is easy to verify this by observing data from the mainnet. With only this information we can deduce an easy formula for the price of RAM.
Note: fee will be explained at the end.
Say we are buying Q bytes of RAM. We will have to pay some amount P of EOS. The price we are paying for RAM is simply P/Q. Before buying, we have the quantities E and R. After buying we will have E+P and R-Q.
We know (E+P)(R-Q) = ER.
So E/(R-Q) is the formula if there was no fee.
Why are the formulas in the code so complicated if at the end of the day the actual formula is so easy? I have no idea.
Notice that if the amount Q is small compared to available ram R, the price is approximately E/R. However if for example Q = R/2, the price is 2E/R. And so on.
How does the fee get in? According to the code in the contract delegate bandwidth.cpp the function “buyram” first charges a 0.5% fee and then buys ram with the rest of the money. So the final formula is just 1.005 E / (R-Q).
( Actually the factor 1.005 is 1000/995 = 1.005025126, because this is the number such that after substracting 0.5% the result is 1 ).
The analysis for selling RAM is similar.
Note: see the following screenshot with the difference of 1 million EOS between the connector's balance and the balance of eosio.ram, due to connector initialization.
When selling Q bytes of RAM, the same equations work but changing the sign of P and Q. Therefore the formula for the price is P/Q = E/(R+Q) times the fee factor 0.995
This is so much more elegant then this unnecessary complexity of the Relay model in the EOSIO code.
This piece really helped me. E * R =constant. I tested this on EOS, Telos and BOS and is exactly right. This formula also has no slippage.
price = dE/-dR = d (c/R)/-dR= -c/(R*R) dR/-dR = E/R -> QED
PS it is -dR instead of dR as RAM connector buffer goes down when EOS enters the EOS connector
You can also easily derive what the price curve looks like if you want to plot on the X-axis the % RAM utilisation = x and on the Y-axis the price = p
p = E / R and R = (1-x) * R0 and E0 * R0 = c (E0 and R0 are starter balances)
p= c / (R^2) = E0 * R0 / ((1-x)^2 * R0^2) = E0/R0 /(1-x)^2 =p0 / (1-x)^2
So the price p goes up from the starting price p0 with the curve 1/(1-x)^2 in every Bancor Relay model