operations/path_payment_strict_send.js

  1. import xdr from '../xdr';
  2. import { decodeAddressToMuxedAccount } from '../util/decode_encode_muxed_account';
  3. /**
  4. * Creates a PathPaymentStrictSend operation.
  5. *
  6. * A `PathPaymentStrictSend` operation sends the specified amount to the
  7. * destination account crediting at least `destMin` of `destAsset`, optionally
  8. * through a path. XLM payments create the destination account if it does not
  9. * exist.
  10. *
  11. * @function
  12. * @alias Operation.pathPaymentStrictSend
  13. * @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send
  14. *
  15. * @param {object} opts - Options object
  16. * @param {Asset} opts.sendAsset - asset to pay with
  17. * @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees)
  18. * @param {string} opts.destination - destination account to send to
  19. * @param {Asset} opts.destAsset - asset the destination will receive
  20. * @param {string} opts.destMin - minimum amount of destAsset to be receive
  21. * @param {Asset[]} opts.path - array of Asset objects to use as the path
  22. *
  23. * @param {string} [opts.source] - The source account for the payment.
  24. * Defaults to the transaction's source account.
  25. *
  26. * @returns {xdr.Operation} the resulting path payment operation
  27. * (xdr.PathPaymentStrictSendOp)
  28. */
  29. export function pathPaymentStrictSend(opts) {
  30. switch (true) {
  31. case !opts.sendAsset:
  32. throw new Error('Must specify a send asset');
  33. case !this.isValidAmount(opts.sendAmount):
  34. throw new TypeError(this.constructAmountRequirementsError('sendAmount'));
  35. case !opts.destAsset:
  36. throw new Error('Must provide a destAsset for a payment operation');
  37. case !this.isValidAmount(opts.destMin):
  38. throw new TypeError(this.constructAmountRequirementsError('destMin'));
  39. default:
  40. break;
  41. }
  42. const attributes = {};
  43. attributes.sendAsset = opts.sendAsset.toXDRObject();
  44. attributes.sendAmount = this._toXDRAmount(opts.sendAmount);
  45. try {
  46. attributes.destination = decodeAddressToMuxedAccount(opts.destination);
  47. } catch (e) {
  48. throw new Error('destination is invalid');
  49. }
  50. attributes.destAsset = opts.destAsset.toXDRObject();
  51. attributes.destMin = this._toXDRAmount(opts.destMin);
  52. const path = opts.path ? opts.path : [];
  53. attributes.path = path.map((x) => x.toXDRObject());
  54. const payment = new xdr.PathPaymentStrictSendOp(attributes);
  55. const opAttributes = {};
  56. opAttributes.body = xdr.OperationBody.pathPaymentStrictSend(payment);
  57. this.setSourceAccount(opAttributes, opts);
  58. return new xdr.Operation(opAttributes);
  59. }