Source

js-stellar-base/src/operations/manage_buy_offer.js

  1. import { Hyper } from '@stellar/js-xdr';
  2. import xdr from '../xdr';
  3. /**
  4. * Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or
  5. * deletes a buy offer.
  6. * @function
  7. * @alias Operation.manageBuyOffer
  8. * @param {object} opts Options object
  9. * @param {Asset} opts.selling - What you're selling.
  10. * @param {Asset} opts.buying - What you're buying.
  11. * @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer.
  12. * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`.
  13. * @param {number} opts.price.n - If `opts.price` is an object: the price numerator
  14. * @param {number} opts.price.d - If `opts.price` is an object: the price denominator
  15. * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer.
  16. * @param {string} [opts.source] - The source account (defaults to transaction source).
  17. * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found.
  18. * @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation
  19. */
  20. export function manageBuyOffer(opts) {
  21. const attributes = {};
  22. attributes.selling = opts.selling.toXDRObject();
  23. attributes.buying = opts.buying.toXDRObject();
  24. if (!this.isValidAmount(opts.buyAmount, true)) {
  25. throw new TypeError(this.constructAmountRequirementsError('buyAmount'));
  26. }
  27. attributes.buyAmount = this._toXDRAmount(opts.buyAmount);
  28. if (opts.price === undefined) {
  29. throw new TypeError('price argument is required');
  30. }
  31. attributes.price = this._toXDRPrice(opts.price);
  32. if (opts.offerId !== undefined) {
  33. opts.offerId = opts.offerId.toString();
  34. } else {
  35. opts.offerId = '0';
  36. }
  37. attributes.offerId = Hyper.fromString(opts.offerId);
  38. const manageBuyOfferOp = new xdr.ManageBuyOfferOp(attributes);
  39. const opAttributes = {};
  40. opAttributes.body = xdr.OperationBody.manageBuyOffer(manageBuyOfferOp);
  41. this.setSourceAccount(opAttributes, opts);
  42. return new xdr.Operation(opAttributes);
  43. }