BitShares-Core  7.0.2
BitShares blockchain node software and command-line wallet software
db_market.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
3  *
4  * The MIT License
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
26 
29 #include <graphene/chain/hardfork.hpp>
32 
33 #include <fc/uint128.hpp>
34 
35 namespace graphene { namespace chain {
36 
37 namespace detail {
38 
39  share_type calculate_percent(const share_type& value, uint16_t percent)
40  {
41  fc::uint128_t a(value.value);
42  a *= percent;
44  FC_ASSERT( a <= GRAPHENE_MAX_SHARE_SUPPLY, "overflow when calculating percent" );
45  return static_cast<int64_t>(a);
46  }
47 
48 } //detail
49 
50 bool database::check_for_blackswan( const asset_object& mia, bool enable_black_swan,
51  const asset_bitasset_data_object* bitasset_ptr )
52 {
53  if( !mia.is_market_issued() ) return false;
54 
55  const asset_bitasset_data_object& bitasset = bitasset_ptr ? *bitasset_ptr : mia.bitasset_data(*this);
56  if( bitasset.is_globally_settled() ) return true; // already globally settled
57  auto settle_price = bitasset.current_feed.settlement_price;
58  if( settle_price.is_null() ) return false; // no feed
59 
60  asset_id_type debt_asset_id = bitasset.asset_id;
61 
63  bool before_core_hardfork_1270 = ( maint_time <= HARDFORK_CORE_1270_TIME ); // call price caching issue
64  bool after_core_hardfork_2481 = HARDFORK_CORE_2481_PASSED( maint_time ); // Match settle orders with margin calls
65 
66  // After core-2481 hard fork, if there are force-settlements, match call orders with them first
67  if( after_core_hardfork_2481 )
68  {
69  const auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
70  auto lower_itr = settlement_index.lower_bound( debt_asset_id );
71  if( lower_itr != settlement_index.end() && lower_itr->balance.asset_id == debt_asset_id )
72  return false;
73  }
74 
75  // Find the call order with the least collateral ratio
76  const call_order_object* call_ptr = find_least_collateralized_short( bitasset, false );
77  if( !call_ptr ) // no call order
78  return false;
79 
80  const limit_order_index& limit_index = get_index_type<limit_order_index>();
81  const auto& limit_price_index = limit_index.indices().get<by_price>();
82 
83  // looking for limit orders selling the most USD for the least CORE
84  auto highest_possible_bid = price::max( debt_asset_id, bitasset.options.short_backing_asset );
85  // stop when limit orders are selling too little USD for too much CORE
86  auto lowest_possible_bid = price::min( debt_asset_id, bitasset.options.short_backing_asset );
87 
88  FC_ASSERT( highest_possible_bid.base.asset_id == lowest_possible_bid.base.asset_id );
89  // NOTE limit_price_index is sorted from greatest to least
90  auto limit_itr = limit_price_index.lower_bound( highest_possible_bid );
91  auto limit_end = limit_price_index.upper_bound( lowest_possible_bid );
92 
93  price call_pays_price;
94  if( limit_itr != limit_end )
95  {
96  call_pays_price = limit_itr->sell_price;
97  if( after_core_hardfork_2481 )
98  {
99  // due to margin call fee, we check with MCPP (margin call pays price) here
100  call_pays_price = call_pays_price * bitasset.get_margin_call_pays_ratio();
101  }
102  }
103 
105  const auto bsrm = bitasset.get_black_swan_response_method();
106 
107  // when BSRM is individual settlement, we loop multiple times
108  bool settled_some = false;
109  while( true )
110  {
111  settle_price = bitasset.current_feed.settlement_price;
112  price highest = settle_price;
113  // Due to #338, we won't check for black swan on incoming limit order, so need to check with MSSP here
114  // * If BSRM is individual_settlement_to_fund, check with median_feed to decide whether to settle.
115  // * If BSRM is no_settlement, check with current_feed to NOT trigger global settlement.
116  // * If BSRM is global_settlement or individual_settlement_to_order, median_feed == current_feed.
117  if( bsrm_type::individual_settlement_to_fund == bsrm )
118  highest = bitasset.median_feed.max_short_squeeze_price();
119  else if( !before_core_hardfork_1270 )
120  highest = bitasset.current_feed.max_short_squeeze_price();
121  else if( maint_time > HARDFORK_CORE_338_TIME )
122  highest = bitasset.current_feed.max_short_squeeze_price_before_hf_1270();
123  // else do nothing
124 
125  if( limit_itr != limit_end )
126  {
127  FC_ASSERT( highest.base.asset_id == limit_itr->sell_price.base.asset_id );
128  if( bsrm_type::individual_settlement_to_fund != bsrm )
129  highest = std::max( call_pays_price, highest );
130  // for individual_settlement_to_fund, if call_pays_price < current_feed.max_short_squeeze_price(),
131  // we don't match the least collateralized short with the limit order
132  // even if call_pays_price >= median_feed.max_short_squeeze_price()
133  else if( call_pays_price >= bitasset.current_feed.max_short_squeeze_price() )
134  highest = call_pays_price;
135  // else highest is median_feed.max_short_squeeze_price()
136  }
137 
138  // The variable `highest` after hf_338:
139  // * if no limit order, it is expected to be the black swan price; if the call order with the least CR
140  // has CR below or equal to the black swan price, we trigger GS,
141  // * if there exists at least one limit order and the price is higher, we use the limit order's price,
142  // which means we will match the margin call orders with the limit order first.
143  //
144  // However, there was a bug: after hf_bsip74 and before hf_2481, margin call fee was not considered
145  // when calculating highest, which means some blackswans weren't got caught here. Fortunately they got
146  // caught by an additional check in check_call_orders().
147  // This bug is fixed in hf_2481. Actually, after hf_2481,
148  // * if there is a force settlement, we totally rely on the additional checks in check_call_orders(),
149  // * if there is no force settlement, we check here with margin call fee in consideration.
150 
151  auto least_collateral = call_ptr->collateralization();
152  // Note: strictly speaking, even when the call order's collateralization is lower than ~highest,
153  // if the matching limit order is smaller, due to rounding, it is still possible that the
154  // call order's collateralization would increase and become higher than ~highest after matched.
155  // However, for simplicity, we only compare the prices here.
156  bool is_blackswan = after_core_hardfork_2481 ? ( ~least_collateral > highest )
157  : ( ~least_collateral >= highest );
158  if( !is_blackswan )
159  return settled_some;
160 
161  wdump( (*call_ptr) );
162  elog( "Black Swan detected on asset ${symbol} (${id}) at block ${b}: \n"
163  " Least collateralized call: ${lc} ${~lc}\n"
164  // " Highest Bid: ${hb} ${~hb}\n"
165  " Settle Price: ${~sp} ${sp}\n"
166  " Max: ${~h} ${h}\n",
167  ("id",mia.id)("symbol",mia.symbol)("b",head_block_num())
168  ("lc",least_collateral.to_real())("~lc",(~least_collateral).to_real())
169  // ("hb",limit_itr->sell_price.to_real())("~hb",(~limit_itr->sell_price).to_real())
170  ("sp",settle_price.to_real())("~sp",(~settle_price).to_real())
171  ("h",highest.to_real())("~h",(~highest).to_real()) );
172  edump((enable_black_swan));
173  FC_ASSERT( enable_black_swan,
174  "Black swan was detected during a margin update which is not allowed to trigger a blackswan" );
175 
176  if( bsrm_type::individual_settlement_to_fund == bsrm || bsrm_type::individual_settlement_to_order == bsrm )
177  {
178  individually_settle( bitasset, *call_ptr );
179  call_ptr = find_least_collateralized_short( bitasset, true );
180  if( !call_ptr ) // no call order
181  return true;
182  settled_some = true;
183  continue;
184  }
185  // Global settlement or no settlement, but we should not be here if BSRM is no_settlement
186  else if( after_core_hardfork_2481 )
187  {
188  if( bsrm_type::no_settlement == bsrm ) // this should not happen, be defensive here
189  wlog( "Internal error: BSRM is no_settlement but undercollateralization occurred" );
190  // After hf_2481, when a global settlement occurs,
191  // * the margin calls (whose CR <= MCR) pay a premium (by MSSR-MCFR) and a margin call fee (by MCFR), and
192  // they are closed at the same price,
193  // * the debt positions with CR > MCR do not pay premium or margin call fee, and they are closed at a same
194  // price too.
195  // * The GS price would close the position with the least CR with no collateral left for the owner,
196  // but would close other positions with some collateral left (if any) for their owners.
197  // * Both the premium and the margin call fee paid by the margin calls go to the asset owner, none will go
198  // to the global settlement fund, because
199  // - if a part of the premium or fees goes to the global settlement fund, it means there would be a
200  // difference in settlement prices, so traders are incentivized to create new debt in the last minute
201  // then settle after GS to earn free money,
202  // - if no premium or fees goes to the global settlement fund, it means debt asset holders would only
203  // settle for less after GS, so they are incentivized to settle before GS which helps avoid GS.
204  globally_settle_asset(mia, ~least_collateral, true );
205  }
206  else if( maint_time > HARDFORK_CORE_338_TIME && ~least_collateral <= settle_price )
207  // global settle at feed price if possible
208  globally_settle_asset(mia, settle_price );
209  else
210  globally_settle_asset(mia, ~least_collateral );
211  return true;
212  }
213 }
214 
221 void database::globally_settle_asset( const asset_object& mia, const price& settlement_price,
222  bool check_margin_calls )
223 {
225  bool before_core_hardfork_1669 = ( maint_time <= HARDFORK_CORE_1669_TIME ); // whether to use call_price
226 
227  if( before_core_hardfork_1669 )
228  {
229  globally_settle_asset_impl( mia, settlement_price,
230  get_index_type<call_order_index>().indices().get<by_price>(),
231  check_margin_calls );
232  }
233  else
234  {
235  // Note: it is safe to iterate here even if there is no call order due to individual settlements
236  globally_settle_asset_impl( mia, settlement_price,
237  get_index_type<call_order_index>().indices().get<by_collateral>(),
238  check_margin_calls );
239  }
240 }
241 
242 template<typename IndexType>
243 void database::globally_settle_asset_impl( const asset_object& mia,
244  const price& settlement_price,
245  const IndexType& call_index,
246  bool check_margin_calls )
247 { try {
248  const asset_bitasset_data_object& bitasset = mia.bitasset_data(*this);
249  // GCOVR_EXCL_START
250  // Defensive code, normally it should not fail
251  FC_ASSERT( !bitasset.is_globally_settled(), "black swan already occurred, it should not happen again" );
252  // GCOVR_EXCL_STOP
253 
254  asset collateral_gathered( 0, bitasset.options.short_backing_asset );
255 
256  const asset_dynamic_data_object& mia_dyn = mia.dynamic_asset_data_id(*this);
257  auto original_mia_supply = mia_dyn.current_supply;
258 
260  bool before_core_hardfork_342 = ( maint_time <= HARDFORK_CORE_342_TIME ); // better rounding
261 
262  // cancel all call orders and accumulate it into collateral_gathered
263  auto call_itr = call_index.lower_bound( price::min( bitasset.options.short_backing_asset, bitasset.asset_id ) );
264  auto call_end = call_index.upper_bound( price::max( bitasset.options.short_backing_asset, bitasset.asset_id ) );
265 
266  auto margin_end = call_end;
267  bool is_margin_call = false;
268  price call_pays_price = settlement_price;
269  price fund_receives_price = settlement_price;
270  if( check_margin_calls )
271  {
272  margin_end = call_index.upper_bound( bitasset.current_maintenance_collateralization );
273  // Note: settlement_price is in debt / collateral, here the fund gets less collateral
274  fund_receives_price = settlement_price * ratio_type( bitasset.current_feed.maximum_short_squeeze_ratio,
276  if( call_itr != margin_end )
277  is_margin_call = true;
278  }
279  asset margin_call_fee( 0, bitasset.options.short_backing_asset );
280 
281  asset pays;
282  while( call_itr != call_end )
283  {
284  if( is_margin_call && call_itr == margin_end )
285  {
286  is_margin_call = false;
287  call_pays_price = fund_receives_price;
288  }
289 
290  const call_order_object& order = *call_itr;
291  ++call_itr;
292 
293  auto order_debt = order.get_debt();
294  if( before_core_hardfork_342 )
295  pays = order_debt * call_pays_price; // round down, in favor of call order
296  else
297  pays = order_debt.multiply_and_round_up( call_pays_price ); // round up in favor of global-settle fund
298 
299  if( pays > order.get_collateral() )
300  pays = order.get_collateral();
301 
302  if( is_margin_call )
303  {
304  auto fund_receives = order_debt.multiply_and_round_up( fund_receives_price );
305  if( fund_receives > pays )
306  fund_receives = pays;
307  margin_call_fee = pays - fund_receives;
308  collateral_gathered += fund_receives;
309  }
310  else
311  {
312  margin_call_fee.amount = 0;
313  collateral_gathered += pays;
314  }
315 
316  // call order is maker
317  FC_ASSERT( fill_call_order( order, pays, order_debt, fund_receives_price, true, margin_call_fee, false ),
318  "Internal error: unable to close margin call ${o}", ("o", order) );
319  }
320 
321  // Remove the individual settlement order
322  const limit_order_object* limit_ptr = find_settled_debt_order( bitasset.asset_id );
323  if( limit_ptr )
324  remove( *limit_ptr );
325 
326  // Move individual settlement fund to the GS fund
327  collateral_gathered.amount += bitasset.individual_settlement_fund;
328 
329  modify( bitasset, [&mia,&original_mia_supply,&collateral_gathered]( asset_bitasset_data_object& obj ){
330  obj.options.extensions.value.black_swan_response_method.reset(); // Update BSRM to GS
331  obj.current_feed = obj.median_feed; // reset current feed price if was capped
332  obj.individual_settlement_debt = 0;
333  obj.individual_settlement_fund = 0;
334  obj.settlement_price = mia.amount(original_mia_supply) / collateral_gathered;
335  obj.settlement_fund = collateral_gathered.amount;
336  });
337 
338 } FC_CAPTURE_AND_RETHROW( (mia)(settlement_price) ) } // GCOVR_EXCL_LINE
339 
340 void database::individually_settle( const asset_bitasset_data_object& bitasset, const call_order_object& order )
341 {
342  FC_ASSERT( bitasset.asset_id == order.debt_type(), "Internal error: asset type mismatch" );
343 
345  const auto bsrm = bitasset.get_black_swan_response_method();
346  FC_ASSERT( bsrm_type::individual_settlement_to_fund == bsrm || bsrm_type::individual_settlement_to_order == bsrm,
347  "Internal error: Invalid BSRM" );
348 
349  auto order_debt = order.get_debt();
350  auto order_collateral = order.get_collateral();
351  auto fund_receives_price = (~order.collateralization()) / bitasset.get_margin_call_pays_ratio();
352  auto fund_receives = order_debt.multiply_and_round_up( fund_receives_price );
353  if( fund_receives.amount > order.collateral ) // should not happen, just be defensive
354  fund_receives.amount = order.collateral;
355 
356  auto margin_call_fee = order_collateral - fund_receives;
357 
358  modify( bitasset, [&order,&fund_receives]( asset_bitasset_data_object& obj ){
359  obj.individual_settlement_debt += order.debt;
360  obj.individual_settlement_fund += fund_receives.amount;
361  });
362 
363  if( bsrm_type::individual_settlement_to_order == bsrm ) // settle to order
364  {
365  const auto& head_time = head_block_time();
366  bool after_core_hardfork_2591 = HARDFORK_CORE_2591_PASSED( head_time ); // Tighter peg (fill debt order at MCOP)
367 
368  const limit_order_object* limit_ptr = find_settled_debt_order( bitasset.asset_id );
369  if( limit_ptr )
370  {
371  modify( *limit_ptr, [after_core_hardfork_2591,&bitasset]( limit_order_object& obj ) {
372  // TODO fix duplicate code
373  bool sell_all = true;
374  if( after_core_hardfork_2591 )
375  {
376  obj.sell_price = ~bitasset.get_margin_call_order_price();
377  asset settled_debt( bitasset.individual_settlement_debt, obj.receive_asset_id() );
378  try
379  {
380  obj.for_sale = settled_debt.multiply_and_round_up( obj.sell_price ).amount; // may overflow
381  // Note: the "=" below is for the consistency of order matching logic
382  if( obj.for_sale <= bitasset.individual_settlement_fund )
383  sell_all = false;
384  }
385  catch( fc::exception& e ) // catch the overflow
386  {
387  // do nothing
388  dlog( e.to_detail_string() );
389  }
390  }
391  if( sell_all )
392  {
393  obj.for_sale = bitasset.individual_settlement_fund;
394  obj.sell_price = ~bitasset.get_individual_settlement_price();
395  }
396  } );
397  }
398  else
399  {
400  create< limit_order_object >( [&order_debt,&fund_receives]( limit_order_object& obj ) {
401  obj.expiration = time_point_sec::maximum();
402  obj.seller = GRAPHENE_NULL_ACCOUNT;
403  obj.for_sale = fund_receives.amount;
404  obj.sell_price = fund_receives / order_debt;
405  obj.is_settled_debt = true;
406  } );
407  }
408  // Note: CORE asset in settled debt is not counted in account_stats.total_core_in_orders
409  }
410 
411  // call order is maker
412  FC_ASSERT( fill_call_order( order, order_collateral, order_debt,
413  fund_receives_price, true, margin_call_fee, false ),
414  "Internal error: unable to close margin call ${o}", ("o", order) );
415 
416  // Update current feed if needed
417  if( bsrm_type::individual_settlement_to_fund == bsrm )
418  update_bitasset_current_feed( bitasset, true );
419 
420 }
421 
423 { try {
424  // GCOVR_EXCL_START
425  // Defensive code, normally none of these should fail
426  FC_ASSERT( bitasset.is_market_issued() );
427  FC_ASSERT( bitasset.id == bad.asset_id );
431  // GCOVR_EXCL_STOP
432 
433  const asset_dynamic_data_object& bdd = bitasset.dynamic_asset_data_id(*this);
434  if( bdd.current_supply > 0 )
435  {
436  // Create + execute a "bid" with 0 additional collateral
437  const collateral_bid_object& pseudo_bid = create<collateral_bid_object>(
438  [&bitasset,&bad,&bdd](collateral_bid_object& bid) {
439  bid.bidder = bitasset.issuer;
441  / asset(bdd.current_supply, bad.asset_id);
442  });
443  execute_bid( pseudo_bid, bdd.current_supply, bad.settlement_fund, bad.current_feed );
444  } else
445  FC_ASSERT( bad.settlement_fund == 0 );
446 
447  _cancel_bids_and_revive_mpa( bitasset, bad );
448 } FC_CAPTURE_AND_RETHROW( (bitasset) ) } // GCOVR_EXCL_LINE
449 
450 void database::_cancel_bids_and_revive_mpa( const asset_object& bitasset, const asset_bitasset_data_object& bad )
451 { try {
452  // GCOVR_EXCL_START
453  // Defensive code, normally none of these should fail
454  FC_ASSERT( bitasset.is_market_issued() );
457  // GCOVR_EXCL_STOP
458 
459  // cancel remaining bids
460  const auto& bid_idx = get_index_type< collateral_bid_index >().indices().get<by_price>();
461  auto itr = bid_idx.lower_bound( bad.asset_id );
462  const auto end = bid_idx.upper_bound( bad.asset_id );
463  while( itr != end )
464  {
465  const collateral_bid_object& bid = *itr;
466  ++itr;
467  cancel_bid( bid );
468  }
469 
470  // revive
471  modify( bad, []( asset_bitasset_data_object& obj ){
472  obj.settlement_price = price();
473  obj.settlement_fund = 0;
474  });
475 } FC_CAPTURE_AND_RETHROW( (bitasset) ) } // GCOVR_EXCL_LINE
476 
477 void database::cancel_bid(const collateral_bid_object& bid, bool create_virtual_op)
478 {
480 
481  if( create_virtual_op )
482  {
484  vop.bidder = bid.bidder;
487  push_applied_operation( vop );
488  }
489  remove(bid);
490 }
491 
493  share_type collateral_from_fund, const price_feed& current_feed )
494 {
495  const call_order_object& call_obj = create<call_order_object>(
496  [&bid, &debt_covered, &collateral_from_fund, &current_feed, this](call_order_object& call ){
497  call.borrower = bid.bidder;
498  call.collateral = bid.inv_swan_price.base.amount + collateral_from_fund;
499  call.debt = debt_covered;
500  // don't calculate call_price after core-1270 hard fork
501  if( get_dynamic_global_properties().next_maintenance_time > HARDFORK_CORE_1270_TIME )
502  // bid.inv_swan_price is in collateral / debt
503  call.call_price = price( asset( 1, bid.inv_swan_price.base.asset_id ),
504  asset( 1, bid.inv_swan_price.quote.asset_id ) );
505  else
506  call.call_price = price::call_price( asset(debt_covered, bid.inv_swan_price.quote.asset_id),
508  current_feed.maintenance_collateral_ratio );
509  });
510 
511  // Note: CORE asset in collateral_bid_object is not counted in account_stats.total_core_in_orders
512  if( bid.inv_swan_price.base.asset_id == asset_id_type() )
514  stats.total_core_in_orders += call_obj.collateral;
515  });
516 
518  asset( debt_covered, bid.inv_swan_price.quote.asset_id ),
519  asset( call_obj.collateral, bid.inv_swan_price.base.asset_id ) ) );
520 
521  remove(bid);
522 }
523 
525 {
526  adjust_balance(order.owner, order.balance);
527 
529 
530  remove(order);
531 }
532 
533 void database::cancel_limit_order( const limit_order_object& order, bool create_virtual_op, bool skip_cancel_fee )
534 {
535  // if need to create a virtual op, try deduct a cancellation fee here.
536  // there are two scenarios when order is cancelled and need to create a virtual op:
537  // 1. due to expiration: always deduct a fee if there is any fee deferred
538  // 2. due to cull_small: deduct a fee after hard fork 604, but not before (will set skip_cancel_fee)
539  const account_statistics_object* seller_acc_stats = nullptr;
540  const asset_dynamic_data_object* deferred_fee_asset_dyn_data = nullptr;
542  share_type deferred_fee = order.deferred_fee;
543  asset deferred_paid_fee = order.deferred_paid_fee;
544  if( create_virtual_op )
545  {
546  vop.order = order.id;
547  vop.fee_paying_account = order.seller;
548  // only deduct fee if not skipping fee, and there is any fee deferred
549  if( !skip_cancel_fee && deferred_fee > 0 )
550  {
551  asset core_cancel_fee = current_fee_schedule().calculate_fee( vop );
552  // cap the fee
553  if( core_cancel_fee.amount > deferred_fee )
554  core_cancel_fee.amount = deferred_fee;
555  // if there is any CORE fee to deduct, redirect it to referral program
556  if( core_cancel_fee.amount > 0 )
557  {
558  seller_acc_stats = &get_account_stats_by_owner( order.seller );
559  modify( *seller_acc_stats, [&core_cancel_fee, this]( account_statistics_object& obj ) {
560  obj.pay_fee( core_cancel_fee.amount, get_global_properties().parameters.cashback_vesting_threshold );
561  } );
562  deferred_fee -= core_cancel_fee.amount;
563  // handle originally paid fee if any:
564  // to_deduct = round_up( paid_fee * core_cancel_fee / deferred_core_fee_before_deduct )
565  if( deferred_paid_fee.amount == 0 )
566  {
567  vop.fee = core_cancel_fee;
568  }
569  else
570  {
571  fc::uint128_t fee128( deferred_paid_fee.amount.value );
572  fee128 *= core_cancel_fee.amount.value;
573  // to round up
574  fee128 += order.deferred_fee.value;
575  fee128 -= 1;
576  fee128 /= order.deferred_fee.value;
577  share_type cancel_fee_amount = static_cast<int64_t>(fee128);
578  // cancel_fee should be positive, pay it to asset's accumulated_fees
579  deferred_fee_asset_dyn_data = &deferred_paid_fee.asset_id(*this).dynamic_asset_data_id(*this);
580  modify( *deferred_fee_asset_dyn_data, [&cancel_fee_amount](asset_dynamic_data_object& addo) {
581  addo.accumulated_fees += cancel_fee_amount;
582  });
583  // cancel_fee should be no more than deferred_paid_fee
584  deferred_paid_fee.amount -= cancel_fee_amount;
585  vop.fee = asset( cancel_fee_amount, deferred_paid_fee.asset_id );
586  }
587  }
588  }
589  }
590 
591  // refund funds in order
592  auto refunded = order.amount_for_sale();
593  if( refunded.asset_id == asset_id_type() )
594  {
595  if( !seller_acc_stats )
596  seller_acc_stats = &get_account_stats_by_owner( order.seller );
597  modify( *seller_acc_stats, [&refunded]( account_statistics_object& obj ) {
598  obj.total_core_in_orders -= refunded.amount;
599  });
600  }
601  adjust_balance(order.seller, refunded);
602 
603  // refund fee
604  // could be virtual op or real op here
605  if( order.deferred_paid_fee.amount == 0 )
606  {
607  // be here, order.create_time <= HARDFORK_CORE_604_TIME, or fee paid in CORE, or no fee to refund.
608  // if order was created before hard fork 604 then cancelled no matter before or after hard fork 604,
609  // see it as fee paid in CORE, deferred_fee should be refunded to order owner but not fee pool
610  adjust_balance( order.seller, deferred_fee );
611  }
612  else // need to refund fee in originally paid asset
613  {
614  adjust_balance(order.seller, deferred_paid_fee);
615  // be here, must have: fee_asset != CORE
616  if( !deferred_fee_asset_dyn_data )
617  deferred_fee_asset_dyn_data = &deferred_paid_fee.asset_id(*this).dynamic_asset_data_id(*this);
618  modify( *deferred_fee_asset_dyn_data, [&deferred_fee](asset_dynamic_data_object& addo) {
619  addo.fee_pool += deferred_fee;
620  });
621  }
622 
623  if( create_virtual_op )
624  {
625  auto op_id = push_applied_operation( vop );
626  set_applied_operation_result( op_id, refunded );
627  }
628 
629  cleanup_and_remove_limit_order( order );
630 }
631 
632 void database::cleanup_and_remove_limit_order( const limit_order_object& order )
633 {
634  // Unlink the linked take profit order if it exists
635  if( order.take_profit_order_id.valid() )
636  {
637  const auto& take_profit_order = (*order.take_profit_order_id)(*this);
638  modify( take_profit_order, []( limit_order_object& loo ) {
640  });
641  }
642 
643  remove(order);
644 }
645 
647 {
658  if( order.amount_to_receive().amount == 0 )
659  {
660  if( order.deferred_fee > 0 && db.head_block_time() <= HARDFORK_CORE_604_TIME )
661  {
662  db.cancel_limit_order( order, true, true );
663  }
664  else
665  db.cancel_limit_order( order );
666  return true;
667  }
668  return false;
669 }
670 
671 // Note: optimizations have been done in apply_order(...)
673 {
674  auto order_id = new_order_object.id;
675  const asset_object& sell_asset = get(new_order_object.amount_for_sale().asset_id);
676  const asset_object& receive_asset = get(new_order_object.amount_to_receive().asset_id);
677 
678  // Possible optimization: We only need to check calls if both are true:
679  // - The new order is at the front of the book
680  // - The new order is below the call limit price
681  bool called_some = check_call_orders(sell_asset, true, true); // the first time when checking, call order is maker
682  bool called_some_else = check_call_orders(receive_asset, true, true); // the other side, same as above
683  if( ( called_some || called_some_else ) && !find_object(order_id) ) // then we were filled by call order
684  return true;
685 
686  const auto& limit_price_idx = get_index_type<limit_order_index>().indices().get<by_price>();
687 
688  // it should be possible to simply check the NEXT/PREV iterator after new_order_object to
689  // determine whether or not this order has "changed the book" in a way that requires us to
690  // check orders. For now I just lookup the lower bound and check for equality... this is log(n) vs
691  // constant time check. Potential optimization.
692 
693  auto max_price = ~new_order_object.sell_price;
694  auto limit_itr = limit_price_idx.lower_bound(max_price.max());
695  auto limit_end = limit_price_idx.upper_bound(max_price);
696 
697  bool finished = false;
698  while( !finished && limit_itr != limit_end )
699  {
700  auto old_limit_itr = limit_itr;
701  ++limit_itr;
702  // match returns 2 when only the old order was fully filled. In this case, we keep matching; otherwise, we stop.
703  finished = ( match(new_order_object, *old_limit_itr, old_limit_itr->sell_price)
705  }
706 
707  // Possible optimization: only check calls if the new order completely filled some old order.
708  // Do I need to check both assets?
709  check_call_orders(sell_asset); // after the new limit order filled some orders on the book,
710  // if a call order matches another order, the call order is taker
711  check_call_orders(receive_asset); // the other side, same as above
712 
713  const limit_order_object* updated_order_object = find< limit_order_object >( order_id );
714  if( !updated_order_object )
715  return true;
716  if( head_block_time() <= HARDFORK_555_TIME )
717  return false;
718  // before #555 we would have done maybe_cull_small_order() logic as a result of fill_order()
719  // being called by match() above
720  // however after #555 we need to get rid of small orders -- #555 hardfork defers logic that
721  // was done too eagerly before, and
722  // this is the point it's deferred to.
723  return maybe_cull_small_order( *this, *updated_order_object );
724 }
725 
726 /***
727  * @brief apply a new limit_order_object to the market, matching with existing limit orders or
728  * margin call orders where possible, leaving remainder on the book if not fully matched.
729  * @detail Called from limit_order_create_evaluator::do_apply() in market_evaluator.cpp in
730  * response to a limit_order_create operation. If we're not at the front of the book, we
731  * return false early and do nothing else, since there's nothing we can match. If we are at
732  * the front of the book, then we first look for matching limit orders that are more
733  * favorable than the margin call price, then we search through active margin calls, then
734  * finaly the remaining limit orders, until we either fully consume the order or can no
735  * longer match and must leave the remainder on the book.
736  * @return Returns true if limit order is completely consumed by matching, else false if it
737  * remains on the book.
738  * @param new_order_object the new limit order (read only ref, though the corresponding db
739  * object is modified as we match and deleted if filled completely)
740  */
741 bool database::apply_order(const limit_order_object& new_order_object)
742 {
743  auto order_id = new_order_object.id;
744  asset_id_type sell_asset_id = new_order_object.sell_asset_id();
745  asset_id_type recv_asset_id = new_order_object.receive_asset_id();
746 
747  // We only need to check if the new order will match with others if it is at the front of the book
748  const auto& limit_price_idx = get_index_type<limit_order_index>().indices().get<by_price>();
749  auto limit_itr = limit_price_idx.iterator_to( new_order_object );
750  if( limit_itr != limit_price_idx.begin() )
751  {
752  --limit_itr;
753  if( limit_itr->sell_asset_id() == sell_asset_id && limit_itr->receive_asset_id() == recv_asset_id )
754  return false;
755  }
756 
757  // this is the opposite side (on the book)
758  auto max_price = ~new_order_object.sell_price;
759  limit_itr = limit_price_idx.lower_bound( max_price.max() );
760  auto limit_end = limit_price_idx.upper_bound( max_price );
761 
762  // Order matching should be in favor of the taker.
763  // When a new limit order is created, e.g. an ask, need to check if it will match the highest bid.
764  // We were checking call orders first. However, due to MSSR (maximum_short_squeeze_ratio),
765  // effective price of call orders may be worse than limit orders, so we should also check limit orders here.
766 
767  // Question: will a new limit order trigger a black swan event?
768  //
769  // 1. as of writing, it's possible due to the call-order-and-limit-order overlapping issue:
770  // https://github.com/bitshares/bitshares-core/issues/606 .
771  // when it happens, a call order can be very big but don't match with the opposite,
772  // even when price feed is too far away, further than swan price,
773  // if the new limit order is in the same direction with the call orders, it can eat up all the opposite,
774  // then the call order will lose support and trigger a black swan event.
775  // 2. after issue 606 is fixed, there will be no limit order on the opposite side "supporting" the call order,
776  // so a new order in the same direction with the call order won't trigger a black swan event.
777  // 3. calling is one direction. if the new limit order is on the opposite direction,
778  // no matter if matches with the call, it won't trigger a black swan event.
779  // (if a match at MSSP caused a black swan event, it means the call order is already undercollateralized,
780  // which should trigger a black swan event earlier.)
781  //
782  // Since it won't trigger a black swan, no need to check here.
783 
784  // currently we don't do cross-market (triangle) matching.
785  // the limit order will only match with a call order if meet all of these:
786  // 1. it's buying collateral, which means sell_asset is the MIA, receive_asset is the backing asset.
787  // 2. sell_asset is not a prediction market
788  // 3. sell_asset is not globally settled
789  // 4. sell_asset has a valid price feed
790  // 5. the call order's collateral ratio is below or equals to MCR
791  // 6. the limit order provided a good price
792 
794  bool before_core_hardfork_1270 = ( maint_time <= HARDFORK_CORE_1270_TIME ); // call price caching issue
795 
796  bool to_check_call_orders = false;
797  const asset_object& sell_asset = sell_asset_id( *this );
798  const asset_bitasset_data_object* sell_abd = nullptr;
799  price call_match_price; // Price at which margin calls sit on the books. Prior to BSIP-74 this price is
800  // same as the MSSP. After, it is the MCOP, which may deviate from MSSP due to MCFR.
801  price call_pays_price; // Price margin call actually relinquishes collateral at. Equals the MSSP and it may
802  // differ from call_match_price if there is a Margin Call Fee.
803  if( sell_asset.is_market_issued() )
804  {
805  sell_abd = &sell_asset.bitasset_data( *this );
806  if( sell_abd->options.short_backing_asset == recv_asset_id
807  && !sell_abd->is_prediction_market
808  && !sell_abd->is_globally_settled()
809  && !sell_abd->current_feed.settlement_price.is_null() )
810  {
811  if( before_core_hardfork_1270 ) {
812  call_match_price = ~sell_abd->current_feed.max_short_squeeze_price_before_hf_1270();
813  call_pays_price = call_match_price;
814  } else {
815  call_match_price = ~sell_abd->get_margin_call_order_price();
816  call_pays_price = ~sell_abd->current_feed.max_short_squeeze_price();
817  }
818  if( ~new_order_object.sell_price <= call_match_price ) // If new limit order price is good enough to
819  to_check_call_orders = true; // match a call, then check if there are calls.
820  }
821  }
822 
823  bool finished = false; // whether the new order is gone
824  bool feed_price_updated = false; // whether current_feed.settlement_price has been updated
825  if( to_check_call_orders )
826  {
827  // check limit orders first, match the ones with better price in comparison to call orders
828  auto limit_itr_after_call = limit_price_idx.lower_bound( call_match_price );
829  while( !finished && limit_itr != limit_itr_after_call )
830  {
831  const limit_order_object& matching_limit_order = *limit_itr;
832  ++limit_itr;
833  // match returns 2 when only the old order was fully filled.
834  // In this case, we keep matching; otherwise, we stop.
835  finished = ( match( new_order_object, matching_limit_order, matching_limit_order.sell_price )
837  }
838 
839  auto call_min = price::min( recv_asset_id, sell_asset_id );
840  if( !finished && !before_core_hardfork_1270 ) // TODO refactor or cleanup duplicate code after core-1270 hf
841  {
842  // check if there are margin calls
843  // Note: it is safe to iterate here even if there is no call order due to individual settlements
844  const auto& call_collateral_idx = get_index_type<call_order_index>().indices().get<by_collateral>();
845  // Note: when BSRM is no_settlement, current_feed can change after filled a call order,
846  // so we recalculate inside the loop
848  auto bsrm = sell_abd->get_black_swan_response_method();
849  bool update_call_price = ( bsrm_type::no_settlement == bsrm && sell_abd->is_current_feed_price_capped() );
850  auto old_current_feed_price = sell_abd->current_feed.settlement_price;
851  while( !finished )
852  {
853  // hard fork core-343 and core-625 took place at same time,
854  // always check call order with least collateral ratio
855  auto call_itr = call_collateral_idx.lower_bound( call_min );
856  if( call_itr == call_collateral_idx.end()
857  || call_itr->debt_type() != sell_asset_id
858  // feed protected https://github.com/cryptonomex/graphene/issues/436
859  || call_itr->collateralization() > sell_abd->current_maintenance_collateralization )
860  break;
861  // hard fork core-338 and core-625 took place at same time, not checking HARDFORK_CORE_338_TIME here.
862  const auto match_result = match( new_order_object, *call_itr, call_match_price,
863  *sell_abd, call_pays_price );
864  // match returns 1 or 3 when the new order was fully filled.
865  // In this case, we stop matching; otherwise keep matching.
866  // since match can return 0 due to BSIP38 (hf core-834), we no longer only check if the result is 2.
867  if( match_result_type::only_taker_filled == match_result
868  || match_result_type::both_filled == match_result )
869  finished = true;
870  else if( update_call_price )
871  {
872  call_match_price = ~sell_abd->get_margin_call_order_price();
873  call_pays_price = ~sell_abd->current_feed.max_short_squeeze_price();
874  update_call_price = sell_abd->is_current_feed_price_capped();
875  // Since current feed price (in debt/collateral) can only decrease after updated, if there still
876  // exists a call order in margin call territory, it would be on the top of the order book,
877  // so no need to check if the current limit (buy) order would match another limit (sell) order atm.
878  // On the other hand, the current limit order is on the top of the other side of the order book.
879  }
880  } // while !finished
881  if( bsrm_type::no_settlement == bsrm && sell_abd->current_feed.settlement_price != old_current_feed_price )
882  feed_price_updated = true;
883  } // if after core-1270 hf
884  else if( !finished ) // and before core-1270 hard fork
885  {
886  // check if there are margin calls
887  const auto& call_price_idx = get_index_type<call_order_index>().indices().get<by_price>();
888  while( !finished )
889  {
890  // assume hard fork core-343 and core-625 will take place at same time,
891  // always check call order with least call_price
892  auto call_itr = call_price_idx.lower_bound( call_min );
893  if( call_itr == call_price_idx.end()
894  || call_itr->debt_type() != sell_asset_id
895  // feed protected https://github.com/cryptonomex/graphene/issues/436
896  || call_itr->call_price > ~sell_abd->current_feed.settlement_price )
897  break;
898  // assume hard fork core-338 and core-625 will take place at same time,
899  // not checking HARDFORK_CORE_338_TIME here.
900  const auto match_result = match( new_order_object, *call_itr, call_match_price, *sell_abd );
901  // match returns 1 or 3 when the new order was fully filled.
902  // In this case, we stop matching; otherwise keep matching.
903  // since match can return 0 due to BSIP38 (hard fork core-834),
904  // we no longer only check if the result is 2.
905  if( match_result_type::only_taker_filled == match_result
906  || match_result_type::both_filled == match_result )
907  finished = true;
908  } // while !finished
909  } // if before core-1270 hf
910  } // if to check call
911 
912  // still need to check limit orders
913  while( !finished && limit_itr != limit_end )
914  {
915  const limit_order_object& matching_limit_order = *limit_itr;
916  ++limit_itr;
917  // match returns 2 when only the old order was fully filled. In this case, we keep matching; otherwise, we stop.
918  finished = ( match( new_order_object, matching_limit_order, matching_limit_order.sell_price )
920  }
921 
922  bool limit_order_is_gone = true;
923  const limit_order_object* updated_order_object = find< limit_order_object >( order_id );
924  if( updated_order_object )
925  // before #555 we would have done maybe_cull_small_order() logic as a result of fill_order()
926  // being called by match() above
927  // however after #555 we need to get rid of small orders -- #555 hardfork defers logic that
928  // was done too eagerly before, and
929  // this is the point it's deferred to.
930  limit_order_is_gone = maybe_cull_small_order( *this, *updated_order_object );
931 
932  if( limit_order_is_gone && feed_price_updated )
933  {
934  // If current_feed got updated, and the new limit order is gone,
935  // it is possible that other limit orders are able to get filled,
936  // so we need to call check_call_orders()
937  check_call_orders( sell_asset, true, false, sell_abd );
938  }
939 
940  return limit_order_is_gone;
941 }
942 
944  const asset_bitasset_data_object& bitasset,
945  const asset_object& asset_obj )
946 {
947  // Defensive checks
949  // GCOVR_EXCL_START
950  // Defensive code, normally none of these should fail
951  FC_ASSERT( HARDFORK_CORE_2481_PASSED( maint_time ), "Internal error: hard fork core-2481 not passed" );
952  FC_ASSERT( new_settlement.balance.asset_id == bitasset.asset_id, "Internal error: asset type mismatch" );
953  FC_ASSERT( !bitasset.is_prediction_market, "Internal error: asset is a prediction market" );
954  FC_ASSERT( !bitasset.is_globally_settled(), "Internal error: asset is globally settled already" );
955  FC_ASSERT( !bitasset.current_feed.settlement_price.is_null(), "Internal error: no sufficient price feeds" );
956  // GCOVR_EXCL_STOP
957 
958  auto head_time = head_block_time();
959  bool after_core_hardfork_2582 = HARDFORK_CORE_2582_PASSED( head_time ); // Price feed issues
960 
961  auto new_obj_id = new_settlement.id;
962 
963  // Price at which margin calls sit on the books.
964  // It is the MCOP, which may deviate from MSSP due to MCFR.
965  price call_match_price = bitasset.get_margin_call_order_price();
966  // Price margin call actually relinquishes collateral at. Equals the MSSP and it may
967  // differ from call_match_price if there is a Margin Call Fee.
968  price call_pays_price = bitasset.current_feed.max_short_squeeze_price();
969 
970  // Note: when BSRM is no_settlement, current_feed can change after filled a call order,
971  // so we recalculate inside the loop
973  auto bsrm = bitasset.get_black_swan_response_method();
974  bool update_call_price = ( bsrm_type::no_settlement == bsrm && bitasset.is_current_feed_price_capped() );
975 
976  bool finished = false; // whether the new order is gone
977 
978  // check if there are margin calls
979  // Note: it is safe to iterate here even if there is no call order due to individual settlements
980  const auto& call_collateral_idx = get_index_type<call_order_index>().indices().get<by_collateral>();
981  auto call_min = price::min( bitasset.options.short_backing_asset, new_settlement.balance.asset_id );
982  while( !finished )
983  {
984  // always check call order with the least collateral ratio
985  auto call_itr = call_collateral_idx.lower_bound( call_min );
986  // Note: we don't precalculate an iterator with upper_bound() before entering the loop,
987  // because the upper bound can change after a call order got filled
988  if( call_itr == call_collateral_idx.end()
989  || call_itr->debt_type() != new_settlement.balance.asset_id
990  // feed protected https://github.com/cryptonomex/graphene/issues/436
991  || call_itr->collateralization() > bitasset.current_maintenance_collateralization )
992  break;
993  // TCR applies here
994  auto settle_price = after_core_hardfork_2582 ? bitasset.median_feed.settlement_price
995  : bitasset.current_feed.settlement_price;
996  asset max_debt_to_cover( call_itr->get_max_debt_to_cover( call_pays_price,
997  settle_price,
1000  new_settlement.balance.asset_id );
1001 
1002  match( new_settlement, *call_itr, call_pays_price, bitasset, max_debt_to_cover, call_match_price, true );
1003 
1004  // Check whether the new order is gone
1005  finished = ( nullptr == find_object( new_obj_id ) );
1006 
1007  if( update_call_price )
1008  {
1009  // when current_feed is updated, it is possible that there are limit orders able to get filled,
1010  // so we need to call check_call_orders(), but skip matching call orders with force settlements
1011  check_call_orders( asset_obj, true, false, &bitasset, false, true );
1012  if( !finished )
1013  {
1014  call_match_price = bitasset.get_margin_call_order_price();
1015  call_pays_price = bitasset.current_feed.max_short_squeeze_price();
1016  update_call_price = bitasset.is_current_feed_price_capped();
1017  }
1018  }
1019  }
1020 
1021 }
1022 
1024 static database::match_result_type get_match_result( bool taker_filled, bool maker_filled )
1025 {
1026  int8_t result = 0;
1027  if( maker_filled )
1028  result += static_cast<int8_t>( database::match_result_type::only_maker_filled );
1029  if( taker_filled )
1030  result += static_cast<int8_t>( database::match_result_type::only_taker_filled );
1031  return static_cast<database::match_result_type>( result );
1032 }
1033 
1039 database::match_result_type database::match( const limit_order_object& taker, const limit_order_object& maker,
1040  const price& match_price )
1041 {
1042  // GCOVR_EXCL_START
1043  // Defensive code, normally none of these should fail
1044  FC_ASSERT( taker.sell_price.quote.asset_id == maker.sell_price.base.asset_id );
1045  FC_ASSERT( taker.sell_price.base.asset_id == maker.sell_price.quote.asset_id );
1046  FC_ASSERT( taker.for_sale > 0 && maker.for_sale > 0 );
1047  // GCOVR_EXCL_STOP
1048 
1049  return maker.is_settled_debt ? match_limit_settled_debt( taker, maker, match_price )
1050  : match_limit_normal_limit( taker, maker, match_price );
1051 }
1052 
1054 database::match_result_type database::match_limit_normal_limit( const limit_order_object& taker,
1055  const limit_order_object& maker, const price& match_price )
1056 {
1057  // GCOVR_EXCL_START
1058  // Defensive code, normally none of these should fail
1059  FC_ASSERT( !maker.is_settled_debt, "Internal error: maker is settled debt" );
1060  FC_ASSERT( !taker.is_settled_debt, "Internal error: taker is settled debt" );
1061  // GCOVR_EXCL_STOP
1062 
1063  auto taker_for_sale = taker.amount_for_sale();
1064  auto maker_for_sale = maker.amount_for_sale();
1065 
1066  asset taker_pays;
1067  asset taker_receives;
1068  asset maker_pays;
1069  asset maker_receives;
1070 
1072  bool before_core_hardfork_342 = ( maint_time <= HARDFORK_CORE_342_TIME ); // better rounding
1073 
1074  bool cull_taker = false;
1075  if( taker_for_sale <= ( maker_for_sale * match_price ) ) // rounding down here should be fine
1076  {
1077  taker_receives = taker_for_sale * match_price; // round down, in favor of bigger order
1078 
1079  // Be here, it's possible that taker is paying something for nothing due to partially filled in last loop.
1080  // In this case, we see it as filled and cancel it later
1081  if( taker_receives.amount == 0 && maint_time > HARDFORK_CORE_184_TIME )
1083 
1084  if( before_core_hardfork_342 )
1085  maker_receives = taker_for_sale;
1086  else
1087  {
1088  // The remaining amount in order `taker` would be too small,
1089  // so we should cull the order in fill_limit_order() below.
1090  // The order would receive 0 even at `match_price`, so it would receive 0 at its own price,
1091  // so calling maybe_cull_small() will always cull it.
1092  maker_receives = taker_receives.multiply_and_round_up( match_price );
1093  cull_taker = true;
1094  }
1095  }
1096  else
1097  {
1098  //This line once read: assert( maker_for_sale < taker_for_sale * match_price ); // check
1099  //This assert is not always true -- see trade_amount_equals_zero in operation_tests.cpp
1100  //Although taker_for_sale is greater than maker_for_sale * match_price,
1101  // maker_for_sale == taker_for_sale * match_price
1102  //Removing the assert seems to be safe -- apparently no asset is created or destroyed.
1103 
1104  // The maker won't be paying something for nothing, since if it would, it would have been cancelled already.
1105  maker_receives = maker_for_sale * match_price; // round down, in favor of bigger order
1106  if( before_core_hardfork_342 )
1107  taker_receives = maker_for_sale;
1108  else
1109  // The remaining amount in order `maker` would be too small,
1110  // so the order will be culled in fill_limit_order() below
1111  taker_receives = maker_receives.multiply_and_round_up( match_price );
1112  }
1113 
1114  maker_pays = taker_receives;
1115  taker_pays = maker_receives;
1116 
1117  if( before_core_hardfork_342 )
1118  FC_ASSERT( taker_pays == taker.amount_for_sale() ||
1119  maker_pays == maker.amount_for_sale() );
1120 
1121  // the first param of match() is taker
1122  bool taker_filled = fill_limit_order( taker, taker_pays, taker_receives, cull_taker, match_price, false );
1123  // the second param of match() is maker
1124  bool maker_filled = fill_limit_order( maker, maker_pays, maker_receives, true, match_price, true );
1125 
1126  match_result_type result = get_match_result( taker_filled, maker_filled );
1128  return result;
1129 }
1130 
1132 database::match_result_type database::match_limit_settled_debt( const limit_order_object& taker,
1133  const limit_order_object& maker, const price& match_price )
1134 {
1135  // GCOVR_EXCL_START
1136  // Defensive code, normally none of these should fail
1137  FC_ASSERT( maker.is_settled_debt, "Internal error: maker is not settled debt" );
1138  FC_ASSERT( !taker.is_settled_debt, "Internal error: taker is settled debt" );
1139  // GCOVR_EXCL_STOP
1140 
1141  bool cull_taker = false;
1142  bool maker_filled = false;
1143 
1144  const auto& mia = maker.receive_asset_id()(*this);
1145  const auto& bitasset = mia.bitasset_data(*this);
1146 
1147  auto usd_for_sale = taker.amount_for_sale();
1148  auto usd_to_buy = asset( bitasset.individual_settlement_debt, maker.receive_asset_id() );
1149 
1150  asset call_receives;
1151  asset order_receives;
1152  if( usd_to_buy > usd_for_sale )
1153  { // fill taker limit order
1154  order_receives = usd_for_sale * match_price; // round down here, in favor of "call order"
1155 
1156  // Be here, it's possible that taker is paying something for nothing due to partially filled in last loop.
1157  // In this case, we see it as filled and cancel it later
1158  if( order_receives.amount == 0 )
1160 
1161  // The remaining amount in the limit order could be too small,
1162  // so we should cull the order in fill_limit_order() below.
1163  // If the order would receive 0 even at `match_price`, it would receive 0 at its own price,
1164  // so calling maybe_cull_small() will always cull it.
1165  call_receives = order_receives.multiply_and_round_up( match_price );
1166  cull_taker = true;
1167  }
1168  else
1169  { // fill maker "call order"
1170  call_receives = usd_to_buy;
1171  order_receives = maker.amount_for_sale();
1172  maker_filled = true;
1173  }
1174 
1175  // seller, pays, receives, ...
1176  bool taker_filled = fill_limit_order( taker, call_receives, order_receives, cull_taker, match_price, false );
1177 
1178  const auto& head_time = head_block_time();
1179  bool after_core_hardfork_2591 = HARDFORK_CORE_2591_PASSED( head_time ); // Tighter peg (fill debt order at MCOP)
1180 
1181  asset call_pays = order_receives;
1182  if( maker_filled ) // Regardless of hf core-2591
1183  call_pays.amount = bitasset.individual_settlement_fund;
1184  else if( maker.for_sale != bitasset.individual_settlement_fund ) // implies hf core-2591
1185  call_pays = call_receives * bitasset.get_individual_settlement_price(); // round down, in favor of "call order"
1186  if( call_pays < order_receives ) // be defensive, maybe unnecessary
1187  { // GCOVR_EXCL_START
1188  wlog( "Unexpected scene: call_pays < order_receives" );
1189  call_pays = order_receives;
1190  } // GCOVR_EXCL_STOP
1191  asset collateral_fee = call_pays - order_receives;
1192 
1193  // Reduce current supply, and accumulate collateral fees
1194  const asset_dynamic_data_object& mia_ddo = mia.dynamic_asset_data_id(*this);
1195  modify( mia_ddo, [&call_receives,&collateral_fee]( asset_dynamic_data_object& ao ){
1196  ao.current_supply -= call_receives.amount;
1197  ao.accumulated_collateral_fees += collateral_fee.amount;
1198  });
1199 
1200  // Push fill_order vitual operation
1201  // id, seller, pays, receives, ...
1202  push_applied_operation( fill_order_operation( maker.id, maker.seller, call_pays, call_receives,
1203  collateral_fee, match_price, true ) );
1204 
1205  // Update bitasset data
1206  modify( bitasset, [&call_receives,&call_pays]( asset_bitasset_data_object& obj ){
1207  obj.individual_settlement_debt -= call_receives.amount;
1208  obj.individual_settlement_fund -= call_pays.amount;
1209  });
1210 
1211  // Update the maker order
1212  // Note: CORE asset in settled debt is not counted in account_stats.total_core_in_orders
1213  if( maker_filled )
1214  remove( maker );
1215  else
1216  {
1217  modify( maker, [after_core_hardfork_2591,&bitasset]( limit_order_object& obj ) {
1218  if( after_core_hardfork_2591 )
1219  {
1220  // Note: for simplicity, only update price when necessary
1221  asset settled_debt( bitasset.individual_settlement_debt, obj.receive_asset_id() );
1222  obj.for_sale = settled_debt.multiply_and_round_up( obj.sell_price ).amount;
1223  if( obj.for_sale > bitasset.individual_settlement_fund ) // be defensive, maybe unnecessary
1224  { // GCOVR_EXCL_START
1225  wlog( "Unexpected scene: obj.for_sale > bitasset.individual_settlement_fund" );
1226  obj.for_sale = bitasset.individual_settlement_fund;
1227  obj.sell_price = ~bitasset.get_individual_settlement_price();
1228  } // GCOVR_EXCL_STOP
1229  }
1230  else
1231  {
1232  obj.for_sale = bitasset.individual_settlement_fund;
1233  obj.sell_price = ~bitasset.get_individual_settlement_price();
1234  }
1235  // Note: filled_amount is not updated, but it should be fine
1236  });
1237  // Note:
1238  // After the price is updated, it is possible that the order can be matched with another order on the order
1239  // book, which may then be matched with more other orders. For simplicity, we don't do more matching here.
1240  }
1241 
1242  match_result_type result = get_match_result( taker_filled, maker_filled );
1243  return result;
1244 }
1245 
1247 // TODO fix duplicate code
1248 database::match_result_type database::match_settled_debt_limit( const limit_order_object& taker,
1249  const limit_order_object& maker, const price& match_price )
1250 {
1251  // GCOVR_EXCL_START
1252  // Defensive code, normally none of these should fail
1253  FC_ASSERT( !maker.is_settled_debt, "Internal error: maker is settled debt" );
1254  FC_ASSERT( taker.is_settled_debt, "Internal error: taker is not settled debt" );
1255  // GCOVR_EXCL_STOP
1256 
1257  bool taker_filled = false;
1258 
1259  const auto& mia = taker.receive_asset_id()(*this);
1260  const auto& bitasset = mia.bitasset_data(*this);
1261 
1262  auto usd_for_sale = maker.amount_for_sale();
1263  auto usd_to_buy = asset( bitasset.individual_settlement_debt, taker.receive_asset_id() );
1264 
1265  asset call_receives;
1266  asset order_receives;
1267  if( usd_to_buy > usd_for_sale )
1268  { // fill maker limit order
1269  order_receives = usd_for_sale * match_price; // round down here, in favor of call order
1270 
1271  // Be here, the limit order won't be paying something for nothing, since if it would, it would have
1272  // been cancelled elsewhere already (a maker limit order won't be paying something for nothing).
1273 
1274  call_receives = order_receives.multiply_and_round_up( match_price );
1275  }
1276  else
1277  { // fill taker "call order"
1278  call_receives = usd_to_buy;
1279  order_receives = call_receives.multiply_and_round_up( match_price ); // round up here, in favor of limit order
1280  taker_filled = true;
1281  }
1282 
1283  asset call_pays = order_receives;
1284  if( taker_filled )
1285  call_pays.amount = bitasset.individual_settlement_fund;
1286  else if( taker.for_sale != bitasset.individual_settlement_fund )
1287  call_pays = call_receives * bitasset.get_individual_settlement_price(); // round down, in favor of "call order"
1288  if( call_pays < order_receives ) // be defensive, maybe unnecessary
1289  { // GCOVR_EXCL_START
1290  wlog( "Unexpected scene: call_pays < order_receives" );
1291  call_pays = order_receives;
1292  } // GCOVR_EXCL_STOP
1293  asset collateral_fee = call_pays - order_receives;
1294 
1295  // Reduce current supply, and accumulate collateral fees
1296  const asset_dynamic_data_object& mia_ddo = mia.dynamic_asset_data_id(*this);
1297  modify( mia_ddo, [&call_receives,&collateral_fee]( asset_dynamic_data_object& ao ){
1298  ao.current_supply -= call_receives.amount;
1299  ao.accumulated_collateral_fees += collateral_fee.amount;
1300  });
1301 
1302  // Push fill_order vitual operation
1303  // id, seller, pays, receives, ...
1304  push_applied_operation( fill_order_operation( taker.id, taker.seller, call_pays, call_receives,
1305  collateral_fee, match_price, false ) );
1306 
1307  // Update bitasset data
1308  modify( bitasset, [&call_receives,&call_pays]( asset_bitasset_data_object& obj ){
1309  obj.individual_settlement_debt -= call_receives.amount;
1310  obj.individual_settlement_fund -= call_pays.amount;
1311  });
1312 
1313  // Update the taker order
1314  // Note: CORE asset in settled debt is not counted in account_stats.total_core_in_orders
1315  if( taker_filled )
1316  remove( taker );
1317  else
1318  {
1319  modify( taker, [&bitasset]( limit_order_object& obj ) {
1320  // Note: for simplicity, only update price when necessary
1321  asset settled_debt( bitasset.individual_settlement_debt, obj.receive_asset_id() );
1322  obj.for_sale = settled_debt.multiply_and_round_up( obj.sell_price ).amount;
1323  if( obj.for_sale > bitasset.individual_settlement_fund ) // be defensive, maybe unnecessary
1324  { // GCOVR_EXCL_START
1325  wlog( "Unexpected scene: obj.for_sale > bitasset.individual_settlement_fund" );
1326  obj.for_sale = bitasset.individual_settlement_fund;
1327  obj.sell_price = ~bitasset.get_individual_settlement_price();
1328  } // GCOVR_EXCL_STOP
1329  // Note: filled_amount is not updated, but it should be fine
1330  });
1331  }
1332 
1333  // seller, pays, receives, ...
1334  bool maker_filled = fill_limit_order( maker, call_receives, order_receives, true, match_price, true );
1335 
1336  match_result_type result = get_match_result( taker_filled, maker_filled );
1337  return result;
1338 }
1339 
1340 
1341 database::match_result_type database::match( const limit_order_object& bid, const call_order_object& ask,
1342  const price& match_price,
1343  const asset_bitasset_data_object& bitasset,
1344  const price& call_pays_price )
1345 {
1346  FC_ASSERT( bid.sell_asset_id() == ask.debt_type() );
1347  FC_ASSERT( bid.receive_asset_id() == ask.collateral_type() );
1348  FC_ASSERT( bid.for_sale > 0 && ask.debt > 0 && ask.collateral > 0 );
1349 
1350  bool cull_taker = false;
1351 
1353  bool before_core_hardfork_1270 = ( maint_time <= HARDFORK_CORE_1270_TIME ); // call price caching issue
1354  bool after_core_hardfork_2481 = HARDFORK_CORE_2481_PASSED( maint_time ); // Match settle orders with margin calls
1355 
1356  auto head_time = head_block_time();
1357  bool after_core_hardfork_2582 = HARDFORK_CORE_2582_PASSED( head_time ); // Price feed issues
1358 
1359  const auto& feed_price = after_core_hardfork_2582 ? bitasset.median_feed.settlement_price
1360  : bitasset.current_feed.settlement_price;
1361  const auto& maintenance_collateral_ratio = bitasset.current_feed.maintenance_collateral_ratio;
1362  optional<price> maintenance_collateralization;
1363  if( !before_core_hardfork_1270 )
1364  maintenance_collateralization = bitasset.current_maintenance_collateralization;
1365 
1366  asset usd_for_sale = bid.amount_for_sale();
1367  asset usd_to_buy( ask.get_max_debt_to_cover( call_pays_price, feed_price, maintenance_collateral_ratio,
1368  maintenance_collateralization ),
1369  ask.debt_type() );
1370 
1371  asset call_pays;
1372  asset call_receives;
1373  asset order_pays;
1374  asset order_receives;
1375  if( usd_to_buy > usd_for_sale )
1376  { // fill limit order
1377  order_receives = usd_for_sale * match_price; // round down here, in favor of call order
1378 
1379  // Be here, it's possible that taker is paying something for nothing due to partially filled in last loop.
1380  // In this case, we see it as filled and cancel it later
1381  if( order_receives.amount == 0 )
1383 
1384  call_receives = order_receives.multiply_and_round_up( match_price );
1385  if( after_core_hardfork_2481 )
1386  call_pays = call_receives * call_pays_price; // calculate with updated call_receives
1387  else
1388  // TODO add tests about CR change
1389  call_pays = usd_for_sale * call_pays_price; // (same as match_price until BSIP-74)
1390 
1391  // The remaining amount (if any) in the limit order would be too small,
1392  // so we should cull the order in fill_limit_order() below.
1393  // The order would receive 0 even at `match_price`, so it would receive 0 at its own price,
1394  // so calling maybe_cull_small() will always cull it.
1395  cull_taker = true;
1396  }
1397  else
1398  { // fill call order
1399  call_receives = usd_to_buy;
1400  order_receives = usd_to_buy.multiply_and_round_up( match_price ); // round up here, in favor of limit order
1401  call_pays = usd_to_buy.multiply_and_round_up( call_pays_price );
1402  // Note: here we don't re-assign call_receives with (orders_receives * match_price) to receive more
1403  // debt asset, it means the call order could be receiving a bit too much less than its value.
1404  // It is a sad thing for the call order, but it is the rule -- when a call order is margin called,
1405  // it does not get more than it borrowed.
1406  // On the other hand, if the call order is not being closed (due to TCR),
1407  // it means get_max_debt_to_cover() did not return a perfect result, probably we can improve it.
1408  }
1409  order_pays = call_receives;
1410 
1411  // Compute margin call fee (BSIP74). Difference between what the call order pays and the limit order
1412  // receives is the margin call fee that is paid by the call order owner to the asset issuer.
1413  // Margin call fee should equal = X*MCFR/settle_price, to within rounding error.
1414  FC_ASSERT(call_pays >= order_receives);
1415  const asset margin_call_fee = call_pays - order_receives;
1416 
1417  bool taker_filled = fill_limit_order( bid, order_pays, order_receives, cull_taker, match_price, false );
1418  bool maker_filled = fill_call_order( ask, call_pays, call_receives, match_price, true, margin_call_fee );
1419 
1420  // Update current_feed after filled call order if needed
1421  if( bitasset_options::black_swan_response_type::no_settlement == bitasset.get_black_swan_response_method() )
1422  update_bitasset_current_feed( bitasset, true );
1423 
1424  // Note: result can be none_filled when call order has target_collateral_ratio option set.
1425  match_result_type result = get_match_result( taker_filled, maker_filled );
1426  return result;
1427 }
1428 
1429 
1430 asset database::match( const force_settlement_object& settle,
1431  const call_order_object& call,
1432  const price& match_price,
1433  const asset_bitasset_data_object& bitasset,
1434  const asset& max_settlement,
1435  const price& fill_price,
1436  bool is_margin_call )
1437 {
1438  return match_impl( settle, call, match_price, bitasset, max_settlement, fill_price, is_margin_call, true );
1439 }
1440 
1441 asset database::match( const call_order_object& call,
1442  const force_settlement_object& settle,
1443  const price& match_price,
1444  const asset_bitasset_data_object& bitasset,
1445  const asset& max_settlement,
1446  const price& fill_price )
1447 {
1448  return match_impl( settle, call, match_price, bitasset, max_settlement, fill_price, true, false );
1449 }
1450 
1451 asset database::match_impl( const force_settlement_object& settle,
1452  const call_order_object& call,
1453  const price& p_match_price,
1454  const asset_bitasset_data_object& bitasset,
1455  const asset& max_settlement,
1456  const price& p_fill_price,
1457  bool is_margin_call,
1458  bool settle_is_taker )
1459 { try {
1460  FC_ASSERT(call.get_debt().asset_id == settle.balance.asset_id );
1461  FC_ASSERT(call.debt > 0 && call.collateral > 0 && settle.balance.amount > 0);
1462 
1464  bool before_core_hardfork_342 = ( maint_time <= HARDFORK_CORE_342_TIME ); // better rounding
1465 
1466  auto settle_for_sale = std::min(settle.balance, max_settlement);
1467  auto call_debt = call.get_debt();
1468  auto call_collateral = call.get_collateral();
1469 
1470  price match_price = p_match_price;
1471  price fill_price = p_fill_price;
1472 
1473  asset call_receives = std::min(settle_for_sale, call_debt);
1474  asset call_pays = call_receives * match_price; // round down here, in favor of call order, for first check
1475  // TODO possible optimization: check need to round up
1476  // or down first
1477 
1478  // Note: when is_margin_call == true, the call order is being margin called,
1479  // match_price is the price that the call order pays,
1480  // fill_price is the price that the settle order receives,
1481  // the difference is the margin-call fee
1482 
1483  asset settle_receives = call_pays;
1484  asset settle_pays = call_receives;
1485 
1486  // Be here, the call order may be paying nothing.
1487  bool cull_settle_order = false; // whether need to cancel dust settle order
1488  if( maint_time > HARDFORK_CORE_184_TIME && call_pays.amount == 0 )
1489  {
1490  if( call_receives == call_debt ) // the call order is smaller than or equal to the settle order
1491  {
1492  call_pays.amount = 1;
1493  settle_receives.amount = 1; // Note: no margin-call fee in this case even if is_margin_call
1494  }
1495  else if( call_receives == settle.balance ) // the settle order is smaller
1496  {
1497  cancel_settle_order( settle );
1498  // If the settle order is canceled, we just return, since nothing else can be done
1499  return asset( 0, call_debt.asset_id );
1500  }
1501  // be here, neither order will be completely filled, perhaps due to max_settlement too small
1502  else if( !is_margin_call )
1503  {
1504  // If the call order is not being margin called, we simply return and continue outside
1505  return asset( 0, call_debt.asset_id );
1506  }
1507  else
1508  {
1509  // Be here, the call order is being margin called, and it is not being fully covered due to TCR,
1510  // and the settle order is big enough.
1511  // So the call order is considered as the smaller one, and we should round up call_pays.
1512  // We have ( call_receives == max_settlement == call_order.get_max_debt_to_cover() ).
1513  // It is guaranteed by call_order.get_max_debt_to_cover() that rounding up call_pays
1514  // would not reduce CR of the call order, but would push it to be above MCR.
1515  call_pays.amount = 1;
1516  settle_receives.amount = 1; // Note: no margin-call fee in this case
1517  }
1518  } // end : if after the core-184 hf and call_pays.amount == 0
1519  else if( !before_core_hardfork_342 && call_pays.amount != 0 )
1520  {
1521  auto margin_call_pays_ratio = bitasset.get_margin_call_pays_ratio();
1522  // be here, the call order is not paying nothing,
1523  // but it is still possible that the settle order is paying more than minimum required due to rounding
1524  if( call_receives == call_debt ) // the call order is smaller than or equal to the settle order
1525  {
1526  call_pays = call_receives.multiply_and_round_up( match_price ); // round up here, in favor of settle order
1527  if( is_margin_call ) // implies hf core-2481
1528  {
1529  if( call_pays.amount > call.collateral ) // CR too low
1530  {
1531  call_pays.amount = call.collateral;
1532  match_price = call_debt / call_collateral;
1533  fill_price = match_price / margin_call_pays_ratio;
1534  }
1535  settle_receives = call_receives.multiply_and_round_up( fill_price );
1536  }
1537  else // be here, we should have: call_pays <= call_collateral
1538  {
1539  settle_receives = call_pays; // Note: fill_price is not used in calculation when is_margin_call is false
1540  }
1541  }
1542  else // the call order is not completely filled, due to max_settlement too small or settle order too small
1543  {
1544  // be here, call_pays has been rounded down
1545  if( !is_margin_call )
1546  {
1547  // it was correct to round down call_pays.
1548  // round up here to mitigate rounding issues (hf core-342).
1549  // It is important to understand the math that the newly rounded-up call_receives won't be greater than
1550  // the old call_receives. And rounding up here would NOT make CR lower.
1551  call_receives = call_pays.multiply_and_round_up( match_price );
1552  }
1553  // the call order is a margin call, implies hf core-2481
1554  else if( settle_pays == max_settlement ) // the settle order is larger, but the call order has TCR
1555  {
1556  // Note: here settle_pays == call_receives
1557  call_pays = call_receives.multiply_and_round_up( match_price ); // round up, in favor of settle order
1558  settle_receives = call_receives.multiply_and_round_up( fill_price ); // round up
1559  // Note: here we do NOT stabilize call_receives since it is done in get_max_debt_to_cover(),
1560  // and it is already the maximum value
1561  }
1562  else // the call order is a margin call, and the settle order is smaller
1563  {
1564  // It was correct to round down call_pays. However, it is not the final result.
1565  // For margin calls, due to margin call fee, it is fairer to calculate with fill_price first
1566  const auto& calculate = [&settle_receives,&settle_pays,&fill_price,&call_receives,&call_pays,&match_price]
1567  {
1568  settle_receives = settle_pays * fill_price; // round down here, in favor of call order
1569  if( settle_receives.amount != 0 )
1570  {
1571  // round up to mitigate rounding issues (hf core-342)
1572  call_receives = settle_receives.multiply_and_round_up( fill_price );
1573  // round down
1574  call_pays = call_receives * match_price;
1575  }
1576  };
1577 
1578  calculate();
1579  if( settle_receives.amount == 0 )
1580  {
1581  cancel_settle_order( settle );
1582  // If the settle order is canceled, we just return, since nothing else can be done
1583  return asset( 0, call_debt.asset_id );
1584  }
1585 
1586  // check whether the call order can be filled at match_price
1587  bool cap_price = false;
1588  if( call_pays.amount >= call.collateral ) // CR too low, normally won't be true, just be defensive here
1589  cap_price = true;
1590  else
1591  {
1592  auto new_collateral = call_collateral - call_pays;
1593  auto new_debt = call_debt - call_receives; // the result is positive due to math
1594  if( ( new_collateral / new_debt ) < call.collateralization() ) // if CR would decrease
1595  cap_price = true;
1596  }
1597 
1598  if( cap_price ) // match_price is not good, update match price and fill price, then calculate again
1599  {
1600  match_price = call_debt / call_collateral;
1601  fill_price = match_price / margin_call_pays_ratio;
1602  calculate();
1603  if( settle_receives.amount == 0 )
1604  {
1605  // Note: when it is a margin call, max_settlement is max_debt_to_cover.
1606  // if need to cap price here, max_debt_to_cover should be equal to call_debt.
1607  // if call pays 0, it means the settle order is really small.
1608  cancel_settle_order( settle );
1609  // If the settle order is canceled, we just return, since nothing else can be done
1610  return asset( 0, call_debt.asset_id );
1611  }
1612  }
1613  } // end : if is_margin_call, else ...
1614 
1615  // be here, we should have: call_pays <= call_collateral
1616 
1617  // if the settle order is too small, mark it to be culled
1618  if( settle_pays == settle.balance && call_receives != settle.balance )
1619  cull_settle_order = true;
1620  // else do nothing, since we can't cull the settle order, or it is already fully filled
1621 
1622  settle_pays = call_receives;
1623  }
1624  } // end : if after the core-342 hf and call_pays.amount != 0
1625  // else : before the core-184 hf or the core-342 hf, do nothing
1626 
1634  if( before_core_hardfork_342 )
1635  {
1636  GRAPHENE_ASSERT( call_pays < call_collateral, black_swan_exception, "" );
1637 
1638  assert( settle_pays == settle_for_sale || call_receives == call.get_debt() );
1639  }
1640  // else do nothing, since black swan event won't happen, and the assertion is no longer true
1641 
1642  asset margin_call_fee = call_pays - settle_receives;
1643 
1644  fill_call_order( call, call_pays, call_receives, fill_price, settle_is_taker, margin_call_fee );
1645  // do not pay force-settlement fee if the call is being margin called
1646  fill_settle_order( settle, settle_pays, settle_receives, fill_price, !settle_is_taker, !is_margin_call );
1647 
1648  // Update current_feed after filled call order if needed
1649  if( bitasset_options::black_swan_response_type::no_settlement == bitasset.get_black_swan_response_method() )
1650  update_bitasset_current_feed( bitasset, true );
1651 
1652  if( cull_settle_order )
1653  cancel_settle_order( settle );
1654 
1655  return call_receives;
1656 } FC_CAPTURE_AND_RETHROW( (p_match_price)(max_settlement)(p_fill_price) // GCOVR_EXCL_LINE
1657  (is_margin_call)(settle_is_taker) ) } // GCOVR_EXCL_LINE
1658 
1659 optional<limit_order_id_type> database::process_limit_order_on_fill( const limit_order_object& order,
1660  const asset& order_receives )
1661 {
1662  optional<limit_order_id_type> result;
1663  if( order.on_fill.empty() )
1664  return result;
1665 
1666  const auto& take_profit_action = order.get_take_profit_action();
1667 
1668  fc::uint128_t amount128( order_receives.amount.value );
1669  amount128 *= take_profit_action.size_percent;
1670  amount128 += (GRAPHENE_100_PERCENT - 1); // Round up
1671  amount128 /= GRAPHENE_100_PERCENT;
1672  // GCOVR_EXCL_START
1673  // Defensive code, should not happen
1674  if( amount128 <= 0 )
1675  return result;
1676  // GCOVR_EXCL_STOP
1677 
1678  asset for_sale( static_cast<int64_t>( amount128 ), order_receives.asset_id );
1679 
1680  if( order.take_profit_order_id.valid() ) // Update existing take profit order
1681  {
1682  limit_order_update_operation op;
1683  op.seller = order.seller;
1684  op.order = *order.take_profit_order_id;
1685  op.delta_amount_to_sell = for_sale;
1686 
1687  if( ( time_point_sec::maximum() - take_profit_action.expiration_seconds ) > head_block_time() )
1688  op.new_expiration = head_block_time() + take_profit_action.expiration_seconds;
1689  else
1690  op.new_expiration = time_point_sec::maximum();
1691 
1692  try
1693  {
1694  if( take_profit_action.fee_asset_id == asset_id_type() )
1695  op.fee = current_fee_schedule().calculate_fee( op );
1696  else
1697  op.fee = current_fee_schedule().calculate_fee( op,
1698  take_profit_action.fee_asset_id(*this).options.core_exchange_rate ); // This may throw
1699 
1700  if( *order.take_profit_order_id > order.get_id() ) //The linked take profit order was generated by this order
1701  {
1702  // Update order price
1703  const auto& take_profit_order = (*order.take_profit_order_id)(*this);
1704  for_sale.amount += take_profit_order.for_sale;
1705  auto sell_price = (~order.sell_price) * ratio_type( GRAPHENE_100_PERCENT,
1706  int32_t(GRAPHENE_100_PERCENT) + take_profit_action.spread_percent );
1707  auto new_min_to_receive = for_sale.multiply_and_round_up( sell_price ); // This may throw
1708  op.new_price = for_sale / new_min_to_receive;
1709  }
1710  // else do not update order price
1711 
1712  // GCOVR_EXCL_START
1713  // Defensive code, should not fail
1714  FC_ASSERT( !op.new_price || ( ~(*op.new_price) > order.sell_price ),
1715  "Internal error: the take profit order should not match the current order" );
1716  // GCOVR_EXCL_STOP
1717 
1718  transaction_evaluation_state eval_state(this);
1719  eval_state.skip_limit_order_price_check = true;
1720 
1721  try_push_virtual_operation( eval_state, op );
1722  }
1723  catch( const fc::exception& e )
1724  {
1725  // We can in fact get here
1726  // e.g. if the selling or receiving asset issuer blacklisted the account,
1727  // or no sufficient balance to pay fees, or undo sessions nested too deeply
1728  wlog( "At block ${n}, failed to process on_fill for limit order ${order}, "
1729  "automatic action (maybe incomplete) was ${op}, exception was ${e}",
1730  ("op", operation(op))("order", order)
1731  ("n", head_block_num())("e", e.to_detail_string()) );
1732  }
1733  }
1734  else // Create a new take profit order
1735  {
1736  limit_order_create_operation op;
1737  op.seller = order.seller;
1738  op.amount_to_sell = for_sale;
1739  if( ( time_point_sec::maximum() - take_profit_action.expiration_seconds ) > head_block_time() )
1740  op.expiration = head_block_time() + take_profit_action.expiration_seconds;
1741  else
1742  op.expiration = time_point_sec::maximum();
1743  if( take_profit_action.repeat )
1744  op.extensions.value.on_fill = order.on_fill;
1745 
1746  try
1747  {
1748  if( take_profit_action.fee_asset_id == asset_id_type() )
1749  op.fee = current_fee_schedule().calculate_fee( op );
1750  else
1751  op.fee = current_fee_schedule().calculate_fee( op,
1752  take_profit_action.fee_asset_id(*this).options.core_exchange_rate ); // This may throw
1753 
1754  auto sell_price = (~order.sell_price) * ratio_type( GRAPHENE_100_PERCENT,
1755  int32_t(GRAPHENE_100_PERCENT) + take_profit_action.spread_percent );
1756  op.min_to_receive = for_sale.multiply_and_round_up( sell_price ); // This may throw
1757 
1758  // GCOVR_EXCL_START
1759  // Defensive code, should not fail
1760  FC_ASSERT( ~op.get_price() > order.sell_price,
1761  "Internal error: the take profit order should not match the current order" );
1762  // GCOVR_EXCL_STOP
1763 
1764  transaction_evaluation_state eval_state(this);
1765 
1766  auto op_result = try_push_virtual_operation( eval_state, op );
1767  result = limit_order_id_type( op_result.get<object_id_type>() );
1768  }
1769  catch( const fc::exception& e )
1770  {
1771  // We can in fact get here
1772  // e.g. if the selling or receiving asset issuer blacklisted the account,
1773  // or no sufficient balance to pay fees, or undo sessions nested too deeply
1774  wlog( "At block ${n}, failed to process on_fill for limit order ${order}, "
1775  "automatic action (maybe incomplete) was ${op}, exception was ${e}",
1776  ("op", operation(op))("order", order)
1777  ("n", head_block_num())("e", e.to_detail_string()) );
1778  }
1779  }
1780 
1781  return result;
1782 }
1783 
1784 bool database::fill_limit_order( const limit_order_object& order, const asset& pays, const asset& receives,
1785  bool cull_if_small, const price& fill_price, const bool is_maker)
1786 { try {
1787  if( head_block_time() < HARDFORK_555_TIME )
1788  cull_if_small = true;
1789 
1790  // GCOVR_EXCL_START
1791  // Defensive code, normally none of these should fail
1792  FC_ASSERT( order.amount_for_sale().asset_id == pays.asset_id );
1793  FC_ASSERT( pays.asset_id != receives.asset_id );
1794  // GCOVR_EXCL_STOP
1795 
1796  const account_object& seller = order.seller(*this);
1797 
1798  const auto issuer_fees = pay_market_fees(&seller, receives.asset_id(*this), receives, is_maker);
1799 
1800  auto order_receives = receives - issuer_fees;
1801  pay_order( seller, order_receives, pays );
1802 
1803  push_applied_operation( fill_order_operation( order.id, order.seller, pays, receives,
1804  issuer_fees, fill_price, is_maker ) );
1805 
1806  // BSIP85: Maker order creation fee discount, https://github.com/bitshares/bsips/blob/master/bsip-0085.md
1807  // if the order creation fee was paid in BTS,
1808  // return round_down(deferred_fee * maker_fee_discount_percent) to the owner,
1809  // then process the remaining deferred fee as before;
1810  // if the order creation fee was paid in another asset,
1811  // return round_down(deferred_paid_fee * maker_fee_discount_percent) to the owner,
1812  // return round_down(deferred_fee * maker_fee_discount_percent) to the fee pool of the asset,
1813  // then process the remaining deferred fee and deferred paid fee as before.
1814  const uint16_t maker_discount_percent = get_global_properties().parameters.get_maker_fee_discount_percent();
1815 
1816  // Save local copies for calculation
1817  share_type deferred_fee = order.deferred_fee;
1818  share_type deferred_paid_fee = order.deferred_paid_fee.amount;
1819 
1820  // conditional because cheap integer comparison may allow us to avoid two expensive modify() and object lookups
1821  if( order.deferred_paid_fee.amount > 0 ) // implies head_block_time() > HARDFORK_CORE_604_TIME
1822  {
1823  share_type fee_pool_refund = 0;
1824  if( is_maker && maker_discount_percent > 0 )
1825  {
1826  share_type refund = detail::calculate_percent( deferred_paid_fee, maker_discount_percent );
1827  // Note: it's possible that the deferred_paid_fee is very small,
1828  // which can result in a zero refund due to rounding issue,
1829  // in this case, no refund to the fee pool
1830  if( refund > 0 )
1831  {
1832  FC_ASSERT( refund <= deferred_paid_fee, "Internal error" );
1833  adjust_balance( order.seller, asset(refund, order.deferred_paid_fee.asset_id) );
1834  deferred_paid_fee -= refund;
1835 
1836  // deferred_fee might be positive too
1837  FC_ASSERT( deferred_fee > 0, "Internal error" );
1838  fee_pool_refund = detail::calculate_percent( deferred_fee, maker_discount_percent );
1839  FC_ASSERT( fee_pool_refund <= deferred_fee, "Internal error" );
1840  deferred_fee -= fee_pool_refund;
1841  }
1842  }
1843 
1844  const auto& fee_asset_dyn_data = order.deferred_paid_fee.asset_id(*this).dynamic_asset_data_id(*this);
1845  modify( fee_asset_dyn_data, [deferred_paid_fee,fee_pool_refund](asset_dynamic_data_object& addo) {
1846  addo.accumulated_fees += deferred_paid_fee;
1847  addo.fee_pool += fee_pool_refund;
1848  });
1849  }
1850 
1851  if( order.deferred_fee > 0 )
1852  {
1853  if( order.deferred_paid_fee.amount <= 0 // paid in CORE, or before HF 604
1854  && is_maker && maker_discount_percent > 0 )
1855  {
1856  share_type refund = detail::calculate_percent( deferred_fee, maker_discount_percent );
1857  if( refund > 0 )
1858  {
1859  FC_ASSERT( refund <= deferred_fee, "Internal error" );
1860  adjust_balance( order.seller, asset(refund, asset_id_type()) );
1861  deferred_fee -= refund;
1862  }
1863  }
1864  // else do nothing here, because we have already processed it above, or no need to process
1865 
1866  if( deferred_fee > 0 )
1867  {
1868  modify( seller.statistics(*this), [deferred_fee,this]( account_statistics_object& statistics )
1869  {
1870  statistics.pay_fee( deferred_fee, get_global_properties().parameters.cashback_vesting_threshold );
1871  } );
1872  }
1873  }
1874 
1875  // Process on_fill for order_receives
1876  optional<limit_order_id_type> new_take_profit_order_id = process_limit_order_on_fill( order, order_receives );
1877 
1878  // If this order is fully filled
1879  if( pays == order.amount_for_sale() )
1880  {
1881  cleanup_and_remove_limit_order( order );
1882  return true;
1883  }
1884 
1885  // This order is partially filled
1886  if( new_take_profit_order_id.valid() ) // A new take profit order is created, link this order to it
1887  {
1888  modify( (*new_take_profit_order_id)(*this), [&order]( limit_order_object& loo ) {
1889  loo.take_profit_order_id = order.get_id();
1890  });
1891  }
1892  modify( order, [&pays,&new_take_profit_order_id]( limit_order_object& b ) {
1893  b.for_sale -= pays.amount;
1894  b.filled_amount += pays.amount.value;
1895  b.deferred_fee = 0;
1896  b.deferred_paid_fee.amount = 0;
1897  if( new_take_profit_order_id.valid() ) // A new take profit order is created, link it to this order
1898  b.take_profit_order_id = *new_take_profit_order_id;
1899  });
1900  if( cull_if_small )
1901  return maybe_cull_small_order( *this, order );
1902  return false;
1903 } FC_CAPTURE_AND_RETHROW( (pays)(receives) ) } // GCOVR_EXCL_LINE
1904 
1905 /***
1906  * @brief fill a call order in the specified amounts
1907  * @param order the call order
1908  * @param pays What the call order will give to the other party (collateral)
1909  * @param receives what the call order will receive from the other party (debt)
1910  * @param fill_price the price at which the call order will execute
1911  * @param is_maker TRUE if the call order is the maker, FALSE if it is the taker
1912  * @param margin_call_fee Margin call fees paid in collateral asset
1913  * @returns TRUE if the call order was completely filled
1914  */
1915 bool database::fill_call_order( const call_order_object& order, const asset& pays, const asset& receives,
1916  const price& fill_price, const bool is_maker, const asset& margin_call_fee, bool reduce_current_supply )
1917 { try {
1918  FC_ASSERT( order.debt_type() == receives.asset_id );
1919  FC_ASSERT( order.collateral_type() == pays.asset_id );
1920  FC_ASSERT( order.collateral >= pays.amount );
1921 
1922  // TODO pass in mia and bitasset_data for better performance
1923  const asset_object& mia = receives.asset_id(*this);
1924  FC_ASSERT( mia.is_market_issued() );
1925  const asset_bitasset_data_object& bitasset = mia.bitasset_data(*this);
1926 
1927  optional<asset> collateral_freed;
1928  // adjust the order
1929  modify( order, [&]( call_order_object& o ) {
1930  o.debt -= receives.amount;
1931  o.collateral -= pays.amount;
1932  if( o.debt == 0 ) // is the whole debt paid?
1933  {
1934  collateral_freed = o.get_collateral();
1935  o.collateral = 0;
1936  }
1937  else // the debt was not completely paid
1938  {
1939  auto maint_time = get_dynamic_global_properties().next_maintenance_time;
1940  // update call_price after core-343 hard fork,
1941  // but don't update call_price after core-1270 hard fork
1942  if( maint_time <= HARDFORK_CORE_1270_TIME && maint_time > HARDFORK_CORE_343_TIME )
1943  {
1944  o.call_price = price::call_price( o.get_debt(), o.get_collateral(),
1945  bitasset.current_feed.maintenance_collateral_ratio );
1946  }
1947  }
1948  });
1949 
1950  // update current supply
1951  if( reduce_current_supply )
1952  {
1953  const asset_dynamic_data_object& mia_ddo = mia.dynamic_asset_data_id(*this);
1954  modify( mia_ddo, [&receives]( asset_dynamic_data_object& ao ){
1955  ao.current_supply -= receives.amount;
1956  });
1957  }
1958 
1959  // If the whole debt is paid, adjust borrower's collateral balance
1960  if( collateral_freed.valid() )
1961  adjust_balance( order.borrower, *collateral_freed );
1962 
1963  // Update account statistics. We know that order.collateral_type() == pays.asset_id
1964  if( pays.asset_id == asset_id_type() )
1965  {
1966  modify( get_account_stats_by_owner(order.borrower), [&collateral_freed,&pays]( account_statistics_object& b ){
1967  b.total_core_in_orders -= pays.amount;
1968  if( collateral_freed.valid() )
1969  b.total_core_in_orders -= collateral_freed->amount;
1970  });
1971  }
1972 
1973  // BSIP74: Accumulate the collateral-denominated fee
1974  if (margin_call_fee.amount.value != 0)
1975  mia.accumulate_fee(*this, margin_call_fee);
1976 
1977  // virtual operation for account history
1978  push_applied_operation( fill_order_operation( order.id, order.borrower, pays, receives,
1979  margin_call_fee, fill_price, is_maker ) );
1980 
1981  // Call order completely filled, remove it
1982  if( collateral_freed.valid() )
1983  remove( order );
1984 
1985  return collateral_freed.valid();
1986 } FC_CAPTURE_AND_RETHROW( (pays)(receives) ) } // GCOVR_EXCL_LINE
1987 
1988 /***
1989  * @brief fullfill a settle order in the specified amounts
1990  *
1991  * @details Called from database::match(), this coordinates exchange of debt asset X held in the
1992  * settle order for collateral asset Y held in a call order, and routes fees. Note that we
1993  * don't touch the call order directly, as match() handles this via a separate call to
1994  * fill_call_order(). We are told exactly how much X and Y to exchange, based on details of
1995  * order matching determined higher up the call chain. Thus it is possible that the settle
1996  * order is not completely satisfied at the conclusion of this function.
1997  *
1998  * @param settle the force_settlement object
1999  * @param pays the quantity of market-issued debt asset X which the settler will yield in this
2000  * round (may be less than the full amount indicated in settle object)
2001  * @param receives the quantity of collateral asset Y which the settler will receive in
2002  * exchange for X
2003  * @param fill_price the price at which the settle order will execute (not used - passed through
2004  * to virtual operation)
2005  * @param is_maker TRUE if the settle order is the maker, FALSE if it is the taker (passed
2006  * through to virtual operation)
2007  * @returns TRUE if the settle order was completely filled, FALSE if only partially filled
2008  */
2009 bool database::fill_settle_order( const force_settlement_object& settle, const asset& pays, const asset& receives,
2010  const price& fill_price, bool is_maker, bool pay_force_settle_fee )
2011 { try {
2012  bool filled = false;
2013 
2014  const account_object* settle_owner_ptr = nullptr;
2015  // The owner of the settle order pays market fees to the issuer of the collateral asset.
2016  // After HF core-1780, these fees are shared to the referral program, which is flagged to
2017  // pay_market_fees by setting settle_owner_ptr non-null.
2018  //
2019  // TODO Check whether the HF check can be removed after the HF.
2020  // Note: even if logically it can be removed, perhaps the removal will lead to a small performance
2021  // loss. Needs testing.
2022  if( head_block_time() >= HARDFORK_CORE_1780_TIME )
2023  settle_owner_ptr = &settle.owner(*this);
2024  // Compute and pay the market fees:
2025  asset market_fees = pay_market_fees( settle_owner_ptr, get(receives.asset_id), receives, is_maker );
2026 
2027  // Issuer of the settled smartcoin asset lays claim to a force-settlement fee (BSIP87), but
2028  // note that fee is denominated in collateral asset, not the debt asset. Asset object of
2029  // debt asset is passed to the pay function so it knows where to put the fee. Note that
2030  // amount of collateral asset upon which fee is assessed is reduced by market_fees already
2031  // paid to prevent the total fee exceeding total collateral.
2032  asset force_settle_fees = pay_force_settle_fee
2033  ? pay_force_settle_fees( get(pays.asset_id), receives - market_fees )
2034  : asset( 0, receives.asset_id );
2035 
2036  auto total_collateral_denominated_fees = market_fees + force_settle_fees;
2037 
2038  // If we don't consume entire settle order:
2039  if( pays < settle.balance )
2040  {
2041  modify(settle, [&pays](force_settlement_object& s) {
2042  s.balance -= pays;
2043  });
2044  } else {
2045  filled = true;
2046  }
2047  // Give released collateral not already taken as fees to settle order owner:
2048  adjust_balance(settle.owner, receives - total_collateral_denominated_fees);
2049 
2050  assert( pays.asset_id != receives.asset_id );
2051  push_applied_operation( fill_order_operation( settle.id, settle.owner, pays, receives,
2052  total_collateral_denominated_fees, fill_price, is_maker ) );
2053 
2054  if (filled)
2055  remove(settle);
2056 
2057  return filled;
2058 
2059 } FC_CAPTURE_AND_RETHROW( (pays)(receives) ) } // GCOVR_EXCL_LINE
2060 
2079 bool database::check_call_orders( const asset_object& mia, bool enable_black_swan, bool for_new_limit_order,
2080  const asset_bitasset_data_object* bitasset_ptr,
2081  bool mute_exceptions, bool skip_matching_settle_orders )
2082 { try {
2083  const auto& dyn_prop = get_dynamic_global_properties();
2084  auto maint_time = dyn_prop.next_maintenance_time;
2085  if( for_new_limit_order )
2086  FC_ASSERT( maint_time <= HARDFORK_CORE_625_TIME ); // `for_new_limit_order` is only true before HF 338 / 625
2087 
2088  if( !mia.is_market_issued() ) return false;
2089 
2090  const asset_bitasset_data_object& bitasset = ( bitasset_ptr ? *bitasset_ptr : mia.bitasset_data(*this) );
2091 
2092  // price feeds can cause black swans in prediction markets
2093  // The hardfork check may be able to be removed after the hardfork date
2094  // if check_for_blackswan never triggered a black swan on a prediction market.
2095  // NOTE: check_for_blackswan returning true does not always mean a black
2096  // swan was triggered.
2097  if ( maint_time >= HARDFORK_CORE_460_TIME && bitasset.is_prediction_market )
2098  return false;
2099 
2101  const auto bsrm = bitasset.get_black_swan_response_method();
2102 
2103  // Only check for black swan here if BSRM is not individual settlement
2104  if( bsrm_type::individual_settlement_to_fund != bsrm
2105  && bsrm_type::individual_settlement_to_order != bsrm
2106  && check_for_blackswan( mia, enable_black_swan, &bitasset ) )
2107  return false;
2108 
2109  if( bitasset.is_prediction_market ) return false;
2110  if( bitasset.current_feed.settlement_price.is_null() ) return false;
2111 
2112  const limit_order_index& limit_index = get_index_type<limit_order_index>();
2113  const auto& limit_price_index = limit_index.indices().get<by_price>();
2114 
2115  bool before_core_hardfork_1270 = ( maint_time <= HARDFORK_CORE_1270_TIME ); // call price caching issue
2116  bool after_core_hardfork_2481 = HARDFORK_CORE_2481_PASSED( maint_time ); // Match settle orders with margin calls
2117 
2118  // Looking for limit orders selling the most USD for the least CORE.
2119  auto max_price = price::max( bitasset.asset_id, bitasset.options.short_backing_asset );
2120  // Stop when limit orders are selling too little USD for too much CORE.
2121  // Note that since BSIP74, margin calls offer somewhat less CORE per USD
2122  // if the issuer claims a Margin Call Fee.
2123  auto min_price = before_core_hardfork_1270 ?
2125  : bitasset.get_margin_call_order_price();
2126 
2127  // NOTE limit_price_index is sorted from greatest to least
2128  auto limit_itr = limit_price_index.lower_bound( max_price );
2129  auto limit_end = limit_price_index.upper_bound( min_price );
2130 
2131  // Before the core-2481 hf, only check limit orders
2132  if( !after_core_hardfork_2481 && limit_itr == limit_end )
2133  return false;
2134 
2135  const call_order_index& call_index = get_index_type<call_order_index>();
2136  const auto& call_price_index = call_index.indices().get<by_price>();
2137  // Note: it is safe to iterate here even if there is no call order due to individual settlements
2138  const auto& call_collateral_index = call_index.indices().get<by_collateral>();
2139 
2140  auto call_min = price::min( bitasset.options.short_backing_asset, bitasset.asset_id );
2141  auto call_max = price::max( bitasset.options.short_backing_asset, bitasset.asset_id );
2142 
2143  auto call_price_itr = call_price_index.begin();
2144  auto call_price_end = call_price_itr;
2145  auto call_collateral_itr = call_collateral_index.begin();
2146  auto call_collateral_end = call_collateral_itr;
2147 
2148  if( before_core_hardfork_1270 )
2149  {
2150  call_price_itr = call_price_index.lower_bound( call_min );
2151  call_price_end = call_price_index.upper_bound( call_max );
2152  }
2153  else
2154  {
2155  call_collateral_itr = call_collateral_index.lower_bound( call_min );
2156  call_collateral_end = call_collateral_index.upper_bound( call_max );
2157  }
2158 
2159  bool filled_limit = false;
2160  bool margin_called = false; // toggles true once/if we actually execute a margin call
2161 
2162  auto head_time = head_block_time();
2163  auto head_num = head_block_num();
2164 
2165  bool before_hardfork_615 = ( head_time < HARDFORK_615_TIME );
2166  bool after_hardfork_436 = ( head_time > HARDFORK_436_TIME );
2167 
2168  bool before_core_hardfork_342 = ( maint_time <= HARDFORK_CORE_342_TIME ); // better rounding
2169  bool before_core_hardfork_343 = ( maint_time <= HARDFORK_CORE_343_TIME ); // update call_price on partial fill
2170  bool before_core_hardfork_453 = ( maint_time <= HARDFORK_CORE_453_TIME ); // multiple matching issue
2171  bool before_core_hardfork_606 = ( maint_time <= HARDFORK_CORE_606_TIME ); // feed always trigger call
2172  bool before_core_hardfork_834 = ( maint_time <= HARDFORK_CORE_834_TIME ); // target collateral ratio option
2173 
2174  bool after_core_hardfork_2582 = HARDFORK_CORE_2582_PASSED( head_time ); // Price feed issues
2175 
2176  auto has_call_order = [ before_core_hardfork_1270,
2177  &call_collateral_itr,&call_collateral_end,
2178  &call_price_itr,&call_price_end ]()
2179  {
2180  return before_core_hardfork_1270 ? ( call_price_itr != call_price_end )
2181  : ( call_collateral_itr != call_collateral_end );
2182  };
2183 
2184  bool update_current_feed = ( bsrm_type::no_settlement == bsrm && bitasset.is_current_feed_price_capped() );
2185 
2186  const auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
2187 
2188  while( has_call_order() )
2189  {
2190  // check for blackswan first // TODO perhaps improve performance by passing in iterators
2191  bool settled_some = check_for_blackswan( mia, enable_black_swan, &bitasset );
2192  if( bitasset.is_globally_settled() )
2193  return margin_called;
2194 
2195  if( settled_some ) // which implies that BSRM is individual settlement to fund or to order
2196  {
2197  call_collateral_itr = call_collateral_index.lower_bound( call_min );
2198  if( call_collateral_itr == call_collateral_end ) // no call order left
2199  {
2200  check_settled_debt_order( bitasset );
2201  return true;
2202  }
2203  margin_called = true;
2204  if( bsrm_type::individual_settlement_to_fund == bsrm )
2205  limit_end = limit_price_index.upper_bound( bitasset.get_margin_call_order_price() );
2206  }
2207 
2208  // be here, there exists at least one call order
2209  const call_order_object& call_order = ( before_core_hardfork_1270 ? *call_price_itr : *call_collateral_itr );
2210 
2211  // Feed protected (don't call if CR>MCR) https://github.com/cryptonomex/graphene/issues/436
2212  bool feed_protected = before_core_hardfork_1270 ?
2213  ( after_hardfork_436 && bitasset.current_feed.settlement_price > ~call_order.call_price )
2214  : ( bitasset.current_maintenance_collateralization < call_order.collateralization() );
2215  if( feed_protected )
2216  {
2217  check_settled_debt_order( bitasset );
2218  return margin_called;
2219  }
2220 
2221  // match call orders with limit orders
2222  if( limit_itr != limit_end )
2223  {
2224  const limit_order_object& limit_order = *limit_itr;
2225 
2226  price match_price = limit_order.sell_price;
2227  // There was a check `match_price.validate();` here, which is removed now because it always passes
2228 
2229  // Old rule: margin calls can only buy high https://github.com/bitshares/bitshares-core/issues/606
2230  if( before_core_hardfork_606 && match_price > ~call_order.call_price )
2231  return margin_called;
2232 
2233  margin_called = true;
2234 
2235  price call_pays_price = match_price * bitasset.get_margin_call_pays_ratio();
2236  // Since BSIP74, the call "pays" a bit more collateral per debt than the match price, with the
2237  // excess being kept by the asset issuer as a margin call fee. In what follows, we use
2238  // call_pays_price for the black swan check, and for the TCR, but we still use the match_price,
2239  // of course, to determine what the limit order receives. Note margin_call_pays_ratio() returns
2240  // 1/1 if margin_call_fee_ratio is unset (i.e. before BSIP74), so hardfork check is implicit.
2241 
2242  // Although we checked for black swan above, we do one more check to ensure the call order can
2243  // pay the amount of collateral which we intend to take from it (including margin call fee).
2244  // TODO refactor code for better performance and readability, perhaps extract the new logic to a new
2245  // function and call it after hf_1270, hf_bsip74 or hf_2481.
2246  auto usd_to_buy = call_order.get_debt();
2247  if( !after_core_hardfork_2481 && ( usd_to_buy * call_pays_price ) > call_order.get_collateral() )
2248  {
2249  // Trigger black swan
2250  elog( "black swan detected on asset ${symbol} (${id}) at block ${b}",
2251  ("id",bitasset.asset_id)("symbol",mia.symbol)("b",head_num) );
2252  edump((enable_black_swan));
2253  FC_ASSERT( enable_black_swan );
2254  globally_settle_asset(mia, bitasset.current_feed.settlement_price );
2255  return true;
2256  }
2257 
2258  if( !before_core_hardfork_1270 )
2259  {
2260  auto settle_price = after_core_hardfork_2582 ? bitasset.median_feed.settlement_price
2261  : bitasset.current_feed.settlement_price;
2262  usd_to_buy.amount = call_order.get_max_debt_to_cover( call_pays_price,
2263  settle_price,
2266  }
2267  else if( !before_core_hardfork_834 )
2268  {
2269  usd_to_buy.amount = call_order.get_max_debt_to_cover( call_pays_price,
2270  bitasset.current_feed.settlement_price,
2272  }
2273 
2274  asset usd_for_sale = limit_order.amount_for_sale();
2275  asset call_pays, call_receives, limit_pays, limit_receives;
2276 
2277  struct UndercollateralizationException {};
2278  try { // throws UndercollateralizationException if the call order is undercollateralized
2279 
2280  bool filled_call = false;
2281 
2282  if( usd_to_buy > usd_for_sale )
2283  { // fill order
2284  limit_receives = usd_for_sale * match_price; // round down, in favor of call order
2285 
2286  // Be here, the limit order won't be paying something for nothing, since if it would, it would have
2287  // been cancelled elsewhere already (a maker limit order won't be paying something for nothing):
2288  // * after hard fork core-625, the limit order will be always a maker if entered this function;
2289  // * before hard fork core-625,
2290  // * when the limit order is a taker, it could be paying something for nothing only when
2291  // the call order is smaller and is too small
2292  // * when the limit order is a maker, it won't be paying something for nothing
2293 
2294  if( before_core_hardfork_342 )
2295  call_receives = usd_for_sale;
2296  else
2297  // The remaining amount in the limit order would be too small,
2298  // so we should cull the order in fill_limit_order() below.
2299  // The order would receive 0 even at `match_price`, so it would receive 0 at its own price,
2300  // so calling maybe_cull_small() will always cull it.
2301  call_receives = limit_receives.multiply_and_round_up( match_price );
2302 
2303  if( !after_core_hardfork_2481 )
2304  // TODO add tests about CR change
2305  call_pays = usd_for_sale * call_pays_price; // (same as match_price until BSIP-74)
2306  else
2307  {
2308  call_pays = call_receives * call_pays_price; // calculate with updated call_receives
2309  if( call_pays.amount >= call_order.collateral )
2310  throw UndercollateralizationException();
2311  auto new_collateral = call_order.get_collateral() - call_pays;
2312  auto new_debt = call_order.get_debt() - call_receives; // the result is positive due to math
2313  if( ( new_collateral / new_debt ) < call_order.collateralization() ) // if CR would decrease
2314  throw UndercollateralizationException();
2315  }
2316 
2317  filled_limit = true;
2318 
2319  } else { // fill call, could be partial fill due to TCR
2320  call_receives = usd_to_buy;
2321 
2322  if( before_core_hardfork_342 )
2323  {
2324  limit_receives = usd_to_buy * match_price; // round down, in favor of call order
2325  call_pays = limit_receives;
2326  } else {
2327  call_pays = usd_to_buy.multiply_and_round_up( call_pays_price ); // BSIP74; excess is fee.
2328  // Note: Due to different rounding, this could potentialy be
2329  // one satoshi more than the blackswan check above
2330  if( call_pays.amount > call_order.collateral )
2331  {
2332  if( after_core_hardfork_2481 )
2333  throw UndercollateralizationException();
2334  if( mute_exceptions )
2335  call_pays.amount = call_order.collateral;
2336  }
2337  // Note: if it is a partial fill due to TCR, the math guarantees that the new CR will be higher
2338  // than the old CR, so no additional check for potential blackswan here
2339 
2340  limit_receives = usd_to_buy.multiply_and_round_up( match_price ); // round up, favors limit order
2341  if( limit_receives.amount > call_order.collateral ) // implies !after_hf_2481
2342  limit_receives.amount = call_order.collateral;
2343  // Note: here we don't re-assign call_receives with (orders_receives * match_price) to receive more
2344  // debt asset, it means the call order could be receiving a bit too much less than its value.
2345  // It is a sad thing for the call order, but it is the rule
2346  // -- when a call order is margin called, it does not get more than it borrowed.
2347  // On the other hand, if the call order is not being closed (due to TCR),
2348  // it means get_max_debt_to_cover() did not return a perfect result, maybe we can improve it.
2349  }
2350 
2351  filled_call = true; // this is safe, since BSIP38 (hard fork core-834) depends on BSIP31 (hf core-343)
2352 
2353  if( usd_to_buy == usd_for_sale )
2354  filled_limit = true;
2355  else if( filled_limit && before_hardfork_615 )
2356  //NOTE: Multiple limit match problem (see issue 453, yes this happened)
2357  _issue_453_affected_assets.insert( bitasset.asset_id );
2358  }
2359  limit_pays = call_receives;
2360 
2361  // BSIP74: Margin call fee
2362  FC_ASSERT(call_pays >= limit_receives);
2363  const asset margin_call_fee = call_pays - limit_receives;
2364 
2365  if( filled_call && before_core_hardfork_343 )
2366  ++call_price_itr;
2367 
2368  // when for_new_limit_order is true, the call order is maker, otherwise the call order is taker
2369  fill_call_order( call_order, call_pays, call_receives, match_price, for_new_limit_order, margin_call_fee);
2370 
2371  // Update current_feed after filled call order if needed
2372  if( update_current_feed )
2373  {
2374  update_bitasset_current_feed( bitasset, true );
2375  limit_end = limit_price_index.upper_bound( bitasset.get_margin_call_order_price() );
2376  update_current_feed = bitasset.is_current_feed_price_capped();
2377  }
2378 
2379  if( !before_core_hardfork_1270 )
2380  call_collateral_itr = call_collateral_index.lower_bound( call_min );
2381  else if( !before_core_hardfork_343 )
2382  call_price_itr = call_price_index.lower_bound( call_min );
2383 
2384  auto next_limit_itr = std::next( limit_itr );
2385  // when for_new_limit_order is true, the limit order is taker, otherwise the limit order is maker
2386  bool really_filled = fill_limit_order( limit_order, limit_pays, limit_receives, true,
2387  match_price, !for_new_limit_order );
2388  if( really_filled || ( filled_limit && before_core_hardfork_453 ) )
2389  limit_itr = next_limit_itr;
2390 
2391  continue; // check for blackswan again
2392 
2393  } catch( const UndercollateralizationException& ) {
2394  // Nothing to do here
2395  }
2396  } // if there is a matching limit order
2397 
2398  // be here, it is unable to fill a limit order due to undercollateralization (and there is a force settlement),
2399  // or there is no matching limit order due to MSSR, or no limit order at all
2400 
2401  // If no need to process force settlements, we return
2402  // Note: before core-2481/2467 hf, or BSRM is no_settlement and processing a new force settlement
2403  if( skip_matching_settle_orders || !after_core_hardfork_2481 )
2404  return margin_called;
2405 
2406  // If no force settlements, we return
2407  // Note: there is no matching limit order due to MSSR, or no limit order at all,
2408  // in either case, the settled debt order can't be matched
2409  auto settle_itr = settlement_index.lower_bound( bitasset.asset_id );
2410  if( settle_itr == settlement_index.end() || settle_itr->balance.asset_id != bitasset.asset_id )
2411  return margin_called;
2412 
2413  // Check margin calls against force settlements
2414  // Note: we always need to recheck limit orders after processed call-settle match,
2415  // in case when the least collateralized short was undercollateralized.
2416  if( match_force_settlements( bitasset ) )
2417  {
2418  margin_called = true;
2419  call_collateral_itr = call_collateral_index.lower_bound( call_min );
2420  if( update_current_feed )
2421  {
2422  // Note: we do not call update_bitasset_current_feed() here,
2423  // because it's called in match_impl() in match() in match_force_settlements()
2424  limit_end = limit_price_index.upper_bound( bitasset.get_margin_call_order_price() );
2425  update_current_feed = bitasset.is_current_feed_price_capped();
2426  }
2427  }
2428  // else : no more force settlements, or feed protected, both will be handled in the next loop
2429  } // while there exists a call order
2430  check_settled_debt_order( bitasset );
2431  return margin_called;
2432 } FC_CAPTURE_AND_RETHROW() } // GCOVR_EXCL_LINE
2433 
2434 bool database::match_force_settlements( const asset_bitasset_data_object& bitasset )
2435 {
2436  // Defensive checks
2437  auto maint_time = get_dynamic_global_properties().next_maintenance_time;
2438  // GCOVR_EXCL_START
2439  // Defensive code, normally none of these should fail
2440  FC_ASSERT( HARDFORK_CORE_2481_PASSED( maint_time ), "Internal error: hard fork core-2481 not passed" );
2441  FC_ASSERT( !bitasset.is_prediction_market, "Internal error: asset is a prediction market" );
2442  FC_ASSERT( !bitasset.is_globally_settled(), "Internal error: asset is globally settled already" );
2443  FC_ASSERT( !bitasset.current_feed.settlement_price.is_null(), "Internal error: no sufficient price feeds" );
2444  // GCOVR_EXCL_STOP
2445 
2446  auto head_time = head_block_time();
2447  bool after_core_hardfork_2582 = HARDFORK_CORE_2582_PASSED( head_time ); // Price feed issues
2448 
2449  const auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
2450  auto settle_itr = settlement_index.lower_bound( bitasset.asset_id );
2451  auto settle_end = settlement_index.upper_bound( bitasset.asset_id );
2452 
2453  // Note: it is safe to iterate here even if there is no call order due to individual settlements
2454  const auto& call_collateral_index = get_index_type<call_order_index>().indices().get<by_collateral>();
2455  auto call_min = price::min( bitasset.options.short_backing_asset, bitasset.asset_id );
2456  auto call_max = price::max( bitasset.options.short_backing_asset, bitasset.asset_id );
2457  auto call_itr = call_collateral_index.lower_bound( call_min );
2458  auto call_end = call_collateral_index.upper_bound( call_max );
2459 
2460  // Price at which margin calls sit on the books.
2461  // It is the MCOP, which may deviate from MSSP due to MCFR.
2462  // It is in debt/collateral .
2463  price call_match_price = bitasset.get_margin_call_order_price();
2464  // Price margin call actually relinquishes collateral at. Equals the MSSP and it may
2465  // differ from call_match_price if there is a Margin Call Fee.
2466  // It is in debt/collateral .
2467  price call_pays_price = bitasset.current_feed.max_short_squeeze_price();
2468 
2469  while( settle_itr != settle_end && call_itr != call_end )
2470  {
2471  const force_settlement_object& settle_order = *settle_itr;
2472  const call_order_object& call_order = *call_itr;
2473 
2474  // Feed protected (don't call if CR>MCR) https://github.com/cryptonomex/graphene/issues/436
2475  if( bitasset.current_maintenance_collateralization < call_order.collateralization() )
2476  return false;
2477 
2478  // TCR applies here
2479  auto settle_price = after_core_hardfork_2582 ? bitasset.median_feed.settlement_price
2480  : bitasset.current_feed.settlement_price;
2481  asset max_debt_to_cover( call_order.get_max_debt_to_cover( call_pays_price,
2482  settle_price,
2485  bitasset.asset_id );
2486 
2487  // Note: if the call order's CR is too low, it is probably unable to fill at call_pays_price.
2488  // In this case, the call order pays at its CR, the settle order may receive less due to margin call fee.
2489  // It is processed inside the function.
2490  auto result = match( call_order, settle_order, call_pays_price, bitasset, max_debt_to_cover, call_match_price );
2491 
2492  // if result.amount > 0, it means the call order got updated or removed
2493  // in this case, we need to check limit orders first, so we return
2494  if( result.amount > 0 )
2495  return true;
2496  // else : result.amount == 0, it means the settle order got canceled directly and the call order did not change
2497 
2498  settle_itr = settlement_index.lower_bound( bitasset.asset_id );
2499  call_itr = call_collateral_index.lower_bound( call_min );
2500  }
2501  return false;
2502 }
2503 
2504 void database::check_settled_debt_order( const asset_bitasset_data_object& bitasset )
2505 {
2506  const auto& head_time = head_block_time();
2507  bool after_core_hardfork_2591 = HARDFORK_CORE_2591_PASSED( head_time ); // Tighter peg (fill debt order at MCOP)
2508  if( !after_core_hardfork_2591 )
2509  return;
2510 
2512  const auto bsrm = bitasset.get_black_swan_response_method();
2513  if( bsrm_type::individual_settlement_to_order != bsrm )
2514  return;
2515 
2516  const limit_order_object* limit_ptr = find_settled_debt_order( bitasset.asset_id );
2517  if( !limit_ptr )
2518  return;
2519 
2520  const limit_order_index& limit_index = get_index_type<limit_order_index>();
2521  const auto& limit_price_index = limit_index.indices().get<by_price>();
2522 
2523  // Looking for limit orders selling the most USD for the least CORE.
2524  auto max_price = price::max( bitasset.asset_id, bitasset.options.short_backing_asset );
2525  // Stop when limit orders are selling too little USD for too much CORE.
2526  auto min_price = ~limit_ptr->sell_price;
2527 
2528  // NOTE limit_price_index is sorted from greatest to least
2529  auto limit_itr = limit_price_index.lower_bound( max_price );
2530  auto limit_end = limit_price_index.upper_bound( min_price );
2531 
2532  bool finished = false; // whether the settled debt order is gone
2533  while( !finished && limit_itr != limit_end )
2534  {
2535  const limit_order_object& matching_limit_order = *limit_itr;
2536  ++limit_itr;
2537  price old_price = limit_ptr->sell_price;
2538  finished = ( match_settled_debt_limit( *limit_ptr, matching_limit_order, matching_limit_order.sell_price )
2539  != match_result_type::only_maker_filled );
2540  if( !finished && old_price != limit_ptr->sell_price )
2541  limit_end = limit_price_index.upper_bound( ~limit_ptr->sell_price );
2542  }
2543 }
2544 
2545 void database::pay_order( const account_object& receiver, const asset& receives, const asset& pays )
2546 {
2547  if( pays.asset_id == asset_id_type() )
2548  {
2549  const auto& stats = receiver.statistics(*this);
2550  modify( stats, [&pays]( account_statistics_object& b ){
2551  b.total_core_in_orders -= pays.amount;
2552  });
2553  }
2554  adjust_balance(receiver.get_id(), receives);
2555 }
2556 
2557 asset database::calculate_market_fee( const asset_object& trade_asset, const asset& trade_amount,
2558  const bool& is_maker )const
2559 {
2560  assert( trade_asset.id == trade_amount.asset_id );
2561 
2562  if( !trade_asset.charges_market_fees() )
2563  return trade_asset.amount(0);
2564  // Optimization: The fee is zero if the order is a maker, and the maker fee percent is 0%
2565  if( is_maker && trade_asset.options.market_fee_percent == 0 )
2566  return trade_asset.amount(0);
2567 
2568  // Optimization: The fee is zero if the order is a taker, and the taker fee percent is 0%
2569  const optional<uint16_t>& taker_fee_percent = trade_asset.options.extensions.value.taker_fee_percent;
2570  if(!is_maker && taker_fee_percent.valid() && *taker_fee_percent == 0)
2571  return trade_asset.amount(0);
2572 
2573  uint16_t fee_percent;
2574  if (is_maker) {
2575  // Maker orders are charged the maker fee percent
2576  fee_percent = trade_asset.options.market_fee_percent;
2577  } else {
2578  // Taker orders are charged the taker fee percent if they are valid. Otherwise, the maker fee percent.
2579  fee_percent = taker_fee_percent.valid() ? *taker_fee_percent : trade_asset.options.market_fee_percent;
2580  }
2581 
2582  auto value = detail::calculate_percent(trade_amount.amount, fee_percent);
2583  asset percent_fee = trade_asset.amount(value);
2584 
2585  if( percent_fee.amount > trade_asset.options.max_market_fee )
2586  percent_fee.amount = trade_asset.options.max_market_fee;
2587 
2588  return percent_fee;
2589 }
2590 
2591 
2592 asset database::pay_market_fees(const account_object* seller, const asset_object& recv_asset, const asset& receives,
2593  const bool& is_maker, const optional<asset>& calculated_market_fees )
2594 {
2595  const auto market_fees = ( calculated_market_fees.valid() ? *calculated_market_fees
2596  : calculate_market_fee( recv_asset, receives, is_maker ) );
2597  auto issuer_fees = market_fees;
2598  FC_ASSERT( issuer_fees <= receives, "Market fee shouldn't be greater than receives");
2599  //Don't dirty undo state if not actually collecting any fees
2600  if ( issuer_fees.amount > 0 )
2601  {
2602  // Share market fees to the network
2603  const uint16_t network_percent = get_global_properties().parameters.get_market_fee_network_percent();
2604  if( network_percent > 0 )
2605  {
2606  const auto network_fees_amt = detail::calculate_percent( issuer_fees.amount, network_percent );
2607  FC_ASSERT( network_fees_amt <= issuer_fees.amount,
2608  "Fee shared to the network shouldn't be greater than total market fee" );
2609  if( network_fees_amt > 0 )
2610  {
2611  const asset network_fees = recv_asset.amount( network_fees_amt );
2612  deposit_market_fee_vesting_balance( GRAPHENE_COMMITTEE_ACCOUNT, network_fees );
2613  issuer_fees -= network_fees;
2614  }
2615  }
2616  }
2617 
2618  // Process the remaining fees
2619  if ( issuer_fees.amount > 0 )
2620  {
2621  // calculate and pay rewards
2622  asset reward = recv_asset.amount(0);
2623 
2624  auto is_rewards_allowed = [&recv_asset, seller]() {
2625  if ( !seller )
2626  return false;
2628  return ( !white_list || (*white_list).empty()
2629  || ( (*white_list).find(seller->registrar) != (*white_list).end() ) );
2630  };
2631 
2632  if ( is_rewards_allowed() )
2633  {
2634  const auto reward_percent = recv_asset.options.extensions.value.reward_percent;
2635  if ( reward_percent.valid() && (*reward_percent) > 0 )
2636  {
2637  const auto reward_value = detail::calculate_percent(issuer_fees.amount, *reward_percent);
2638  if ( reward_value > 0 && is_authorized_asset(*this, seller->registrar(*this), recv_asset) )
2639  {
2640  reward = recv_asset.amount(reward_value);
2641  // TODO after hf_1774, remove the `if` check, keep the code in `else`
2642  if( head_block_time() < HARDFORK_1774_TIME ){
2643  FC_ASSERT( reward < issuer_fees, "Market reward should be less than issuer fees");
2644  }
2645  else{
2646  FC_ASSERT( reward <= issuer_fees, "Market reward should not be greater than issuer fees");
2647  }
2648  // cut referrer percent from reward
2649  auto registrar_reward = reward;
2650 
2651  auto registrar = seller->registrar;
2652  auto referrer = seller->referrer;
2653 
2654  // After HF core-1800, for funds going to temp-account, redirect to committee-account
2655  if( head_block_time() >= HARDFORK_CORE_1800_TIME )
2656  {
2657  if( registrar == GRAPHENE_TEMP_ACCOUNT )
2658  registrar = GRAPHENE_COMMITTEE_ACCOUNT;
2659  if( referrer == GRAPHENE_TEMP_ACCOUNT )
2660  referrer = GRAPHENE_COMMITTEE_ACCOUNT;
2661  }
2662 
2663  if( referrer != registrar )
2664  {
2665  const auto referrer_rewards_value = detail::calculate_percent( reward.amount,
2666  seller->referrer_rewards_percentage );
2667 
2668  if ( referrer_rewards_value > 0 && is_authorized_asset(*this, referrer(*this), recv_asset) )
2669  {
2670  FC_ASSERT ( referrer_rewards_value <= reward.amount.value,
2671  "Referrer reward shouldn't be greater than total reward" );
2672  const asset referrer_reward = recv_asset.amount(referrer_rewards_value);
2673  registrar_reward -= referrer_reward;
2674  deposit_market_fee_vesting_balance(referrer, referrer_reward);
2675  }
2676  }
2677  if( registrar_reward.amount > 0 )
2678  deposit_market_fee_vesting_balance(registrar, registrar_reward);
2679  }
2680  }
2681  }
2682 
2683  if( issuer_fees.amount > reward.amount )
2684  {
2685  const auto& recv_dyn_data = recv_asset.dynamic_asset_data_id(*this);
2686  modify( recv_dyn_data, [&issuer_fees, &reward]( asset_dynamic_data_object& obj ){
2687  obj.accumulated_fees += issuer_fees.amount - reward.amount;
2688  });
2689  }
2690  }
2691 
2692  return market_fees;
2693 }
2694 
2695 /***
2696  * @brief Calculate force-settlement fee and give it to issuer of the settled asset
2697  * @param collecting_asset the smart asset object which should receive the fee
2698  * @param collat_receives the amount of collateral the settler would expect to receive absent this fee
2699  * (fee is computed as a percentage of this amount)
2700  * @return asset denoting the amount of fee collected
2701  */
2702 asset database::pay_force_settle_fees(const asset_object& collecting_asset, const asset& collat_receives)
2703 {
2704  FC_ASSERT( collecting_asset.get_id() != collat_receives.asset_id );
2705 
2706  const bitasset_options& collecting_bitasset_opts = collecting_asset.bitasset_data(*this).options;
2707 
2708  if( !collecting_bitasset_opts.extensions.value.force_settle_fee_percent.valid()
2709  || *collecting_bitasset_opts.extensions.value.force_settle_fee_percent == 0 )
2710  return asset{ 0, collat_receives.asset_id };
2711 
2712  auto value = detail::calculate_percent(collat_receives.amount,
2713  *collecting_bitasset_opts.extensions.value.force_settle_fee_percent);
2714  asset settle_fee( value, collat_receives.asset_id );
2715 
2716  // Deposit fee in asset's dynamic data object:
2717  if( value > 0) {
2718  collecting_asset.accumulate_fee(*this, settle_fee);
2719  }
2720  return settle_fee;
2721 }
2722 
2723 } }
GRAPHENE_MAX_SHARE_SUPPLY
constexpr int64_t GRAPHENE_MAX_SHARE_SUPPLY(1000000000000000LL)
graphene::chain::force_settlement_object::owner
account_id_type owner
Definition: market_object.hpp:191
fc::optional::reset
void reset()
Definition: optional.hpp:224
graphene::chain::database::match_result_type::none_filled
@ none_filled
graphene::chain::database::apply_force_settlement
void apply_force_settlement(const force_settlement_object &new_settlement, const asset_bitasset_data_object &bitasset, const asset_object &asset_obj)
Process a new force-settlement request.
Definition: db_market.cpp:943
graphene::chain::asset_dynamic_data_object::fee_pool
share_type fee_pool
in core asset
Definition: asset_object.hpp:65
graphene::protocol::bid_collateral_operation::bidder
account_id_type bidder
pays fee and additional collateral
Definition: market.hpp:247
graphene::db::object_database::find_object
const object * find_object(const object_id_type &id) const
Definition: object_database.cpp:43
FC_CAPTURE_AND_RETHROW
#define FC_CAPTURE_AND_RETHROW(...)
Definition: exception.hpp:479
GRAPHENE_COLLATERAL_RATIO_DENOM
#define GRAPHENE_COLLATERAL_RATIO_DENOM
Definition: config.hpp:113
uint128.hpp
graphene::chain::limit_order_object::amount_to_receive
asset amount_to_receive() const
Definition: market_object.hpp:78
graphene::db::object::id
object_id_type id
Definition: object.hpp:69
is_authorized_asset.hpp
graphene::chain::limit_order_object::sell_price
price sell_price
The seller's asking price.
Definition: market_object.hpp:51
graphene::chain::asset_bitasset_data_object::settlement_fund
share_type settlement_fund
Amount of collateral which is available for force settlement due to global settlement.
Definition: asset_object.hpp:313
graphene::protocol::execute_bid_operation
Definition: market.hpp:262
graphene::chain::database
tracks the blockchain state in an extensible manner
Definition: database.hpp:70
graphene::chain::database::find_settled_debt_order
const limit_order_object * find_settled_debt_order(const asset_id_type &a) const
Definition: db_getter.cpp:152
graphene::chain::call_order_object::debt
share_type debt
call_price.quote.asset_id, access via get_debt
Definition: market_object.hpp:152
wlog
#define wlog(FORMAT,...)
Definition: logger.hpp:123
graphene::chain::limit_order_index
generic_index< limit_order_object, limit_order_multi_index_type > limit_order_index
Definition: market_object.hpp:131
graphene::chain::database::apply_order_before_hardfork_625
bool apply_order_before_hardfork_625(const limit_order_object &new_order_object)
Process a new limit order through the markets.
Definition: db_market.cpp:672
fc::exception
Used to generate a useful error report when an exception is thrown.
Definition: exception.hpp:56
graphene::chain::database::head_block_time
time_point_sec head_block_time() const
Definition: db_getter.cpp:67
graphene::protocol::bid_collateral_operation
Definition: market.hpp:241
asset_object.hpp
graphene::db::object_database::get
const T & get(const object_id_type &id) const
Definition: object_database.hpp:119
graphene::protocol::price
The price struct stores asset prices in the BitShares system.
Definition: asset.hpp:108
graphene::chain::asset_bitasset_data_object::is_prediction_market
bool is_prediction_market
True if this asset implements a Prediction Market.
Definition: asset_object.hpp:291
graphene::protocol::bitasset_options::black_swan_response_type
black_swan_response_type
Defines how a BitAsset would respond to black swan events.
Definition: asset_ops.hpp:112
database.hpp
graphene::chain::dynamic_global_property_object::next_maintenance_time
time_point_sec next_maintenance_time
Definition: global_property_object.hpp:70
graphene::chain::asset_object::bitasset_data
const asset_bitasset_data_object & bitasset_data(const DB &db) const
Definition: asset_object.hpp:166
graphene::protocol::asset_options::market_fee_percent
uint16_t market_fee_percent
Definition: asset_ops.hpp:56
graphene::chain::asset_bitasset_data_object::individual_settlement_fund
share_type individual_settlement_fund
Amount of collateral due to individual settlements.
Definition: asset_object.hpp:327
graphene::chain::call_order_object::get_collateral
asset get_collateral() const
Definition: market_object.hpp:143
graphene::chain::global_property_object::parameters
chain_parameters parameters
Definition: global_property_object.hpp:44
graphene::chain::database::pay_market_fees
asset pay_market_fees(const account_object *seller, const asset_object &recv_asset, const asset &receives, const bool &is_maker, const optional< asset > &calculated_market_fees={})
Definition: db_market.cpp:2592
graphene::chain::asset_dynamic_data_object::current_supply
share_type current_supply
The number of shares currently in existence.
Definition: asset_object.hpp:61
graphene::chain::asset_bitasset_data_object::get_margin_call_pays_ratio
ratio_type get_margin_call_pays_ratio() const
Get margin call pays ratio (MCPR) of this bitasset.
Definition: asset_object.hpp:367
graphene::chain::call_order_object::collateralization
price collateralization() const
Definition: market_object.hpp:148
GRAPHENE_TEMP_ACCOUNT
#define GRAPHENE_TEMP_ACCOUNT
Represents the canonical account with WILDCARD authority (anybody can access funds in temp account)
Definition: config.hpp:148
graphene::chain::account_object::registrar
account_id_type registrar
The account that paid the fee to register this account. Receives a percentage of referral rewards.
Definition: account_object.hpp:194
graphene::chain::asset_object
tracks the parameters of an asset
Definition: asset_object.hpp:75
graphene::chain::asset_bitasset_data_object::current_maintenance_collateralization
price current_maintenance_collateralization
Definition: asset_object.hpp:283
graphene::chain::database::adjust_balance
void adjust_balance(account_id_type account, asset delta)
Adjust a particular account's balance in a given asset by a delta.
Definition: db_balance.cpp:54
graphene::protocol::price_feed::settlement_price
price settlement_price
Definition: asset.hpp:180
graphene::chain::limit_order_object::sell_asset_id
asset_id_type sell_asset_id() const
Definition: market_object.hpp:79
graphene::chain::database::check_call_orders
bool check_call_orders(const asset_object &mia, bool enable_black_swan=true, bool for_new_limit_order=false, const asset_bitasset_data_object *bitasset_ptr=nullptr, bool mute_exceptions=false, bool skip_matching_settle_orders=false)
Definition: db_market.cpp:2079
graphene::chain::asset_object::symbol
string symbol
Ticker symbol for this asset, i.e. "USD".
Definition: asset_object.hpp:131
graphene::protocol::bid_collateral_operation::debt_covered
asset debt_covered
the amount of debt to take over
Definition: market.hpp:249
fc::time_point_sec::maximum
static time_point_sec maximum()
Definition: time.hpp:86
graphene::chain::call_order_object::get_debt
asset get_debt() const
Definition: market_object.hpp:144
graphene::protocol::chain_parameters::get_maker_fee_discount_percent
uint16_t get_maker_fee_discount_percent() const
Definition: chain_parameters.cpp:122
graphene::chain::call_order_object::collateral
share_type collateral
call_price.base.asset_id, access via get_collateral
Definition: market_object.hpp:151
graphene::chain::limit_order_object::seller
account_id_type seller
Who is selling.
Definition: market_object.hpp:49
graphene::protocol::bid_collateral_operation::additional_collateral
asset additional_collateral
the amount of collateral to bid for the debt
Definition: market.hpp:248
graphene::chain::asset_object::dynamic_asset_data_id
asset_dynamic_data_id_type dynamic_asset_data_id
Current supply, fee pool, and collected fees are stored in a separate object as they change frequentl...
Definition: asset_object.hpp:140
graphene::chain::database::set_applied_operation_result
void set_applied_operation_result(uint32_t op_id, const operation_result &r)
Definition: db_block.cpp:555
graphene::protocol::white_list
@ white_list
accounts must be whitelisted in order to hold or transact this asset
Definition: types.hpp:195
graphene::protocol::asset_options::extensions
additional_asset_options_t extensions
Definition: asset_ops.hpp:93
graphene::protocol::bitasset_options
The bitasset_options struct contains configurable options available only to BitAssets.
Definition: asset_ops.hpp:109
graphene::chain::database::match_result_type
match_result_type
Definition: database.hpp:417
graphene::chain::database::cancel_limit_order
void cancel_limit_order(const limit_order_object &order, bool create_virtual_op=true, bool skip_cancel_fee=false)
Definition: db_market.cpp:533
graphene::protocol::price_feed::max_short_squeeze_price
price max_short_squeeze_price() const
Definition: asset.cpp:300
graphene::chain::asset_dynamic_data_object::accumulated_fees
share_type accumulated_fees
fees accumulate to be paid out over time
Definition: asset_object.hpp:63
graphene::chain::database::revive_bitasset
void revive_bitasset(const asset_object &bitasset, const asset_bitasset_data_object &bad)
Definition: db_market.cpp:422
graphene::protocol::additional_asset_options::whitelist_market_fee_sharing
fc::optional< flat_set< account_id_type > > whitelist_market_fee_sharing
Definition: asset_ops.hpp:34
graphene::chain::database::match_result_type::only_maker_filled
@ only_maker_filled
graphene::chain::asset_bitasset_data_object::is_current_feed_price_capped
bool is_current_feed_price_capped() const
Definition: asset_object.hpp:277
graphene::chain::account_statistics_object
Definition: account_object.hpp:46
wdump
#define wdump(SEQ)
Definition: logger.hpp:174
graphene::chain::database::match_result_type::both_filled
@ both_filled
fc::remove
bool remove(const path &p)
Definition: filesystem.cpp:327
graphene::protocol::price::call_price
static price call_price(const asset &debt, const asset &collateral, uint16_t collateral_ratio)
Definition: asset.cpp:216
edump
#define edump(SEQ)
Definition: logger.hpp:182
graphene::chain::database::current_fee_schedule
const fee_schedule & current_fee_schedule() const
Definition: db_getter.cpp:62
dlog
#define dlog(FORMAT,...)
Definition: logger.hpp:100
graphene::protocol::asset::multiply_and_round_up
asset multiply_and_round_up(const price &p) const
Multiply and round up.
Definition: asset.cpp:77
graphene::chain::database::update_bitasset_current_feed
void update_bitasset_current_feed(const asset_bitasset_data_object &bitasset, bool skip_median_update=false)
Definition: db_update.cpp:270
graphene::db::generic_index::indices
const index_type & indices() const
Definition: generic_index.hpp:115
fc::optional::valid
bool valid() const
Definition: optional.hpp:186
graphene::chain::database::cancel_bid
void cancel_bid(const collateral_bid_object &bid, bool create_virtual_op=true)
Definition: db_market.cpp:477
graphene::chain::asset_dynamic_data_object
tracks the asset information that changes frequently
Definition: asset_object.hpp:56
graphene::chain::database::match_result_type::only_taker_filled
@ only_taker_filled
graphene::chain::account_object
This class represents an account on the object graph.
Definition: account_object.hpp:180
graphene::chain::database::apply_order
bool apply_order(const limit_order_object &new_order_object)
Definition: db_market.cpp:741
graphene::protocol::asset::asset_id
asset_id_type asset_id
Definition: asset.hpp:37
graphene::protocol::price_feed::maximum_short_squeeze_ratio
uint16_t maximum_short_squeeze_ratio
Definition: asset.hpp:189
account_object.hpp
graphene::chain::database::push_applied_operation
uint32_t push_applied_operation(const operation &op, bool is_virtual=true)
Definition: db_block.cpp:548
graphene::chain::by_expiration
Definition: proposal_object.hpp:86
graphene::chain::limit_order_object::receive_asset_id
asset_id_type receive_asset_id() const
Definition: market_object.hpp:80
graphene::chain::database::execute_bid
void execute_bid(const collateral_bid_object &bid, share_type debt_covered, share_type collateral_from_fund, const price_feed &current_feed)
Definition: db_market.cpp:492
graphene::protocol::price::is_null
bool is_null() const
Definition: asset.cpp:229
graphene::chain::force_settlement_object::balance
asset balance
Definition: market_object.hpp:192
graphene::protocol::price_feed
defines market parameters for margin positions
Definition: asset.hpp:160
graphene::chain::database::globally_settle_asset
void globally_settle_asset(const asset_object &bitasset, const price &settle_price, bool check_margin_calls=false)
Definition: db_market.cpp:221
graphene::chain::asset_bitasset_data_object
contains properties that only apply to bitassets (market issued assets)
Definition: asset_object.hpp:255
graphene::chain::is_authorized_asset
bool is_authorized_asset(const database &d, const account_object &acct, const asset_object &asset_obj)
Definition: is_authorized_asset.hpp:43
graphene::chain::asset_object::accumulate_fee
void accumulate_fee(DB &db, const asset &fee) const
Definition: asset_object.hpp:201
graphene::chain::asset_bitasset_data_object::current_feed
price_feed_with_icr current_feed
This is the currently active price feed, calculated from median_feed and other parameters.
Definition: asset_object.hpp:272
graphene::chain::collateral_bid_object
bids of collateral for debt after a black swan
Definition: market_object.hpp:206
graphene::chain::call_order_object::get_max_debt_to_cover
share_type get_max_debt_to_cover(price match_price, price feed_price, const uint16_t maintenance_collateral_ratio, const optional< price > &maintenance_collateralization=optional< price >()) const
Definition: market_object.cpp:61
graphene::chain::asset_bitasset_data_object::median_feed
price_feed_with_icr median_feed
This is the median of values from the currently active feeds.
Definition: asset_object.hpp:270
fc::exception::to_detail_string
std::string to_detail_string(log_level ll=log_level::all) const
Definition: exception.cpp:183
graphene::chain::asset_bitasset_data_object::get_margin_call_order_price
price get_margin_call_order_price() const
Get margin call order price (MCOP) of this bitasset.
Definition: asset_object.hpp:355
graphene::chain::call_order_object::call_price
price call_price
Collateral / Debt.
Definition: market_object.hpp:153
graphene::protocol::limit_order_cancel_operation
Definition: market.hpp:145
graphene::chain::collateral_bid_object::bidder
account_id_type bidder
Definition: market_object.hpp:214
graphene::chain::account_object::referrer_rewards_percentage
uint16_t referrer_rewards_percentage
Definition: account_object.hpp:206
graphene::chain::database::head_block_num
uint32_t head_block_num() const
Definition: db_getter.cpp:72
graphene::protocol::asset_settle_cancel_operation
Definition: asset_ops.hpp:293
graphene::protocol::additional_asset_options::reward_percent
fc::optional< uint16_t > reward_percent
Definition: asset_ops.hpp:33
GRAPHENE_COMMITTEE_ACCOUNT
#define GRAPHENE_COMMITTEE_ACCOUNT
Definition: config.hpp:140
graphene::protocol::share_type
safe< int64_t > share_type
Definition: types.hpp:309
graphene::chain::call_order_object::borrower
account_id_type borrower
Definition: market_object.hpp:150
graphene::chain::asset_object::charges_market_fees
bool charges_market_fees() const
Definition: asset_object.hpp:92
FC_ASSERT
#define FC_ASSERT(TEST,...)
Checks a condition and throws an assert_exception if the test is FALSE.
Definition: exception.hpp:345
graphene::chain::asset_object::issuer
account_id_type issuer
ID of the account which issued this asset.
Definition: asset_object.hpp:135
graphene::chain::detail::calculate_percent
share_type calculate_percent(const share_type &value, uint16_t percent)
Definition: db_market.cpp:39
graphene::protocol::limit_order_cancel_operation::fee
asset fee
Definition: market.hpp:149
graphene::protocol::asset::amount
share_type amount
Definition: asset.hpp:36
graphene::protocol::price_feed::maintenance_collateral_ratio
uint16_t maintenance_collateral_ratio
Definition: asset.hpp:186
graphene::chain::maybe_cull_small_order
bool maybe_cull_small_order(database &db, const limit_order_object &order)
Definition: db_market.cpp:646
graphene::protocol::price::max
price max() const
Definition: asset.hpp:124
graphene::chain::limit_order_object::amount_for_sale
asset amount_for_sale() const
Definition: market_object.hpp:77
graphene::chain::asset_object::amount
asset amount(share_type a) const
Helper function to get an asset object with the given amount in this asset's type.
Definition: asset_object.hpp:114
graphene::chain::asset_bitasset_data_object::get_black_swan_response_method
bitasset_options::black_swan_response_type get_black_swan_response_method() const
Get the effective black swan response method of this bitasset.
Definition: asset_object.hpp:349
graphene::chain::force_settlement_object
tracks bitassets scheduled for force settlement at some point in the future.
Definition: market_object.hpp:187
graphene::protocol::asset_options::max_market_fee
share_type max_market_fee
Market fees calculated as market_fee_percent of the traded volume are capped to this value.
Definition: asset_ops.hpp:58
graphene::chain::account_statistics_object::total_core_in_orders
share_type total_core_in_orders
Definition: account_object.hpp:68
graphene::protocol::limit_order_cancel_operation::fee_paying_account
account_id_type fee_paying_account
Definition: market.hpp:152
graphene::chain::call_order_object
tracks debt and call price information
Definition: market_object.hpp:140
graphene::protocol::price::base
asset base
Definition: asset.hpp:113
graphene::chain::account_object::statistics
account_statistics_id_type statistics
Definition: account_object.hpp:229
graphene::protocol::limit_order_cancel_operation::order
limit_order_id_type order
Definition: market.hpp:150
graphene::db::generic_index
Definition: generic_index.hpp:43
graphene::chain::database::get_account_stats_by_owner
const account_statistics_object & get_account_stats_by_owner(account_id_type owner) const
Definition: db_getter.cpp:142
graphene::protocol::price::min
price min() const
Definition: asset.hpp:125
GRAPHENE_NULL_ACCOUNT
#define GRAPHENE_NULL_ACCOUNT
Represents the canonical account with NO authority (nobody can access funds in null account)
Definition: config.hpp:146
graphene::protocol::price_feed::max_short_squeeze_price_before_hf_1270
price max_short_squeeze_price_before_hf_1270() const
Definition: asset.cpp:282
graphene::db::abstract_object::get_id
object_id< SpaceID, TypeID > get_id() const
Definition: object.hpp:113
graphene::chain::database::get_global_properties
const global_property_object & get_global_properties() const
Definition: db_getter.cpp:47
fc::optional
provides stack-based nullable value similar to boost::optional
Definition: optional.hpp:20
graphene::protocol::fee_schedule::calculate_fee
asset calculate_fee(const operation &op) const
Definition: fee_schedule_calc.cpp:79
graphene::chain::account_object::referrer
account_id_type referrer
The account credited as referring this account. Receives a percentage of referral rewards.
Definition: account_object.hpp:196
graphene::chain::limit_order_object::take_profit_order_id
optional< limit_order_id_type > take_profit_order_id
ID of the take profit limit order linked to this limit order.
Definition: market_object.hpp:61
graphene::protocol::asset
Definition: asset.hpp:31
graphene::chain::asset_object::options
asset_options options
Definition: asset_object.hpp:137
market_object.hpp
graphene::chain::database::cancel_settle_order
void cancel_settle_order(const force_settlement_object &order)
Definition: db_market.cpp:524
GRAPHENE_ASSERT
#define GRAPHENE_ASSERT(expr, exc_type, FORMAT,...)
Definition: exceptions.hpp:28
graphene::db::object_database::remove
void remove(const object &obj)
Definition: object_database.hpp:97
graphene::chain::asset_object::is_market_issued
bool is_market_issued() const
Definition: asset_object.hpp:84
graphene::chain::database::get_dynamic_global_properties
const dynamic_global_property_object & get_dynamic_global_properties() const
Definition: db_getter.cpp:57
fc::safe::value
T value
Definition: safe.hpp:28
graphene::chain::database::find_least_collateralized_short
const call_order_object * find_least_collateralized_short(const asset_bitasset_data_object &bitasset, bool force_by_collateral_index) const
Definition: db_getter.cpp:161
graphene::chain::limit_order_object
an offer to sell an amount of an asset at a specified exchange rate by a certain time
Definition: market_object.hpp:45
graphene::protocol::ratio_type
boost::rational< int32_t > ratio_type
Definition: types.hpp:150
graphene::protocol::bitasset_options::short_backing_asset
asset_id_type short_backing_asset
Definition: asset_ops.hpp:171
graphene::chain::account_statistics_object::pay_fee
void pay_fee(share_type core_fee, share_type cashback_vesting_threshold)
Definition: account_object.cpp:100
graphene::chain::limit_order_object::deferred_paid_fee
asset deferred_paid_fee
originally paid fee
Definition: market_object.hpp:54
graphene::chain::limit_order_object::deferred_fee
share_type deferred_fee
fee converted to CORE
Definition: market_object.hpp:53
graphene::protocol::price::quote
asset quote
Definition: asset.hpp:114
GRAPHENE_100_PERCENT
#define GRAPHENE_100_PERCENT
Definition: config.hpp:102
graphene
Definition: api.cpp:48
graphene::protocol::extension::value
T value
Definition: ext.hpp:40
graphene::protocol::bitasset_options::extensions
extension< ext > extensions
Definition: asset_ops.hpp:173
graphene::chain::asset_bitasset_data_object::options
bitasset_options options
The tunable options for BitAssets are stored in this field.
Definition: asset_object.hpp:263
graphene::db::object_database::modify
void modify(const T &obj, const Lambda &m)
Definition: object_database.hpp:99
graphene::protocol::additional_asset_options::taker_fee_percent
fc::optional< uint16_t > taker_fee_percent
Definition: asset_ops.hpp:36
graphene::chain::collateral_bid_object::inv_swan_price
price inv_swan_price
Definition: market_object.hpp:215
graphene::chain::asset_bitasset_data_object::is_globally_settled
bool is_globally_settled() const
Definition: asset_object.hpp:299
graphene::protocol::operation
fc::static_variant< transfer_operation, limit_order_create_operation, limit_order_cancel_operation, call_order_update_operation, fill_order_operation, account_create_operation, account_update_operation, account_whitelist_operation, account_upgrade_operation, account_transfer_operation, asset_create_operation, asset_update_operation, asset_update_bitasset_operation, asset_update_feed_producers_operation, asset_issue_operation, asset_reserve_operation, asset_fund_fee_pool_operation, asset_settle_operation, asset_global_settle_operation, asset_publish_feed_operation, witness_create_operation, witness_update_operation, proposal_create_operation, proposal_update_operation, proposal_delete_operation, withdraw_permission_create_operation, withdraw_permission_update_operation, withdraw_permission_claim_operation, withdraw_permission_delete_operation, committee_member_create_operation, committee_member_update_operation, committee_member_update_global_parameters_operation, vesting_balance_create_operation, vesting_balance_withdraw_operation, worker_create_operation, custom_operation, assert_operation, balance_claim_operation, override_transfer_operation, transfer_to_blind_operation, blind_transfer_operation, transfer_from_blind_operation, asset_settle_cancel_operation, asset_claim_fees_operation, fba_distribute_operation, bid_collateral_operation, execute_bid_operation, asset_claim_pool_operation, asset_update_issuer_operation, htlc_create_operation, htlc_redeem_operation, htlc_redeemed_operation, htlc_extend_operation, htlc_refund_operation, custom_authority_create_operation, custom_authority_update_operation, custom_authority_delete_operation, ticket_create_operation, ticket_update_operation, liquidity_pool_create_operation, liquidity_pool_delete_operation, liquidity_pool_deposit_operation, liquidity_pool_withdraw_operation, liquidity_pool_exchange_operation, samet_fund_create_operation, samet_fund_delete_operation, samet_fund_update_operation, samet_fund_borrow_operation, samet_fund_repay_operation, credit_offer_create_operation, credit_offer_delete_operation, credit_offer_update_operation, credit_offer_accept_operation, credit_deal_repay_operation, credit_deal_expired_operation, liquidity_pool_update_operation, credit_deal_update_operation, limit_order_update_operation > operation
Definition: operations.hpp:134
elog
#define elog(FORMAT,...)
Definition: logger.hpp:129
graphene::chain::asset_bitasset_data_object::asset_id
asset_id_type asset_id
The asset this object belong to.
Definition: asset_object.hpp:260
fc::safe
Definition: safe.hpp:26