Bid for collateral in the settlement fund
164738
def bidcollateral(
    ctx, collateral_symbol, collateral_amount, debt_symbol, debt_amount, account
):
    
    print_tx(
        ctx.bitshares.bid_collateral(
            Amount(collateral_amount, collateral_symbol),
            Amount(debt_amount, debt_symbol),
            account=account,
        )
    )
1050727
async def put(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		# Check if message contains required data
		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]
		cid = int(message["offer_id"].get("cid", 0))
		buyer_address = message["offer_id"].get("buyer_address")
		coinid = message.get("coinid")

		if not all([cid, buyer_address, coinid]):
			self.set_status(400)
			self.write({"error":400, "reason": "Missed required fields."})
			raise tornado.web.Finish

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coin ID"})
			raise tornado.web.Finish

		check = self.account.validator[coinid](public_key)

		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			error_code = account["error"]
			self.set_status(error_code)
			self.write(account)
			raise tornado.web.Finish
	
		# Check if one of sellers or buyers rejects offer
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)
		hex_ = check
		if buyer_address != hex_ and owneraddr != hex_:
			# Avoid rejecting offer
			self.set_status(403)
			self.write({"error": 403, "reason":"Forbidden. Offer does not belong to user."})
		
		# Reject offer
		response = await self.account.blockchain.rejectoffer(coinid=coinid, cid=cid, 
															buyer_address=buyer_address)
		if "error" in response.keys():
			self.set_status(response["error"])
			self.write(response)
			raise tornado.web.Finish

		# Get buyer for email sending
		buyer = await self.account.getaccountbywallet(wallet=buyer_address)
		if "error" in buyer.keys():
			self.set_status(buyer["error"])
			self.write(buyer)
			raise tornado.web.Finish
	
		if buyer.get("email"):
			emaildata = {
				"to": buyer.get("email"),
				"subject": "Robin8 support",
     			"optional": "Your offer with cid %s was rejected." % cid
			}
			await self.account.mailer.sendmail(**emaildata)
		
		# Undeposit balance
		price = await self.account.blockchain.getwriteprice(cid=cid)
		coinid = "PUT"
		await self.account.balance.unfreeze(uid=buyer["id"],coinid=coinid, 
													amount=price)

		del response["result"]
		self.write(response)
827257
function createBid(status, reqBid, response, width, height, bidderCode) {
  let bid = createBidFactory(status, reqBid);

  // TTL 5 mins by default, future support for extended imp wait time
  if (response) {
    Object.assign(bid, {
      requestId: reqBid.bidId,
      cpm: response.price,
      creativeId: response.crid || '-1',
      vastXml: response.adm,
      vastUrl: reqBid.vastUrl,
      mediaType: 'video',
      width: width,
      height: height,
      bidderCode: bidderCode,
      adId: response.id,
      currency: 'USD',
      netRevenue: true,
      ttl: 300,
      ad: response.adm
    });
  }

  return bid;
}
399549
function newBid(serverBid, rtbBid, bidderRequest) {
  const bid = {
    requestId: serverBid.uuid,
    cpm: 0.00,
    creativeId: rtbBid.creative_id,
    dealId: 99999999,
    currency: 'USD',
    netRevenue: true,
    ttl: 300,
    appnexus: {
      buyerMemberId: rtbBid.buyer_member_id
    }
  };

  if (rtbBid.rtb.video) {
    Object.assign(bid, {
      width: rtbBid.rtb.video.player_width,
      height: rtbBid.rtb.video.player_height,
      vastUrl: rtbBid.rtb.video.asset_url,
      vastImpUrl: rtbBid.notify_url,
      ttl: 3600
    });
    // This supports Outstream Video
    if (rtbBid.renderer_url) {
      const rendererOptions = utils.deepAccess(
        bidderRequest.bids[0],
        'renderer.options'
      );

      Object.assign(bid, {
        adResponse: serverBid,
        renderer: newRenderer(bid.adUnitCode, rtbBid, rendererOptions)
      });
      bid.adResponse.ad = bid.adResponse.ads[0];
      bid.adResponse.ad.video = bid.adResponse.ad.rtb.video;
    }
  } else if (rtbBid.rtb[NATIVE]) {
    const nativeAd = rtbBid.rtb[NATIVE];
    bid[NATIVE] = {
      title: nativeAd.title,
      body: nativeAd.desc,
      cta: nativeAd.ctatext,
      sponsoredBy: nativeAd.sponsored,
      clickUrl: nativeAd.link.url,
      clickTrackers: nativeAd.link.click_trackers,
      impressionTrackers: nativeAd.impression_trackers,
      javascriptTrackers: nativeAd.javascript_trackers,
    };
    if (nativeAd.main_img) {
      bid['native'].image = {
        url: nativeAd.main_img.url,
        height: nativeAd.main_img.height,
        width: nativeAd.main_img.width,
      };
    }
    if (nativeAd.icon) {
      bid['native'].icon = {
        url: nativeAd.icon.url,
        height: nativeAd.icon.height,
        width: nativeAd.icon.width,
      };
    }
  } else {
    Object.assign(bid, {
      width: rtbBid.rtb.banner.width,
      height: rtbBid.rtb.banner.height,
      ad: rtbBid.rtb.banner.content
    });
    try {
      const url = rtbBid.rtb.trackers[0].impression_urls[0];
      const tracker = utils.createTrackPixelHtml(url);
      bid.ad += tracker;
    } catch (error) {
      utils.logError('Error appending tracking pixel', error);
    }
  }

  return bid;
}
1298854
function composePowJoint(from_address, round_index, seed, deposit, solution, signer, callbacks){
	var payload = {seed: seed, deposit:deposit, solution: solution};
	var objMessage = {
		app: "pow_equihash",
		payload_location: "inline",
		payload_hash: objectHash.getBase64Hash(payload),
		payload: payload
	};
	composeJoint({
		paying_addresses: [from_address],
		outputs: [{address: from_address, amount: 0}],
		messages: [objMessage],
		round_index: round_index,
		pow_type: constants.POW_TYPE_POW_EQUHASH,
		signer: signer,
		callbacks: callbacks
	});
}
823058
def repay_funding(self, amount, currency):
        
        params = {
            'amount': amount,
            'currency': currency  # example: USD
            }
        return self._send_message('post', '/funding/repay',
                                  data=json.dumps(params))
597189
def calls(ctx, obj, limit):
    
    if obj.upper() == obj:
        # Asset
        from bitshares.asset import Asset

        asset = Asset(obj, full=True)
        calls = asset.get_call_orders(limit)
        t = [["acount", "debt", "collateral", "call price", "ratio"]]
        for call in calls:
            t.append(
                [
                    str(call["account"]["name"]),
                    str(call["debt"]),
                    str(call["collateral"]),
                    str(call["call_price"]),
                    "%.2f" % (call["ratio"]),
                ]
            )
        print_table(t)
    else:
        # Account
        from bitshares.dex import Dex

        dex = Dex(bitshares_instance=ctx.bitshares)
        calls = dex.list_debt_positions(account=obj)
        t = [["debt", "collateral", "call price", "ratio"]]
        for symbol in calls:
            t.append(
                [
                    str(calls[symbol]["debt"]),
                    str(calls[symbol]["collateral"]),
                    str(calls[symbol]["call_price"]),
                    "%.2f" % (calls[symbol]["ratio"]),
                ]
            )
        print_table(t)
733257
def log_player_buys_settlement(self, player, location):
        
        self._logln('{0} buys settlement, builds at {1}'.format(
            player.color,
            location
        ))
1282608
def settle(self, reserveTransactionId, transactionAmount=None):
        
        params = {}
        params['ReserveTransactionId'] = reserveTransactionId
        if(transactionAmount != None):
            params['TransactionAmount'] = transactionAmount
        
        response = self.make_request("Settle", params)
        body = response.read()
        if(response.status == 200):
            rs = ResultSet()
            h = handler.XmlHandler(rs, self)
            xml.sax.parseString(body, h)
            return rs
        else:
            raise FPSResponseError(response.status, response.reason, body)
292338
function(_bid,_error){
        var _batch = _xcache[_bid];
        if (!_batch) return;
        _u._$forIn(
            _batch.h,function(v,k){
                __onError(_bid,k,_error);
            }
        );
    }
147419
function resolveAsset (
	  options,
	  type,
	  id,
	  warnMissing
	) {
	  /* istanbul ignore if */
	  if (typeof id !== 'string') {
	    return
	  }
	  var assets = options[type];
	  var res = assets[id] ||
	    // camelCase ID
	    assets[camelize(id)] ||
	    // Pascal Case ID
	    assets[capitalize(camelize(id))];
	  if ("development" !== 'production' && warnMissing && !res) {
	    warn(
	      'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
	      options
	    );
	  }
	  return res
	}
1151447
async function () {
    const oThis = this
    ;

    // validations
    if (!basicHelper.isNonZeroWeiValid(oThis.amountToStakeInWeis)) {
      logger.error('Invalid amount');
      process.exit(1);
    }

    // Format to big number
    oThis.amountToStakeInWeis = basicHelper.convertToBigNumber(oThis.amountToStakeInWeis);

    const amountToStakeForBT = ((oThis.amountToStakeInWeis.mul(0.9)).minus(oThis.amountToStakeInWeis.mul(0.9).modulo(1)))
      , amountToStakeForSTP = oThis.amountToStakeInWeis.minus(amountToStakeForBT)
      , stPrimeUuid = coreConstants.OST_OPENSTUTILITY_ST_PRIME_UUID
    ;

    // validations
    if (!basicHelper.isNonZeroWeiValid(amountToStakeForBT)) {
      logger.error('Invalid wei amount to stake for BT', amountToStakeForBT.toString(10));
      process.exit(1);
    }
    if (!basicHelper.isNonZeroWeiValid(amountToStakeForSTP)) {
      logger.error('Invalid wei amount to stake for ST Prime', amountToStakeForSTP.toString(10));
      process.exit(1);
    }

    logger.step('** Starting stake mint for branded token for beneficiary reserve of BT Reserve:', oThis.reserveAddr);

    // NOTE: In real case, Member Company transfers ST to staker and then approve is called. To simulate this, foundation
    // is transfering ST to staker.
    logger.info('* Foundation transfers ST to BT Reserve');
    await fundManager.transferST(
        foundationAddr, foundationPassphrase, stakerAddr, oThis.amountToStakeInWeis,
        {tag: 'transferSTToBTReserve', returnType: 'txReceipt'}
    );

    logger.info('* Staker approves openSTValue contract');
    const approveResponse = await (new approveService()).perform();
    if (approveResponse.isFailure()) {
      process.exit(1);
    }

    const approveTransactionHash = approveResponse.data.transaction_hash;

    logger.info('* Get approval status and keep doing so till success');
    const approveReceiptResponse =  await contractInteractHelper.waitAndGetTransactionReceipt(web3Provider, approveTransactionHash, {});
    if (!approveReceiptResponse.isSuccess()) {
      logger.error('Approval receipt error ', approveReceiptResponse);
      process.exit(1);
    }

    logger.info('* Start stake for Branded Token');
    await (new startStakeService({
      beneficiary: oThis.reserveAddr,
      to_stake_amount: amountToStakeForBT,
      uuid: oThis.brandedTokenUuid
    })).perform();

    logger.info('* Waiting for credit of Branded Token to BT Reserve');
    await oThis._waitForBrandedTokenMint();

    logger.info('* Start stake for Simple Token Prime');
    await (new startStakeService({
      beneficiary: oThis.reserveAddr,
      to_stake_amount: amountToStakeForSTP,
      uuid: stPrimeUuid
    })).perform();

    logger.info('* Waiting for credit of Simple Token Prime to BT Reserve');
    await oThis._waitForSimpleTokenPrimeMint();

    return Promise.resolve(responseHelper.successWithData({}));
  }
807471
function invokePending(kind, data) {
      var xs = pending
      pending.length = 0
      for (var i = 0; i < xs.length; ++i)  xs[i][kind](value) }
1153397
function prebidBid(serverBid, cur) {
  if (cur == null || cur == '') {
    cur = 'USD';
  }
  const bid = {
    requestId: serverBid.impid,
    ad: serverBid.adm,
    cpm: serverBid.price,
    creativeId: serverBid.adid,
    currency: cur,
    dealId: serverBid.dealid || '',
    width: serverBid.w,
    height: serverBid.h,
    mediaType: 'banner',
    netRevenue: true,
    ttl: serverBid.ttl || 300,
    nurl: serverBid.nurl || '',
    isBurl: typeof (serverBid.burl) == 'string' && serverBid.burl.length > 0,
  };

  return bid;
}
367558
def _runAuction(self, gteeOfferPrice, gteeBidPrice, haveQ):
        
        pOffers = [offer for offer in self.offers if not offer.reactive]
        pBids = [bid for bid in self.bids if not bid.reactive]

        # Clear offer/bid quantities and prices.
        auction = Auction(self.case, pOffers, pBids, self.auctionType,
                          gteeOfferPrice, gteeBidPrice, self.limits)
        auction.run()

        # Separate auction for reactive power.
        if haveQ:
            qOffers = [offer for offer in self.offers if offer.reactive]
            qBids = [bid for bid in self.bids if bid.reactive]

            # Too complicated to scale with mixed bids/offers (only
            # auction_types LAO and FIRST_PRICE allowed)
            qAuction = Auction(self.case, qOffers, qBids, self.auctionType,
                                gteeOfferPrice, gteeBidPrice, self.limits)
            qAuction.run()
928003
function fundingConfigUSDTieredSTO() {
  let funding = {};

  let selectedFunding = readlineSync.question('Enter' + chalk.green(` P `) + 'for POLY raise,' + chalk.green(` S `) + 'for Stable Coin raise,' + chalk.green(` E `) + 'for Ether raise or any combination of them (i.e.' + chalk.green(` PSE `) + 'for all): ').toUpperCase();

  funding.raiseType = [];
  if (selectedFunding.includes('E')) {
    funding.raiseType.push(gbl.constants.FUND_RAISE_TYPES.ETH);
  }
  if (selectedFunding.includes('P')) {
    funding.raiseType.push(gbl.constants.FUND_RAISE_TYPES.POLY);
  }
  if (selectedFunding.includes('S')) {
    funding.raiseType.push(gbl.constants.FUND_RAISE_TYPES.STABLE);
  }
  if (funding.raiseType.length == 0) {
    funding.raiseType = [gbl.constants.FUND_RAISE_TYPES.ETH, gbl.constants.FUND_RAISE_TYPES.POLY, gbl.constants.FUND_RAISE_TYPES.STABLE];
  }

  return funding;
}
296025
def buy(ctx, buy_amount, buy_asset, price, sell_asset, order_expiration, account):
    
    amount = Amount(buy_amount, buy_asset)
    price = Price(
        price, base=sell_asset, quote=buy_asset, bitshares_instance=ctx.bitshares
    )
    print_tx(
        price.market.buy(price, amount, account=account, expiration=order_expiration)
    )