@stellar/stellar-base 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +1262 -0
  2. package/LICENSE +202 -0
  3. package/README.md +198 -0
  4. package/dist/stellar-base.js +30777 -0
  5. package/dist/stellar-base.min.js +2 -0
  6. package/lib/account.js +80 -0
  7. package/lib/address.js +169 -0
  8. package/lib/asset.js +323 -0
  9. package/lib/auth.js +253 -0
  10. package/lib/claimant.js +193 -0
  11. package/lib/contract.js +113 -0
  12. package/lib/events.js +42 -0
  13. package/lib/fee_bump_transaction.js +134 -0
  14. package/lib/generated/curr_generated.js +8315 -0
  15. package/lib/generated/next_generated.js +8315 -0
  16. package/lib/get_liquidity_pool_id.js +57 -0
  17. package/lib/hashing.js +12 -0
  18. package/lib/index.js +385 -0
  19. package/lib/invocation.js +195 -0
  20. package/lib/keypair.js +308 -0
  21. package/lib/liquidity_pool_asset.js +126 -0
  22. package/lib/liquidity_pool_id.js +101 -0
  23. package/lib/memo.js +270 -0
  24. package/lib/muxed_account.js +159 -0
  25. package/lib/network.js +22 -0
  26. package/lib/numbers/index.js +85 -0
  27. package/lib/numbers/int128.js +50 -0
  28. package/lib/numbers/int256.js +50 -0
  29. package/lib/numbers/sc_int.js +134 -0
  30. package/lib/numbers/uint128.js +50 -0
  31. package/lib/numbers/uint256.js +50 -0
  32. package/lib/numbers/xdr_large_int.js +267 -0
  33. package/lib/operation.js +715 -0
  34. package/lib/operations/account_merge.js +32 -0
  35. package/lib/operations/allow_trust.js +57 -0
  36. package/lib/operations/begin_sponsoring_future_reserves.js +38 -0
  37. package/lib/operations/bump_sequence.js +37 -0
  38. package/lib/operations/change_trust.js +52 -0
  39. package/lib/operations/claim_claimable_balance.js +40 -0
  40. package/lib/operations/clawback.js +46 -0
  41. package/lib/operations/clawback_claimable_balance.js +39 -0
  42. package/lib/operations/create_account.js +37 -0
  43. package/lib/operations/create_claimable_balance.js +65 -0
  44. package/lib/operations/create_passive_sell_offer.js +44 -0
  45. package/lib/operations/end_sponsoring_future_reserves.js +27 -0
  46. package/lib/operations/extend_footprint_ttl.js +45 -0
  47. package/lib/operations/index.js +254 -0
  48. package/lib/operations/inflation.js +23 -0
  49. package/lib/operations/invoke_host_function.js +219 -0
  50. package/lib/operations/liquidity_pool_deposit.js +64 -0
  51. package/lib/operations/liquidity_pool_withdraw.js +50 -0
  52. package/lib/operations/manage_buy_offer.js +50 -0
  53. package/lib/operations/manage_data.js +41 -0
  54. package/lib/operations/manage_sell_offer.js +50 -0
  55. package/lib/operations/path_payment_strict_receive.js +68 -0
  56. package/lib/operations/path_payment_strict_send.js +68 -0
  57. package/lib/operations/payment.js +47 -0
  58. package/lib/operations/restore_footprint.js +38 -0
  59. package/lib/operations/revoke_sponsorship.js +301 -0
  60. package/lib/operations/set_options.js +135 -0
  61. package/lib/operations/set_trustline_flags.js +84 -0
  62. package/lib/scval.js +369 -0
  63. package/lib/signerkey.js +103 -0
  64. package/lib/signing.js +96 -0
  65. package/lib/soroban.js +96 -0
  66. package/lib/sorobandata_builder.js +218 -0
  67. package/lib/strkey.js +400 -0
  68. package/lib/transaction.js +369 -0
  69. package/lib/transaction_base.js +248 -0
  70. package/lib/transaction_builder.js +753 -0
  71. package/lib/util/checksum.js +20 -0
  72. package/lib/util/continued_fraction.js +58 -0
  73. package/lib/util/decode_encode_muxed_account.js +116 -0
  74. package/lib/util/util.js +14 -0
  75. package/lib/xdr.js +9 -0
  76. package/package.json +133 -0
  77. package/types/curr.d.ts +14078 -0
  78. package/types/index.d.ts +1270 -0
  79. package/types/next.d.ts +14078 -0
  80. package/types/xdr.d.ts +1 -0
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+
3
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.Transaction = void 0;
8
+ var _xdr = _interopRequireDefault(require("./xdr"));
9
+ var _hashing = require("./hashing");
10
+ var _strkey = require("./strkey");
11
+ var _operation = require("./operation");
12
+ var _memo = require("./memo");
13
+ var _transaction_base = require("./transaction_base");
14
+ var _decode_encode_muxed_account = require("./util/decode_encode_muxed_account");
15
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
16
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
18
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
19
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
20
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
21
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
22
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
23
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
24
+ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
25
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
26
+ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
27
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
28
+ /**
29
+ * Use {@link TransactionBuilder} to build a transaction object. If you have an
30
+ * object or base64-encoded string of the transaction envelope XDR, use {@link
31
+ * TransactionBuilder.fromXDR}.
32
+ *
33
+ * Once a Transaction has been created, its attributes and operations should not
34
+ * be changed. You should only add signatures (using {@link Transaction#sign})
35
+ * to a Transaction object before submitting to the network or forwarding on to
36
+ * additional signers.
37
+ *
38
+ * @constructor
39
+ *
40
+ * @param {string|xdr.TransactionEnvelope} envelope - transaction envelope
41
+ * object or base64 encoded string
42
+ * @param {string} [networkPassphrase] - passphrase of the target stellar
43
+ * network (e.g. "Public Global Stellar Network ; September 2015")
44
+ *
45
+ * @extends TransactionBase
46
+ */
47
+ var Transaction = exports.Transaction = /*#__PURE__*/function (_TransactionBase) {
48
+ _inherits(Transaction, _TransactionBase);
49
+ var _super = _createSuper(Transaction);
50
+ function Transaction(envelope, networkPassphrase) {
51
+ var _this;
52
+ _classCallCheck(this, Transaction);
53
+ if (typeof envelope === 'string') {
54
+ var buffer = Buffer.from(envelope, 'base64');
55
+ envelope = _xdr["default"].TransactionEnvelope.fromXDR(buffer);
56
+ }
57
+ var envelopeType = envelope["switch"]();
58
+ if (!(envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTx())) {
59
+ throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(envelopeType.name, "."));
60
+ }
61
+ var txEnvelope = envelope.value();
62
+ var tx = txEnvelope.tx();
63
+ var fee = tx.fee().toString();
64
+ var signatures = (txEnvelope.signatures() || []).slice();
65
+ _this = _super.call(this, tx, signatures, fee, networkPassphrase);
66
+ _this._envelopeType = envelopeType;
67
+ _this._memo = tx.memo();
68
+ _this._sequence = tx.seqNum().toString();
69
+ switch (_this._envelopeType) {
70
+ case _xdr["default"].EnvelopeType.envelopeTypeTxV0():
71
+ _this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519());
72
+ break;
73
+ default:
74
+ _this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount());
75
+ break;
76
+ }
77
+ var cond = null;
78
+ var timeBounds = null;
79
+ switch (_this._envelopeType) {
80
+ case _xdr["default"].EnvelopeType.envelopeTypeTxV0():
81
+ timeBounds = tx.timeBounds();
82
+ break;
83
+ case _xdr["default"].EnvelopeType.envelopeTypeTx():
84
+ switch (tx.cond()["switch"]()) {
85
+ case _xdr["default"].PreconditionType.precondTime():
86
+ timeBounds = tx.cond().timeBounds();
87
+ break;
88
+ case _xdr["default"].PreconditionType.precondV2():
89
+ cond = tx.cond().v2();
90
+ timeBounds = cond.timeBounds();
91
+ break;
92
+ default:
93
+ break;
94
+ }
95
+ break;
96
+ default:
97
+ break;
98
+ }
99
+ if (timeBounds) {
100
+ _this._timeBounds = {
101
+ minTime: timeBounds.minTime().toString(),
102
+ maxTime: timeBounds.maxTime().toString()
103
+ };
104
+ }
105
+ if (cond) {
106
+ var ledgerBounds = cond.ledgerBounds();
107
+ if (ledgerBounds) {
108
+ _this._ledgerBounds = {
109
+ minLedger: ledgerBounds.minLedger(),
110
+ maxLedger: ledgerBounds.maxLedger()
111
+ };
112
+ }
113
+ var minSeq = cond.minSeqNum();
114
+ if (minSeq) {
115
+ _this._minAccountSequence = minSeq.toString();
116
+ }
117
+ _this._minAccountSequenceAge = cond.minSeqAge();
118
+ _this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap();
119
+ _this._extraSigners = cond.extraSigners();
120
+ }
121
+ var operations = tx.operations() || [];
122
+ _this._operations = operations.map(function (op) {
123
+ return _operation.Operation.fromXDRObject(op);
124
+ });
125
+ return _this;
126
+ }
127
+
128
+ /**
129
+ * @type {object}
130
+ * @property {string} 64 bit unix timestamp
131
+ * @property {string} 64 bit unix timestamp
132
+ * @readonly
133
+ */
134
+ _createClass(Transaction, [{
135
+ key: "timeBounds",
136
+ get: function get() {
137
+ return this._timeBounds;
138
+ },
139
+ set: function set(value) {
140
+ throw new Error('Transaction is immutable');
141
+ }
142
+
143
+ /**
144
+ * @type {object}
145
+ * @property {number} minLedger - smallest ledger bound (uint32)
146
+ * @property {number} maxLedger - largest ledger bound (or 0 for inf)
147
+ * @readonly
148
+ */
149
+ }, {
150
+ key: "ledgerBounds",
151
+ get: function get() {
152
+ return this._ledgerBounds;
153
+ },
154
+ set: function set(value) {
155
+ throw new Error('Transaction is immutable');
156
+ }
157
+
158
+ /**
159
+ * 64 bit account sequence
160
+ * @readonly
161
+ * @type {string}
162
+ */
163
+ }, {
164
+ key: "minAccountSequence",
165
+ get: function get() {
166
+ return this._minAccountSequence;
167
+ },
168
+ set: function set(value) {
169
+ throw new Error('Transaction is immutable');
170
+ }
171
+
172
+ /**
173
+ * 64 bit number of seconds
174
+ * @type {number}
175
+ * @readonly
176
+ */
177
+ }, {
178
+ key: "minAccountSequenceAge",
179
+ get: function get() {
180
+ return this._minAccountSequenceAge;
181
+ },
182
+ set: function set(value) {
183
+ throw new Error('Transaction is immutable');
184
+ }
185
+
186
+ /**
187
+ * 32 bit number of ledgers
188
+ * @type {number}
189
+ * @readonly
190
+ */
191
+ }, {
192
+ key: "minAccountSequenceLedgerGap",
193
+ get: function get() {
194
+ return this._minAccountSequenceLedgerGap;
195
+ },
196
+ set: function set(value) {
197
+ throw new Error('Transaction is immutable');
198
+ }
199
+
200
+ /**
201
+ * array of extra signers ({@link StrKey}s)
202
+ * @type {string[]}
203
+ * @readonly
204
+ */
205
+ }, {
206
+ key: "extraSigners",
207
+ get: function get() {
208
+ return this._extraSigners;
209
+ },
210
+ set: function set(value) {
211
+ throw new Error('Transaction is immutable');
212
+ }
213
+
214
+ /**
215
+ * @type {string}
216
+ * @readonly
217
+ */
218
+ }, {
219
+ key: "sequence",
220
+ get: function get() {
221
+ return this._sequence;
222
+ },
223
+ set: function set(value) {
224
+ throw new Error('Transaction is immutable');
225
+ }
226
+
227
+ /**
228
+ * @type {string}
229
+ * @readonly
230
+ */
231
+ }, {
232
+ key: "source",
233
+ get: function get() {
234
+ return this._source;
235
+ },
236
+ set: function set(value) {
237
+ throw new Error('Transaction is immutable');
238
+ }
239
+
240
+ /**
241
+ * @type {Array.<xdr.Operation>}
242
+ * @readonly
243
+ */
244
+ }, {
245
+ key: "operations",
246
+ get: function get() {
247
+ return this._operations;
248
+ },
249
+ set: function set(value) {
250
+ throw new Error('Transaction is immutable');
251
+ }
252
+
253
+ /**
254
+ * @type {string}
255
+ * @readonly
256
+ */
257
+ }, {
258
+ key: "memo",
259
+ get: function get() {
260
+ return _memo.Memo.fromXDRObject(this._memo);
261
+ },
262
+ set: function set(value) {
263
+ throw new Error('Transaction is immutable');
264
+ }
265
+
266
+ /**
267
+ * Returns the "signature base" of this transaction, which is the value
268
+ * that, when hashed, should be signed to create a signature that
269
+ * validators on the Stellar Network will accept.
270
+ *
271
+ * It is composed of a 4 prefix bytes followed by the xdr-encoded form
272
+ * of this transaction.
273
+ * @returns {Buffer}
274
+ */
275
+ }, {
276
+ key: "signatureBase",
277
+ value: function signatureBase() {
278
+ var tx = this.tx;
279
+
280
+ // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0
281
+ // we need a Transaction to generate the signature base
282
+ if (this._envelopeType === _xdr["default"].EnvelopeType.envelopeTypeTxV0()) {
283
+ tx = _xdr["default"].Transaction.fromXDR(Buffer.concat([
284
+ // TransactionV0 is a transaction with the AccountID discriminant
285
+ // stripped off, we need to put it back to build a valid transaction
286
+ // which we can use to build a TransactionSignaturePayloadTaggedTransaction
287
+ _xdr["default"].PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()]));
288
+ }
289
+ var taggedTransaction = new _xdr["default"].TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx);
290
+ var txSignature = new _xdr["default"].TransactionSignaturePayload({
291
+ networkId: _xdr["default"].Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)),
292
+ taggedTransaction: taggedTransaction
293
+ });
294
+ return txSignature.toXDR();
295
+ }
296
+
297
+ /**
298
+ * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network.
299
+ * @returns {xdr.TransactionEnvelope}
300
+ */
301
+ }, {
302
+ key: "toEnvelope",
303
+ value: function toEnvelope() {
304
+ var rawTx = this.tx.toXDR();
305
+ var signatures = this.signatures.slice(); // make a copy of the signatures
306
+
307
+ var envelope;
308
+ switch (this._envelopeType) {
309
+ case _xdr["default"].EnvelopeType.envelopeTypeTxV0():
310
+ envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTxV0(new _xdr["default"].TransactionV0Envelope({
311
+ tx: _xdr["default"].TransactionV0.fromXDR(rawTx),
312
+ // make a copy of tx
313
+ signatures: signatures
314
+ }));
315
+ break;
316
+ case _xdr["default"].EnvelopeType.envelopeTypeTx():
317
+ envelope = new _xdr["default"].TransactionEnvelope.envelopeTypeTx(new _xdr["default"].TransactionV1Envelope({
318
+ tx: _xdr["default"].Transaction.fromXDR(rawTx),
319
+ // make a copy of tx
320
+ signatures: signatures
321
+ }));
322
+ break;
323
+ default:
324
+ throw new Error("Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ".concat(this._envelopeType.name, "."));
325
+ }
326
+ return envelope;
327
+ }
328
+
329
+ /**
330
+ * Calculate the claimable balance ID for an operation within the transaction.
331
+ *
332
+ * @param {integer} opIndex the index of the CreateClaimableBalance op
333
+ * @returns {string} a hex string representing the claimable balance ID
334
+ *
335
+ * @throws {RangeError} for invalid `opIndex` value
336
+ * @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance`
337
+ * @throws for general XDR un/marshalling failures
338
+ *
339
+ * @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435
340
+ *
341
+ */
342
+ }, {
343
+ key: "getClaimableBalanceId",
344
+ value: function getClaimableBalanceId(opIndex) {
345
+ // Validate and then extract the operation from the transaction.
346
+ if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) {
347
+ throw new RangeError('invalid operation index');
348
+ }
349
+ var op = this.operations[opIndex];
350
+ try {
351
+ op = _operation.Operation.createClaimableBalance(op);
352
+ } catch (err) {
353
+ throw new TypeError("expected createClaimableBalance, got ".concat(op.type, ": ").concat(err));
354
+ }
355
+
356
+ // Always use the transaction's *unmuxed* source.
357
+ var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source));
358
+ var operationId = _xdr["default"].HashIdPreimage.envelopeTypeOpId(new _xdr["default"].HashIdPreimageOperationId({
359
+ sourceAccount: _xdr["default"].AccountId.publicKeyTypeEd25519(account),
360
+ seqNum: _xdr["default"].SequenceNumber.fromString(this.sequence),
361
+ opNum: opIndex
362
+ }));
363
+ var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw'));
364
+ var balanceId = _xdr["default"].ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash);
365
+ return balanceId.toXDR('hex');
366
+ }
367
+ }]);
368
+ return Transaction;
369
+ }(_transaction_base.TransactionBase);
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.TransactionBase = void 0;
7
+ var _xdr = _interopRequireDefault(require("./xdr"));
8
+ var _hashing = require("./hashing");
9
+ var _keypair = require("./keypair");
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
11
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
12
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
14
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
15
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
16
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
17
+ /**
18
+ * @ignore
19
+ */
20
+ var TransactionBase = exports.TransactionBase = /*#__PURE__*/function () {
21
+ function TransactionBase(tx, signatures, fee, networkPassphrase) {
22
+ _classCallCheck(this, TransactionBase);
23
+ if (typeof networkPassphrase !== 'string') {
24
+ throw new Error("Invalid passphrase provided to Transaction: expected a string but got a ".concat(_typeof(networkPassphrase)));
25
+ }
26
+ this._networkPassphrase = networkPassphrase;
27
+ this._tx = tx;
28
+ this._signatures = signatures;
29
+ this._fee = fee;
30
+ }
31
+
32
+ /**
33
+ * @type {Array.<xdr.DecoratedSignature>}
34
+ * @readonly
35
+ */
36
+ _createClass(TransactionBase, [{
37
+ key: "signatures",
38
+ get: function get() {
39
+ return this._signatures;
40
+ },
41
+ set: function set(value) {
42
+ throw new Error('Transaction is immutable');
43
+ }
44
+ }, {
45
+ key: "tx",
46
+ get: function get() {
47
+ return this._tx;
48
+ },
49
+ set: function set(value) {
50
+ throw new Error('Transaction is immutable');
51
+ }
52
+
53
+ /**
54
+ * @type {string}
55
+ * @readonly
56
+ */
57
+ }, {
58
+ key: "fee",
59
+ get: function get() {
60
+ return this._fee;
61
+ },
62
+ set: function set(value) {
63
+ throw new Error('Transaction is immutable');
64
+ }
65
+
66
+ /**
67
+ * @type {string}
68
+ * @readonly
69
+ */
70
+ }, {
71
+ key: "networkPassphrase",
72
+ get: function get() {
73
+ return this._networkPassphrase;
74
+ },
75
+ set: function set(networkPassphrase) {
76
+ this._networkPassphrase = networkPassphrase;
77
+ }
78
+
79
+ /**
80
+ * Signs the transaction with the given {@link Keypair}.
81
+ * @param {...Keypair} keypairs Keypairs of signers
82
+ * @returns {void}
83
+ */
84
+ }, {
85
+ key: "sign",
86
+ value: function sign() {
87
+ var _this = this;
88
+ var txHash = this.hash();
89
+ for (var _len = arguments.length, keypairs = new Array(_len), _key = 0; _key < _len; _key++) {
90
+ keypairs[_key] = arguments[_key];
91
+ }
92
+ keypairs.forEach(function (kp) {
93
+ var sig = kp.signDecorated(txHash);
94
+ _this.signatures.push(sig);
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Signs a transaction with the given {@link Keypair}. Useful if someone sends
100
+ * you a transaction XDR for you to sign and return (see
101
+ * [addSignature](#addSignature) for more information).
102
+ *
103
+ * When you get a transaction XDR to sign....
104
+ * - Instantiate a `Transaction` object with the XDR
105
+ * - Use {@link Keypair} to generate a keypair object for your Stellar seed.
106
+ * - Run `getKeypairSignature` with that keypair
107
+ * - Send back the signature along with your publicKey (not your secret seed!)
108
+ *
109
+ * Example:
110
+ * ```javascript
111
+ * // `transactionXDR` is a string from the person generating the transaction
112
+ * const transaction = new Transaction(transactionXDR, networkPassphrase);
113
+ * const keypair = Keypair.fromSecret(myStellarSeed);
114
+ * return transaction.getKeypairSignature(keypair);
115
+ * ```
116
+ *
117
+ * @param {Keypair} keypair Keypair of signer
118
+ * @returns {string} Signature string
119
+ */
120
+ }, {
121
+ key: "getKeypairSignature",
122
+ value: function getKeypairSignature(keypair) {
123
+ return keypair.sign(this.hash()).toString('base64');
124
+ }
125
+
126
+ /**
127
+ * Add a signature to the transaction. Useful when a party wants to pre-sign
128
+ * a transaction but doesn't want to give access to their secret keys.
129
+ * This will also verify whether the signature is valid.
130
+ *
131
+ * Here's how you would use this feature to solicit multiple signatures.
132
+ * - Use `TransactionBuilder` to build a new transaction.
133
+ * - Make sure to set a long enough timeout on that transaction to give your
134
+ * signers enough time to sign!
135
+ * - Once you build the transaction, use `transaction.toXDR()` to get the
136
+ * base64-encoded XDR string.
137
+ * - _Warning!_ Once you've built this transaction, don't submit any other
138
+ * transactions onto your account! Doing so will invalidate this pre-compiled
139
+ * transaction!
140
+ * - Send this XDR string to your other parties. They can use the instructions
141
+ * for [getKeypairSignature](#getKeypairSignature) to sign the transaction.
142
+ * - They should send you back their `publicKey` and the `signature` string
143
+ * from [getKeypairSignature](#getKeypairSignature), both of which you pass to
144
+ * this function.
145
+ *
146
+ * @param {string} publicKey The public key of the signer
147
+ * @param {string} signature The base64 value of the signature XDR
148
+ * @returns {void}
149
+ */
150
+ }, {
151
+ key: "addSignature",
152
+ value: function addSignature() {
153
+ var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
154
+ var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
155
+ if (!signature || typeof signature !== 'string') {
156
+ throw new Error('Invalid signature');
157
+ }
158
+ if (!publicKey || typeof publicKey !== 'string') {
159
+ throw new Error('Invalid publicKey');
160
+ }
161
+ var keypair;
162
+ var hint;
163
+ var signatureBuffer = Buffer.from(signature, 'base64');
164
+ try {
165
+ keypair = _keypair.Keypair.fromPublicKey(publicKey);
166
+ hint = keypair.signatureHint();
167
+ } catch (e) {
168
+ throw new Error('Invalid publicKey');
169
+ }
170
+ if (!keypair.verify(this.hash(), signatureBuffer)) {
171
+ throw new Error('Invalid signature');
172
+ }
173
+ this.signatures.push(new _xdr["default"].DecoratedSignature({
174
+ hint: hint,
175
+ signature: signatureBuffer
176
+ }));
177
+ }
178
+
179
+ /**
180
+ * Add a decorated signature directly to the transaction envelope.
181
+ *
182
+ * @param {xdr.DecoratedSignature} signature raw signature to add
183
+ * @returns {void}
184
+ *
185
+ * @see Keypair.signDecorated
186
+ * @see Keypair.signPayloadDecorated
187
+ */
188
+ }, {
189
+ key: "addDecoratedSignature",
190
+ value: function addDecoratedSignature(signature) {
191
+ this.signatures.push(signature);
192
+ }
193
+
194
+ /**
195
+ * Add `hashX` signer preimage as signature.
196
+ * @param {Buffer|String} preimage Preimage of hash used as signer
197
+ * @returns {void}
198
+ */
199
+ }, {
200
+ key: "signHashX",
201
+ value: function signHashX(preimage) {
202
+ if (typeof preimage === 'string') {
203
+ preimage = Buffer.from(preimage, 'hex');
204
+ }
205
+ if (preimage.length > 64) {
206
+ throw new Error('preimage cannnot be longer than 64 bytes');
207
+ }
208
+ var signature = preimage;
209
+ var hashX = (0, _hashing.hash)(preimage);
210
+ var hint = hashX.slice(hashX.length - 4);
211
+ this.signatures.push(new _xdr["default"].DecoratedSignature({
212
+ hint: hint,
213
+ signature: signature
214
+ }));
215
+ }
216
+
217
+ /**
218
+ * Returns a hash for this transaction, suitable for signing.
219
+ * @returns {Buffer}
220
+ */
221
+ }, {
222
+ key: "hash",
223
+ value: function hash() {
224
+ return (0, _hashing.hash)(this.signatureBase());
225
+ }
226
+ }, {
227
+ key: "signatureBase",
228
+ value: function signatureBase() {
229
+ throw new Error('Implement in subclass');
230
+ }
231
+ }, {
232
+ key: "toEnvelope",
233
+ value: function toEnvelope() {
234
+ throw new Error('Implement in subclass');
235
+ }
236
+
237
+ /**
238
+ * Get the transaction envelope as a base64-encoded string
239
+ * @returns {string} XDR string
240
+ */
241
+ }, {
242
+ key: "toXDR",
243
+ value: function toXDR() {
244
+ return this.toEnvelope().toXDR().toString('base64');
245
+ }
246
+ }]);
247
+ return TransactionBase;
248
+ }();