Skip to content

Commit

Permalink
Merge branch 'master' into feature/listaccounthistory_by_txtype
Browse files Browse the repository at this point in the history
  • Loading branch information
monstrobishi authored Dec 7, 2020
2 parents 1150d8d + 6462dc4 commit eb01e0c
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 77 deletions.
4 changes: 2 additions & 2 deletions src/chainparams.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ class CRegTestParams : public CChainParams {
consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in functional tests)
consensus.AMKHeight = 10000000;
consensus.BayfrontHeight = 10000000;
consensus.BayfrontMarinaHeight = 0;
consensus.BayfrontMarinaHeight = 10000000;
consensus.BayfrontGardensHeight = 10000000;

consensus.pos.diffLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
Expand Down Expand Up @@ -723,7 +723,7 @@ void CRegTestParams::UpdateActivationParametersFromArgs(const ArgsManager& args)
LogPrintf("Bayfront disabled for testing\n");
height = std::numeric_limits<int>::max();
}
consensus.BayfrontHeight = static_cast<int>(height);
consensus.BayfrontGardensHeight = static_cast<int>(height);
}

if (!args.IsArgSet("-vbparams")) return;
Expand Down
2 changes: 1 addition & 1 deletion src/masternodes/mn_checks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,7 @@ Res ApplyPoolSwapTx(CCustomCSView &mnview, const CCoinsViewCache &coins, const C
}

return Res::Ok();
}, height >= consensusParams.BayfrontGardensHeight);
}, static_cast<int>(height) >= consensusParams.BayfrontGardensHeight);

if (!res.ok) {
return Res::Err("%s: %s", base, res.msg);
Expand Down
20 changes: 10 additions & 10 deletions src/masternodes/mn_rpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -514,8 +514,8 @@ UniValue listmasternodes(const JSONRPCRequest& request) {
"{id:{...},...} (array) Json object with masternodes information\n"
},
RPCExamples{
HelpExampleCli("listmasternodes", "'[mn_id]' False")
+ HelpExampleRpc("listmasternodes", "'[mn_id]' False")
HelpExampleCli("listmasternodes", "'[mn_id]' false")
+ HelpExampleRpc("listmasternodes", "'[mn_id]' false")
},
}.Check(request);

Expand Down Expand Up @@ -1082,8 +1082,8 @@ UniValue listtokens(const JSONRPCRequest& request) {
"{id:{...},...} (array) Json object with tokens information\n"
},
RPCExamples{
HelpExampleCli("listtokens", "'{\"start\":128}' False")
+ HelpExampleRpc("listtokens", "'{\"start\":128}' False")
HelpExampleCli("listtokens", "'{\"start\":128}' false")
+ HelpExampleRpc("listtokens", "'{\"start\":128}' false")
},
}.Check(request);

Expand Down Expand Up @@ -1382,7 +1382,7 @@ UniValue listaccounts(const JSONRPCRequest& request) {
},
RPCExamples{
HelpExampleCli("listaccounts", "")
+ HelpExampleRpc("listaccounts", "'{}' False")
+ HelpExampleRpc("listaccounts", "'{}' false")
+ HelpExampleRpc("listaccounts", "'{\"start\":\"a914b12ecde1759f792e0228e4fa6d262902687ca7eb87@0\","
"\"limit\":1000"
"}'")
Expand Down Expand Up @@ -1693,8 +1693,8 @@ UniValue listpoolpairs(const JSONRPCRequest& request) {
"{id:{...},...} (array) Json object with pools information\n"
},
RPCExamples{
HelpExampleCli("listpoolpairs", "'{\"start\":128}' False")
+ HelpExampleRpc("listpoolpairs", "'{\"start\":128}' False")
HelpExampleCli("listpoolpairs", "'{\"start\":128}' false")
+ HelpExampleRpc("listpoolpairs", "'{\"start\":128}' false")
},
}.Check(request);

Expand Down Expand Up @@ -2874,8 +2874,8 @@ UniValue listpoolshares(const JSONRPCRequest& request) {
"{id:{...},...} (array) Json object with pools information\n"
},
RPCExamples{
HelpExampleCli("listpoolshares", "'{\"start\":128}' False False")
+ HelpExampleRpc("listpoolshares", "'{\"start\":128}' False False")
HelpExampleCli("listpoolshares", "'{\"start\":128}' false false")
+ HelpExampleRpc("listpoolshares", "'{\"start\":128}' false false")
},
}.Check(request);

Expand Down Expand Up @@ -2998,7 +2998,7 @@ UniValue listaccounthistory(const JSONRPCRequest& request) {
},
RPCExamples{
HelpExampleCli("listaccounthistory", "all '{\"maxBlockHeight\":160,\"depth\":10}'")
+ HelpExampleRpc("listaccounthistory", "address False")
+ HelpExampleRpc("listaccounthistory", "address false")
},
}.Check(request);

Expand Down
15 changes: 5 additions & 10 deletions src/masternodes/poolpairs.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,9 @@ class CPoolPair : public CPoolPairMessage
uint256 creationTx;
uint32_t creationHeight;

Res AddLiquidity(CAmount amountA, CAmount amountB, CScript const & shareAddress, std::function<Res(CScript const & to, CAmount liqAmount)> onMint) {
return this->AddLiquidity(amountA, amountB, shareAddress, onMint, false);
}

// 'amountA' && 'amountB' should be normalized (correspond) to actual 'tokenA' and 'tokenB' ids in the pair!!
// otherwise, 'AddLiquidity' should be () external to 'CPairPool' (i.e. CPoolPairView::AddLiquidity(TAmount a,b etc) with internal lookup of pool by TAmount a,b)
Res AddLiquidity(CAmount amountA, CAmount amountB, CScript const & shareAddress, std::function<Res(CScript const & to, CAmount liqAmount)> onMint, bool slippageProtection) {
Res AddLiquidity(CAmount amountA, CAmount amountB, CScript const & shareAddress, std::function<Res(CScript const & to, CAmount liqAmount)> onMint, bool slippageProtection = false) {
// instead of assertion due to tests
if (amountA <= 0 || amountB <= 0) {
return Res::Err("amounts should be positive");
Expand Down Expand Up @@ -183,7 +179,7 @@ class CPoolPair : public CPoolPairMessage
return onReclaim(address, resAmountA, resAmountB);
}

Res Swap(CTokenAmount in, PoolPrice const & maxPrice, std::function<Res(CTokenAmount const &)> onTransfer, bool postBayfrontGardens = false);
Res Swap(CTokenAmount in, PoolPrice const & maxPrice, std::function<Res(CTokenAmount const &)> onTransfer, bool postBayfrontGardens = true);

private:
CAmount slopeSwap(CAmount unswapped, CAmount & poolFrom, CAmount & poolTo, bool postBayfrontGardens = false);
Expand Down Expand Up @@ -286,14 +282,13 @@ class CPoolPairView : public virtual CStorageView

// distribute trading fees
if (pool.swapEvent) {
CAmount feeA = pool.blockCommissionA * liquidity / pool.totalLiquidity;
CAmount feeA = static_cast<CAmount>((arith_uint256(pool.blockCommissionA) * arith_uint256(liquidity) / arith_uint256(pool.totalLiquidity)).GetLow64());
if (!newRewardCalc) {
feeA = pool.blockCommissionA * liqWeight / PRECISION;
}
distributedFeeA += feeA;
onTransfer(provider, {pool.idTokenA, feeA}); //can throw

CAmount feeB = pool.blockCommissionB * liquidity / pool.totalLiquidity;
CAmount feeB = static_cast<CAmount>((arith_uint256(pool.blockCommissionB) * arith_uint256(liquidity) / arith_uint256(pool.totalLiquidity)).GetLow64());
if (!newRewardCalc) {
feeB = pool.blockCommissionB * liqWeight / PRECISION;
}
Expand All @@ -303,7 +298,7 @@ class CPoolPairView : public virtual CStorageView

// distribute yield farming
if (poolReward) {
CAmount providerReward = poolReward * liquidity / pool.totalLiquidity;
CAmount providerReward = static_cast<CAmount>((arith_uint256(poolReward) * arith_uint256(liquidity) / arith_uint256(pool.totalLiquidity)).GetLow64());
if (!newRewardCalc) {
providerReward = poolReward * liqWeight / PRECISION;
}
Expand Down
12 changes: 5 additions & 7 deletions src/test/liquidity_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,6 @@ BOOST_AUTO_TEST_CASE(math_liquidity_and_trade)
{
auto FAIL_onMint = [](const CScript &, CAmount)-> Res { BOOST_REQUIRE(false); return Res::Err("it should not happen"); };
auto FAIL_onSwap = [](const CTokenAmount &)-> Res { BOOST_REQUIRE(false); return Res::Err("it should not happen"); };
auto OK_onMint = [](const CScript &, CAmount)-> Res { return Res::Ok(); };
auto OK_onSwap = [](const CTokenAmount &)-> Res { return Res::Ok(); };

CCustomCSView mnview(*pcustomcsview);

Expand Down Expand Up @@ -235,9 +233,9 @@ BOOST_AUTO_TEST_CASE(math_liquidity_and_trade)
BOOST_CHECK_EQUAL(pool.reserveA, 100099000);
BOOST_CHECK_EQUAL(pool.reserveB, 99901097913); // pre-optimization: 99901000000

printf("comissionA = %ld\n", pool.blockCommissionA);
printf("reserveA = %ld\n", pool.reserveA);
printf("reserveB = %ld\n", pool.reserveB);
// printf("comissionA = %ld\n", pool.blockCommissionA);
// printf("reserveA = %ld\n", pool.reserveA);
// printf("reserveB = %ld\n", pool.reserveB);
}
}

Expand Down Expand Up @@ -322,9 +320,9 @@ BOOST_AUTO_TEST_CASE(math_rewards)
}
);
int64_t nTimeEnd = GetTimeMicros(); auto nTimeRwd = nTimeEnd - nTimeBegin;
printf("Rewarded %d pools with %d shares each: %.2fms \n", PoolCount, ProvidersCount, 0.001 * (nTimeRwd));
// printf("Rewarded %d pools with %d shares each: %.2fms \n", PoolCount, ProvidersCount, 0.001 * (nTimeRwd));

printf("Distributed: = %ld\n", distributed);
// printf("Distributed: = %ld\n", distributed);
BOOST_CHECK(distributed == 9999000000); // always slightly less due to MINIMUM_LIQUIDITY & rounding

// check it
Expand Down
8 changes: 4 additions & 4 deletions test/functional/feature_any_accounts_to_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ def set_test_params(self):
# We need to enlarge -datacarriersize for allowing for test big OP_RETURN scripts
# resulting from building AnyAccountsToAccounts msg with many accounts balances
self.extra_args = [
['-txnotokens=0', '-bayfrontgardensheight=50', '-datacarriersize=1000'],
['-txnotokens=0', '-bayfrontgardensheight=50', '-datacarriersize=1000'],
['-txnotokens=0', '-bayfrontgardensheight=50', '-datacarriersize=1000'],
['-txnotokens=0', '-bayfrontgardensheight=50', '-datacarriersize=1000']
['-txnotokens=0', '-amkheight=50', '-bayfrontgardensheight=50', '-datacarriersize=1000'],
['-txnotokens=0', '-amkheight=50', '-bayfrontgardensheight=50', '-datacarriersize=1000'],
['-txnotokens=0', '-amkheight=50', '-bayfrontgardensheight=50', '-datacarriersize=1000'],
['-txnotokens=0', '-amkheight=50', '-bayfrontgardensheight=50', '-datacarriersize=1000']
]

def run_test(self):
Expand Down
41 changes: 25 additions & 16 deletions test/functional/feature_poolswap.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ def set_test_params(self):
# node2: Non Foundation
self.setup_clean_chain = True
self.extra_args = [
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-acindex=1'],
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-acindex=1'],
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50'],
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50']]
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=0', '-acindex=1'],
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=0', '-acindex=1'],
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=0'],
['-txnotokens=0', '-amkheight=50', '-bayfrontheight=50', '-bayfrontgardensheight=0']]


def run_test(self):
Expand Down Expand Up @@ -85,8 +85,8 @@ def run_test(self):
# check tokens id
pool = self.nodes[0].getpoolpair("GS")
idGS = list(self.nodes[0].gettoken("GS").keys())[0]
assert(pool[idGS]['idTokenA'] == idGold)
assert(pool[idGS]['idTokenB'] == idSilver)
assert_equal(pool[idGS]['idTokenA'], idGold)
assert_equal(pool[idGS]['idTokenB'], idSilver)

# Fail swap: lack of liquidity
try:
Expand Down Expand Up @@ -134,14 +134,14 @@ def run_test(self):
print("Checking Silver on AccN0:", silverCheckN0, ", id", idSilver)

# 5 Checking that liquidity is correct
assert(goldCheckN0 == 700)
assert(silverCheckN0 == 500)
assert_equal(goldCheckN0, 700)
assert_equal(silverCheckN0, 500)

list_pool = self.nodes[0].listpoolpairs()
#print (list_pool)

assert(list_pool['1']['reserveA'] == 200) # GOLD
assert(list_pool['1']['reserveB'] == 1000) # SILVER
assert_equal(list_pool['1']['reserveA'], 200) # GOLD
assert_equal(list_pool['1']['reserveB'], 1000) # SILVER

# 6 Trying to poolswap

Expand All @@ -161,6 +161,14 @@ def run_test(self):
self.nodes[0].updatepoolpair({"pool": "GS", "status": True})
self.nodes[0].generate(1)

print("Before swap")
print("Checking Gold on AccN0:", goldCheckN0, ", id", idGold)
print("Checking Silver on AccN0:", silverCheckN0, ", id", idSilver)
goldCheckN1 = self.nodes[2].getaccount(accountSN1, {}, True)[idGold]
print("Checking Gold on AccN1:", goldCheckN1, ", id", idGold)
silverCheckN1 = self.nodes[2].getaccount(accountSN1, {}, True)[idSilver]
print("Checking Silver on AccN1:", silverCheckN1, ", id", idSilver)

testPoolSwapRes = self.nodes[0].testpoolswap({
"from": accountGN0,
"tokenFrom": symbolSILVER,
Expand Down Expand Up @@ -193,6 +201,7 @@ def run_test(self):
self.sync_blocks([self.nodes[0], self.nodes[2]])

# 8 Checking that poolswap is correct
print("After swap")
goldCheckN0 = self.nodes[2].getaccount(accountGN0, {}, True)[idGold]
print("Checking Gold on AccN0:", goldCheckN0, ", id", idGold)
silverCheckN0 = self.nodes[2].getaccount(accountGN0, {}, True)[idSilver]
Expand All @@ -209,12 +218,12 @@ def run_test(self):
self.nodes[0].listpoolshares()
#print (list_poolshares)

assert(goldCheckN0 == 700)
assert(str(silverCheckN0) == "490.49990000") # TODO: calculate "true" values with trading fee!
assert(list_pool['1']['reserveA'] + goldCheckN1 == 300)
assert(Decimal(goldCheckPS) + Decimal(psTestAmount) == Decimal(goldCheckN1))
assert(str(silverCheckN1) == "500.50000000")
assert(list_pool['1']['reserveB'] == 1009) #1010 - 1 (commission)
assert_equal(goldCheckN0, 700)
assert_equal(str(silverCheckN0), "490.49999997") # TODO: calculate "true" values with trading fee!
assert_equal(list_pool['1']['reserveA'] + goldCheckN1 , 300)
assert_equal(Decimal(goldCheckPS) + Decimal(psTestAmount), Decimal(goldCheckN1))
assert_equal(str(silverCheckN1), "500.50000000")
assert_equal(list_pool['1']['reserveB'], 1009) #1010 - 1 (commission)

# 9 Fail swap: price higher than indicated
price = list_pool['1']['reserveA/reserveB']
Expand Down
46 changes: 20 additions & 26 deletions test/functional/feature_poolswap_mechanism.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import random
import time
import math
from decimal import Decimal

class PoolSwapTest (DefiTestFramework):
Expand All @@ -25,7 +24,9 @@ def set_test_params(self):
# node1: secondary tester
# node2: revert create (all)
self.setup_clean_chain = True
self.extra_args = [['-txnotokens=0', '-amkheight=0', '-bayfrontheight=0'], ['-txnotokens=0', '-amkheight=0', '-bayfrontheight=0'], ['-txnotokens=0', '-amkheight=0', '-bayfrontheight=0']]
self.extra_args = [['-txnotokens=0', '-amkheight=0', '-bayfrontheight=0', '-bayfrontgardensheight=0'],
['-txnotokens=0', '-amkheight=0', '-bayfrontheight=0', '-bayfrontgardensheight=0'],
['-txnotokens=0', '-amkheight=0', '-bayfrontheight=0', '-bayfrontgardensheight=0']]

# SET parameters for create tokens and pools
#========================
Expand Down Expand Up @@ -148,18 +149,13 @@ def add_pools_liquidity(self, owner):
self.nodes[0].generate(1)

def slope_swap(self, unswapped, poolFrom, poolTo):
while unswapped > 0:
if poolFrom / 1000 > unswapped:
stepFrom = unswapped
else:
stepFrom = poolFrom / 1000
stepTo = poolTo * stepFrom / poolFrom
poolFrom += stepFrom
poolTo -= stepTo
unswapped -= stepFrom
swapped = poolTo - (poolTo * poolFrom / (poolFrom + unswapped))
poolFrom += unswapped
poolTo -= swapped

return (poolFrom, poolTo)

def pollswap(self):
def poolswap(self):
for item in range(self.COUNT_POOLS):
tokenA = "GOLD" + str(item)
tokenB = "SILVER" + str(item)
Expand Down Expand Up @@ -199,29 +195,27 @@ def pollswap(self):
for idx in range(start, end):
liquidity = self.nodes[0].getaccount(self.accounts[idx], {}, True)[idPool]
totalLiquidity = self.nodes[0].getpoolpair(pool, True)[idPool]['totalLiquidity']
liqWeight = int(liquidity * self.DECIMAL) * 10000 // int(totalLiquidity * self.DECIMAL)
assert(liqWeight < 10000)
feeB = (int(blockCommissionB * self.DECIMAL) * liqWeight) / Decimal(10000)

liquidity = int(liquidity * self.DECIMAL)
totalLiquidity = int(totalLiquidity * self.DECIMAL)

feeB = (int(blockCommissionB * self.DECIMAL) * liquidity) // totalLiquidity
(reserveB, reserveA) = self.slope_swap(Decimal(amount - (amount * self.COMMISSION)), reserveB, reserveA)
newReserveB = reserveB
assert_equal(amountsB[idx] - amount + (feeB / self.DECIMAL), self.nodes[0].getaccount(self.accounts[idx], {}, True)[self.get_id_token(tokenB)])

# realPoolReward =
self.nodes[0].getaccount(self.accounts[idx], {}, True)['0'] - poolRewards[idx]
assert_equal(amountsB[idx] - amount + Decimal(str(feeB / self.DECIMAL)), self.nodes[0].getaccount(self.accounts[idx], {}, True)[self.get_id_token(tokenB)])

realPoolReward = self.nodes[0].getaccount(self.accounts[idx], {}, True)['0'] - poolRewards[idx]

yieldFarming = int(self.LP_DAILY_DFI_REWARD * self.DECIMAL) / (60 * 60 * 24 / 600) # Regression test in chainparams.cpp
rewardPct = self.nodes[0].getpoolpair(pool, True)[idPool]['rewardPct']
assert(rewardPct > 0)
poolReward = yieldFarming * int(rewardPct * self.DECIMAL) / self.DECIMAL
poolReward = yieldFarming * int(rewardPct * self.DECIMAL) // self.DECIMAL

if poolReward:
providerReward = poolReward * liqWeight / 10000
providerReward = poolReward * liquidity // totalLiquidity
if providerReward:
(d, n) = math.modf(providerReward)
if math.ceil(d) < 1:
providerReward -= 1
# Inaccurate calculations
#assert_equal(str(int(realPoolReward * self.DECIMAL)), str(int(providerReward)))
assert_equal(int(realPoolReward * self.DECIMAL), int(providerReward))

reserveB = self.nodes[0].getpoolpair(pool, True)[idPool]['reserveB']
assert_equal(str(reserveB), format(newReserveB, '.8f'))
Expand Down Expand Up @@ -304,7 +298,7 @@ def run_test(self):

print("Swapping tokens...")
start_time = time.time()
self.pollswap()
self.poolswap()
end_time = time.time() - start_time
print("Tokens exchanged")
print("Elapsed time: {} s".format(end_time))
Expand Down
Loading

0 comments on commit eb01e0c

Please sign in to comment.