/
transaction.js
1666 lines (1366 loc) · 40.3 KB
/
transaction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const assert = require('assert');
const util = require('util');
const _ = require('lodash');
const {deriveKeypair, sign} = require('ripple-keypairs');
const EventEmitter = require('events').EventEmitter;
const utils = require('./utils');
const sjclcodec = require('sjcl-codec');
const Amount = require('./amount').Amount;
const Currency = require('./currency').Currency;
const RippleError = require('./rippleerror').RippleError;
const hashprefixes = require('./hashprefixes');
const log = require('./log').internal.sub('transaction');
const {isValidAddress, decodeAddress} = require('ripple-address-codec');
const binary = require('ripple-binary-codec');
/**
* @constructor Transaction
*
* Notes:
* All transactions including those with local and malformed errors may be
* forwarded anyway.
*
* A malicous server can:
* - may or may not forward
* - give any result
* + it may declare something correct as incorrect or something incorrect
* as correct
* + it may not communicate with the rest of the network
*/
function Transaction(remote) {
EventEmitter.call(this);
const self = this;
const remoteExists = (typeof remote === 'object');
this.remote = remote;
this.tx_json = {Flags: 0};
this._secret = undefined;
this._build_path = false;
this._should_resubmit = remoteExists
? this.remote.automatic_resubmission
: true;
this._maxFee = remoteExists ? this.remote.max_fee : undefined;
this._lastLedgerOffset = remoteExists ? this.remote.last_ledger_offset : 3;
this.state = 'unsubmitted';
this.finalized = false;
this.previousSigningHash = undefined;
this.submitIndex = undefined;
this.canonical = remoteExists ? this.remote.canonical_signing : true;
this.submittedIDs = [ ];
this.attempts = 0;
this.submissions = 0;
this.responses = 0;
this.once('success', function(message) {
// Transaction definitively succeeded
self.setState('validated');
self.finalize(message);
if (self._successHandler) {
self._successHandler(message);
}
});
this.once('error', function(message) {
// Transaction definitively failed
self.setState('failed');
self.finalize(message);
if (self._errorHandler) {
self._errorHandler(message);
}
});
this.once('submitted', function() {
// Transaction was submitted to the network
self.setState('submitted');
});
this.once('proposed', function() {
// Transaction was submitted successfully to the network
self.setState('pending');
});
}
util.inherits(Transaction, EventEmitter);
// This is currently a constant in rippled known as the "base reference"
// https://wiki.ripple.com/Transaction_Fee#Base_Fees
Transaction.fee_units = {
default: 10
};
Transaction.flags = {
// Universal flags can apply to any transaction type
Universal: {
FullyCanonicalSig: 0x80000000
},
AccountSet: {
RequireDestTag: 0x00010000,
OptionalDestTag: 0x00020000,
RequireAuth: 0x00040000,
OptionalAuth: 0x00080000,
DisallowXRP: 0x00100000,
AllowXRP: 0x00200000
},
TrustSet: {
SetAuth: 0x00010000,
NoRipple: 0x00020000,
SetNoRipple: 0x00020000,
ClearNoRipple: 0x00040000,
SetFreeze: 0x00100000,
ClearFreeze: 0x00200000
},
OfferCreate: {
Passive: 0x00010000,
ImmediateOrCancel: 0x00020000,
FillOrKill: 0x00040000,
Sell: 0x00080000
},
Payment: {
NoRippleDirect: 0x00010000,
PartialPayment: 0x00020000,
LimitQuality: 0x00040000
}
};
// The following are integer (as opposed to bit) flags
// that can be set for particular transactions in the
// SetFlag or ClearFlag field
Transaction.set_clear_flags = {
AccountSet: {
asfRequireDest: 1,
asfRequireAuth: 2,
asfDisallowXRP: 3,
asfDisableMaster: 4,
asfAccountTxnID: 5,
asfNoFreeze: 6,
asfGlobalFreeze: 7,
asfDefaultRipple: 8
}
};
Transaction.MEMO_TYPES = {};
/* eslint-disable max-len */
// URL characters per RFC 3986
Transaction.MEMO_REGEX = /^[0-9a-zA-Z-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\%]+$/;
/* eslint-enable max-len */
Transaction.formats = require('./binformat').tx;
Transaction.prototype.consts = {
telLOCAL_ERROR: -399,
temMALFORMED: -299,
tefFAILURE: -199,
terRETRY: -99,
tesSUCCESS: 0,
tecCLAIMED: 100
};
Transaction.prototype.isTelLocal = function(ter) {
return ter >= this.consts.telLOCAL_ERROR && ter < this.consts.temMALFORMED;
};
Transaction.prototype.isTemMalformed = function(ter) {
return ter >= this.consts.temMALFORMED && ter < this.consts.tefFAILURE;
};
Transaction.prototype.isTefFailure = function(ter) {
return ter >= this.consts.tefFAILURE && ter < this.consts.terRETRY;
};
Transaction.prototype.isTerRetry = function(ter) {
return ter >= this.consts.terRETRY && ter < this.consts.tesSUCCESS;
};
Transaction.prototype.isTepSuccess = function(ter) {
return ter >= this.consts.tesSUCCESS;
};
Transaction.prototype.isTecClaimed = function(ter) {
return ter >= this.consts.tecCLAIMED;
};
Transaction.prototype.isRejected = function(ter) {
return this.isTelLocal(ter) ||
this.isTemMalformed(ter) ||
this.isTefFailure(ter);
};
Transaction.from_json = function(j) {
return (new Transaction()).setJson(j);
};
Transaction.prototype.setJson =
Transaction.prototype.parseJson = function(v) {
this.tx_json = _.merge({}, v);
return this;
};
/**
* Set state on the condition that the state is different
*
* @param {String} state
*/
Transaction.prototype.setState = function(state) {
if (this.state !== state) {
this.state = state;
this.emit('state', state);
}
};
Transaction.prototype.setResubmittable = function(v) {
if (typeof v === 'boolean') {
this._should_resubmit = v;
}
};
Transaction.prototype.isResubmittable = function() {
return this._should_resubmit;
};
/**
* Finalize transaction. This will prevent future activity
*
* @param {Object} message
* @api private
*/
Transaction.prototype.finalize = function(message) {
this.finalized = true;
if (this.result) {
this.result.ledger_index = message.ledger_index;
this.result.ledger_hash = message.ledger_hash;
} else {
this.result = message;
this.result.tx_json = this.tx_json;
}
this.emit('cleanup');
this.emit('final', message);
if (this.remote && this.remote.trace) {
log.info('transaction finalized:',
this.tx_json, this.getManager()._pending.getLength());
}
return this;
};
/**
* Get transaction Account
*
* @return {Account}
*/
Transaction.prototype.getAccount = function() {
return this.tx_json.Account;
};
/**
* Get TransactionType
*
* @return {String}
*/
Transaction.prototype.getType =
Transaction.prototype.getTransactionType = function() {
return this.tx_json.TransactionType;
};
/**
* Get transaction TransactionManager
*
* @param [String] account
* @return {TransactionManager]
*/
Transaction.prototype.getManager = function(account) {
if (!this.remote) {
return undefined;
}
return this.remote.account(account || this.getAccount())._transactionManager;
};
/**
* Get transaction secret
*
* @param [String] account
*/
Transaction.prototype.getSecret =
Transaction.prototype._accountSecret = function(account) {
if (!this.remote) {
return undefined;
}
return this.remote.secrets[account || this.getAccount()];
};
/**
* Returns the number of fee units this transaction will cost.
*
* Each Ripple transaction based on its type and makeup costs a certain number
* of fee units. The fee units are calculated on a per-server basis based on the
* current load on both the network and the server.
*
* @see https://ripple.com/wiki/Transaction_Fee
*
* @return {Number} Number of fee units for this transaction.
*/
Transaction.prototype._getFeeUnits =
Transaction.prototype.feeUnits = function() {
return Transaction.fee_units.default;
};
/**
* Compute median server fee
*
* @return {String} median fee
*/
Transaction.prototype._computeFee = function() {
if (!this.remote) {
return undefined;
}
const servers = this.remote._servers;
const fees = [ ];
for (let i = 0; i < servers.length; i++) {
const server = servers[i];
if (server.isConnected()) {
fees.push(Number(server._computeFee(this._getFeeUnits())));
}
}
switch (fees.length) {
case 0: return undefined;
case 1: return String(fees[0]);
}
fees.sort(function ascending(a, b) {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
});
const midInd = Math.floor(fees.length / 2);
const median = fees.length % 2 === 0
? Math.floor(0.5 + (fees[midInd] + fees[midInd - 1]) / 2)
: fees[midInd];
return String(median);
};
/**
* Attempts to complete the transaction for submission.
*
* This function seeks to fill out certain fields, such as Fee and
* SigningPubKey, which can be determined by the library based on network
* information and other fields.
*
* @return {Boolean|Transaction} If succeeded, return transaction. Otherwise
* return `false`
*/
Transaction.prototype.err = function(error, errorMessage) {
this.emit('error', new RippleError(error, errorMessage));
return false;
};
Transaction.prototype.complete = function() {
const hasMultiSigners = this.hasMultiSigners();
if (!hasMultiSigners) {
// Auto-fill the secret
this._secret = this._secret || this.getSecret();
if (_.isUndefined(this._secret)) {
return this.err('tejSecretUnknown', 'Missing secret');
}
if (this.remote && !(this.remote.local_signing || this.remote.trusted)) {
return this.err(
'tejServerUntrusted',
'Attempt to give secret to untrusted server');
}
}
if (_.isUndefined(this.tx_json.SigningPubKey)) {
if (hasMultiSigners) {
this.setSigningPubKey('');
} else {
try {
this.setSigningPubKey(this.getSigningPubKey());
} catch (e) {
return this.err('tejSecretInvalid', 'Invalid secret');
}
}
}
// Auto-fill transaction Fee
if (_.isUndefined(this.tx_json.Fee)) {
if (this.remote && (this.remote.local_fee || !this.remote.trusted)) {
const computedFee = this._computeFee();
if (!computedFee) {
// Unable to compute fee due to no connected servers
return this.err('tejUnconnected');
}
this.tx_json.Fee = computedFee;
}
}
if (Number(this.tx_json.Fee) > this._maxFee) {
return this.err('tejMaxFeeExceeded', 'Max fee exceeded');
}
// Set canonical flag - this enables canonicalized signature checking
this.setCanonicalFlag();
return this.tx_json;
};
Transaction.prototype.getSigningPubKey = function(secret) {
return deriveKeypair(secret || this._secret).publicKey;
};
Transaction.prototype.setSigningPubKey = function(key) {
this.tx_json.SigningPubKey = key;
return this;
};
Transaction.prototype.setCanonicalFlag = function() {
if (this.remote && this.remote.local_signing && this.canonical) {
this.tx_json.Flags |= Transaction.flags.Universal.FullyCanonicalSig;
// JavaScript converts operands to 32-bit signed ints before doing bitwise
// operations. We need to convert it back to an unsigned int.
this.tx_json.Flags = this.tx_json.Flags >>> 0;
}
return this;
};
Transaction.prototype.serialize = function() {
return binary.encode(this.tx_json);
};
Transaction.prototype.signingHash = function(testnet) {
return this.hash(testnet ? 'HASH_TX_SIGN_TESTNET' : 'HASH_TX_SIGN');
};
Transaction.prototype.signingData = function() {
return binary.encodeForSigning(this.tx_json);
};
Transaction.prototype.multiSigningData = function(account) {
return binary.encodeForMultisigning(this.tx_json, account);
};
Transaction.prototype.hash = function(prefix_, serialized_) {
let prefix;
assert(serialized_ === undefined || _.isString(serialized_));
if (typeof prefix_ !== 'string') {
prefix = hashprefixes.HASH_TX_ID;
} else if (!hashprefixes.hasOwnProperty(prefix_)) {
throw new Error('Unknown hashing prefix requested: ' + prefix_);
} else {
prefix = hashprefixes[prefix_];
}
const hexPrefix = prefix.toString(16).toUpperCase();
const serialized = serialized_ || this.serialize();
return utils.sha512half(new Buffer(hexPrefix + serialized, 'hex'));
};
Transaction.prototype.sign = function(secret) {
if (this.hasMultiSigners()) {
return this;
}
const prev_sig = this.tx_json.TxnSignature;
delete this.tx_json.TxnSignature;
const hash = this.signingHash();
// If the hash is the same, we can re-use the previous signature
if (prev_sig && hash === this.previousSigningHash) {
this.tx_json.TxnSignature = prev_sig;
return this;
}
const keypair = deriveKeypair(secret || this._secret);
this.tx_json.TxnSignature = sign(new Buffer(this.signingData(), 'hex'),
keypair.privateKey);
this.previousSigningHash = hash;
return this;
};
/**
* Add an ID to cached list of submitted IDs
*
* @param {String} transaction id
* @api private
*/
Transaction.prototype.addId = function(id) {
if (!_.contains(this.submittedIDs, id)) {
this.submittedIDs.unshift(id);
}
};
/**
* Find ID within cached received (validated) IDs. If this transaction has
* an ID that is within the cache, it has been seen validated, so return the
* received message
*
* @param {Object} cache
* @return {Object} message
* @api private
*/
Transaction.prototype.findId = function(cache) {
const cachedTransactionID = _.detect(this.submittedIDs, function(id) {
return cache.hasOwnProperty(id);
});
return cache[cachedTransactionID];
};
/**
* Set client ID. This is an identifier specified by the user of the API to
* identify a transaction in the event of a disconnect. It is not currently
* persisted in the transaction itself, but used offline for identification.
* In applications that require high reliability, client-specified ID should
* be persisted such that one could map it to submitted transactions. Use
* .summary() for a consistent transaction summary output for persisitng. In
* the future, this ID may be stored in the transaction itself (in the ledger)
*
* @param {String} id
*/
Transaction.prototype.setClientID =
Transaction.prototype.clientID = function(id) {
if (typeof id === 'string') {
this._clientID = id;
}
return this;
};
Transaction.prototype.setLastLedgerSequenceOffset = function(offset) {
this._lastLedgerOffset = offset;
};
Transaction.prototype.getLastLedgerSequenceOffset = function() {
return this._lastLedgerOffset;
};
Transaction.prototype.lastLedger =
Transaction.prototype.setLastLedger =
Transaction.prototype.setLastLedgerSequence = function(sequence) {
if (!_.isUndefined(sequence)) {
this._setUInt32('LastLedgerSequence', sequence);
} else {
// Autofill LastLedgerSequence
assert(this.remote, 'Unable to set LastLedgerSequence, missing Remote');
this._setUInt32('LastLedgerSequence',
this.remote.getLedgerSequenceSync() + 1
+ this.getLastLedgerSequenceOffset());
}
this._setLastLedger = true;
return this;
};
/**
* Set max fee. Submission will abort if this is exceeded. Specified fee must
* be >= 0.
*
* @param {Number} fee The proposed fee
*/
Transaction.prototype.setMaxFee =
Transaction.prototype.maxFee = function(fee) {
if (typeof fee === 'number' && fee >= 0) {
this._setMaxFee = true;
this._maxFee = fee;
}
return this;
};
/*
* Set the fee user will pay to the network for submitting this transaction.
* Specified fee must be >= 0.
*
* @param {Number} fee The proposed fee
*
* @returns {Transaction} calling instance for chaining
*/
Transaction.prototype.setFixedFee = function(fee) {
return this.setFee(fee, {fixed: true});
};
Transaction.prototype.setFee = function(fee, options = {}) {
if (_.isNumber(fee) && fee >= 0) {
this.tx_json.Fee = String(fee);
if (options.fixed) {
this._setFixedFee = true;
}
}
return this;
};
Transaction.prototype.setSequence = function(sequence) {
if (_.isNumber(sequence)) {
this._setUInt32('Sequence', sequence);
this._setSequence = true;
}
return this;
};
/**
* Set secret If the secret has been set with Remote.setSecret, it does not
* need to be provided
*
* @param {String} secret
*/
Transaction.prototype.setSecret =
Transaction.prototype.secret = function(secret) {
if (typeof secret === 'string') {
this._secret = secret;
}
return this;
};
Transaction.prototype.setType = function(type) {
if (_.isUndefined(Transaction.formats, type)) {
throw new Error('TransactionType must be a valid transaction type');
}
this.tx_json.TransactionType = type;
return this;
};
Transaction.prototype._setUInt32 = function(name, value, options_) {
const options = _.merge({}, options_);
const isValidUInt32 = typeof value === 'number'
&& value >= 0 && value < Math.pow(256, 4);
if (!isValidUInt32) {
throw new Error(name + ' must be a valid UInt32');
}
if (!_.isUndefined(options.min_value) && value < options.min_value) {
throw new Error(name + ' must be >= ' + options.min_value);
}
this.tx_json[name] = value;
return this;
};
/**
* Set SourceTag
*
* @param {Number} source tag
*/
Transaction.prototype.setSourceTag =
Transaction.prototype.sourceTag = function(tag) {
return this._setUInt32('SourceTag', tag);
};
Transaction.prototype._setAccount = function(name, value) {
if (!isValidAddress(value)) {
throw new Error(name + ' must be a valid account');
}
this.tx_json[name] = value;
return this;
};
Transaction.prototype.setAccount = function(account) {
return this._setAccount('Account', account);
};
Transaction.prototype._setAmount = function(name, amount, options_) {
const options = _.merge({no_native: false}, options_);
const parsedAmount = Amount.from_json(amount);
if (parsedAmount.is_negative()) {
throw new Error(name + ' value must be non-negative');
}
const isNative = parsedAmount.currency().is_native();
if (isNative && options.no_native) {
throw new Error(name + ' must be a non-native amount');
}
if (!(isNative || parsedAmount.currency().is_valid())) {
throw new Error(name + ' must have a valid currency');
}
if (!(isNative || isValidAddress(parsedAmount.issuer()))) {
throw new Error(name + ' must have a valid issuer');
}
this.tx_json[name] = parsedAmount.to_json();
return this;
};
Transaction.prototype._setHash256 = function(name, value, options_) {
if (typeof value !== 'string') {
throw new Error(name + ' must be a valid Hash256');
}
const options = _.merge({pad: false}, options_);
let hash256 = value;
if (options.pad) {
while (hash256.length < 64) {
hash256 += '0';
}
}
if (!/^[0-9A-Fa-f]{64}$/.test(hash256)) {
throw new Error(name + ' must be a valid Hash256');
}
this.tx_json[name] = hash256;
return this;
};
Transaction.prototype.setAccountTxnID =
Transaction.prototype.accountTxnID = function(id) {
return this._setHash256('AccountTxnID', id);
};
/**
* Set Flags. You may specify flags as a number, as the string name of the
* flag, or as an array of strings.
*
* setFlags(Transaction.flags.AccountSet.RequireDestTag)
* setFlags('RequireDestTag')
* setFlags('RequireDestTag', 'RequireAuth')
* setFlags([ 'RequireDestTag', 'RequireAuth' ])
*
* @param {Number|String|Array} flags
*/
Transaction.prototype.setFlags = function(flags) {
if (flags === undefined) {
return this;
}
if (typeof flags === 'number') {
this.tx_json.Flags = flags;
return this;
}
const transaction_flags = Transaction.flags[this.getType()] || { };
const flag_set = Array.isArray(flags) ? flags : [].slice.call(arguments);
for (let i = 0, l = flag_set.length; i < l; i++) {
const flag = flag_set[i];
if (transaction_flags.hasOwnProperty(flag)) {
this.tx_json.Flags += transaction_flags[flag];
} else {
// XXX Should throw?
this.emit('error', new RippleError('tejInvalidFlag'));
return this;
}
}
return this;
};
function convertStringToHex(string) {
const utf8String = sjclcodec.utf8String.toBits(string);
return sjclcodec.hex.fromBits(utf8String).toUpperCase();
}
/**
* Add a Memo to transaction.
*
* @param [String] memoType
* - describes what the data represents, must contain valid URL characters
* @param [String] memoFormat
* - describes what format the data is in, MIME type, must contain valid URL
* - characters
* @param [String] memoData
* - data for the memo, can be any JS object. Any object other than string will
* be stringified (JSON) for transport
*/
Transaction.prototype.addMemo = function(options_) {
let options;
if (typeof options_ === 'object') {
options = _.merge({}, options_);
} else {
options = {
memoType: arguments[0],
memoFormat: arguments[1],
memoData: arguments[2]
};
}
const memo = {};
const memoRegex = Transaction.MEMO_REGEX;
let memoType = options.memoType;
const memoFormat = options.memoFormat;
let memoData = options.memoData;
if (memoType) {
if (!(_.isString(memoType) && memoRegex.test(memoType))) {
throw new Error(
'MemoType must be a string containing only valid URL characters');
}
if (Transaction.MEMO_TYPES[memoType]) {
// XXX Maybe in the future we want a schema validator for
// memo types
memoType = Transaction.MEMO_TYPES[memoType];
}
memo.MemoType = convertStringToHex(memoType);
}
if (memoFormat) {
if (!(_.isString(memoFormat) && memoRegex.test(memoFormat))) {
throw new Error(
'MemoFormat must be a string containing only valid URL characters');
}
memo.MemoFormat = convertStringToHex(memoFormat);
}
if (memoData) {
if (typeof memoData !== 'string') {
if (memoFormat.toLowerCase() === 'json') {
try {
memoData = JSON.stringify(memoData);
} catch (e) {
throw new Error(
'MemoFormat json with invalid JSON in MemoData field');
}
} else {
throw new Error(
'MemoData can only be a JSON object with a valid json MemoFormat');
}
}
memo.MemoData = convertStringToHex(memoData);
}
this.tx_json.Memos = (this.tx_json.Memos || []).concat({Memo: memo});
return this;
};
/**
* Construct an 'AccountSet' transaction
*
* Note that bit flags can be set using the .setFlags() method but for
* 'AccountSet' transactions there is an additional way to modify AccountRoot
* flags. The values available for the SetFlag and ClearFlag are as follows:
*
* asfRequireDest: Require a destination tag
* asfRequireAuth: Authorization is required to extend trust
* asfDisallowXRP: XRP should not be sent to this account
* asfDisableMaster: Disallow use of the master key
* asfNoFreeze: Permanently give up the ability to freeze individual
* trust lines. This flag can never be cleared.
* asfGlobalFreeze: Freeze all assets issued by this account
*
* @param [String] set flag
* @param [String] clear flag
*/
Transaction.prototype.accountSet = function(options_) {
let options;
if (typeof options_ === 'object') {
options = _.merge({}, options_);
if (_.isUndefined(options.account)) {
options.account = options.src;
}
if (_.isUndefined(options.set_flag)) {
options.set_flag = options.set;
}
if (_.isUndefined(options.clear_flag)) {
options.clear_flag = options.clear;
}
} else {
options = {
account: arguments[0],
set_flag: arguments[1],
clear_flag: arguments[2]
};
}
this.setType('AccountSet');
this.setAccount(options.account);
if (!_.isUndefined(options.set_flag)) {
this.setSetFlag(options.set_flag);
}
if (!_.isUndefined(options.clear_flag)) {
this.setClearFlag(options.clear_flag);
}
return this;
};
Transaction.prototype.setAccountSetFlag = function(name, value) {
const accountSetFlags = Transaction.set_clear_flags.AccountSet;
let flagValue = value;
if (typeof flagValue === 'string') {
flagValue = /^asf/.test(flagValue)
? accountSetFlags[flagValue]
: accountSetFlags['asf' + flagValue];
}
if (!_.contains(_.values(accountSetFlags), flagValue)) {
throw new Error(name + ' must be a valid AccountSet flag');
}
this.tx_json[name] = flagValue;
return this;
};
Transaction.prototype.setSetFlag = function(flag) {
return this.setAccountSetFlag('SetFlag', flag);
};
Transaction.prototype.setClearFlag = function(flag) {
return this.setAccountSetFlag('ClearFlag', flag);
};
/**
* Set TransferRate for AccountSet
*
* @param {Number} transfer rate
*/
Transaction.prototype.setTransferRate =
Transaction.prototype.transferRate = function(rate) {
const transferRate = rate;
if (transferRate === 0) {
// Clear TransferRate
this.tx_json.TransferRate = transferRate;
return this;
}
// if (rate >= 1 && rate < 2) {
// transferRate *= 1e9;
// }
return this._setUInt32('TransferRate', transferRate, {min_value: 1e9});
};
/**
* Construct a 'SetRegularKey' transaction
*
* If the RegularKey is set, the private key that corresponds to it can be
* used to sign transactions instead of the master key
*
* The RegularKey must be a valid Ripple Address, or a Hash160 of the public
* key corresponding to the new private signing key.
*
* @param {String} account
* @param {String} regular key
*/
Transaction.prototype.setRegularKey = function(options_) {