-
Notifications
You must be signed in to change notification settings - Fork 162
/
api.ts
782 lines (734 loc) · 30.9 KB
/
api.ts
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
/**
* @module AVMAPI
*/
import SlopesCore from '../../slopes';
import { Buffer } from "buffer/";
import { JRPCAPI, RequestResponseData, Defaults } from "../../utils/types";
import { UTXOSet } from './utxos';
import { MergeRule, UnixNow, AVMConstants, InitialStates } from './types';
import { AVMKeyChain } from './keychain';
import { TxUnsigned, Tx, TxCreateAsset } from './tx';
import BN from "bn.js";
import BinTools from '../../utils/bintools';
/**
* @ignore
*/
const bintools = BinTools.getInstance();
/**
* A class for defining the persistance behavior of this an API call.
*
*/
export class PersistanceOptions {
protected name:string = undefined;
protected overwrite:boolean = false;
protected mergeRule:MergeRule = "union";
/**
* Returns the namespace of the instance
*/
getName = ():string => {
return this.name;
}
/**
* Returns the overwrite rule of the instance
*/
getOverwrite = ():boolean => {
return this.overwrite;
}
/**
* Returns the [[MergeRule]] of the instance
*/
getMergeRule = ():MergeRule => {
return this.mergeRule;
}
/**
*
* @param name The namespace of the database the data
* @param overwrite True if the data should be completey overwritten
* @param MergeRule The type of process used to merge with existing data: "intersection", "differenceSelf", "differenceNew", "symDifference", "union", "unionMinusNew", "unionMinusSelf"
*
* @remarks
* The merge rules are as follows:
* * "intersection" - the intersection of the set
* * "differenceSelf" - the difference between the existing data and new set
* * "differenceNew" - the difference between the new data and the existing set
* * "symDifference" - the union of the differences between both sets of data
* * "union" - the unique set of all elements contained in both sets
* * "unionMinusNew" - the unique set of all elements contained in both sets, excluding values only found in the new set
* * "unionMinusSelf" - the unique set of all elements contained in both sets, excluding values only found in the existing set
*/
constructor(name:string, overwrite:boolean = false, mergeRule:MergeRule) {
this.name = name;
this.overwrite = overwrite;
this.mergeRule = mergeRule;
}
}
/**
* Class for interacting with a node endpoint that is using the AVM.
*
* @category RPCAPIs
*
* @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Slopes.addAPI]] function to register this interface with Slopes.
*/
class AVMAPI extends JRPCAPI{
/**
* @ignore
*/
protected keychain:AVMKeyChain = new AVMKeyChain("");
protected blockchainID:string = "";
protected AVAAssetID:Buffer = undefined;
/**
* Gets the alias for the blockchainID if it exists, otherwise returns `undefined`.
*
* @returns The alias for the blockchainID
*/
getBlockchainAlias = ():string => {
let netid:number = this.core.getNetworkID();
if(netid in Defaults.network && this.blockchainID in Defaults.network[netid]){
return Defaults.network[netid][this.blockchainID].alias;
}
/* istanbul ignore next */
return undefined;
}
/**
* Gets the blockchainID and returns it.
*
* @returns The blockchainID
*/
getBlockchainID = ():string => {
return this.blockchainID;
}
/**
* Refresh blockchainID, and if a blockchainID is passed in, use that.
*
* @param Optional. BlockchainID to assign, if none, uses the default based on networkID.
*
* @returns The blockchainID
*/
refreshBlockchainID = (blockchainID:string = undefined):boolean => {
let netid:number = this.core.getNetworkID();
if(typeof blockchainID === "undefined" && netid in Defaults.network) {
this.blockchainID = Defaults.network[netid]["avm"].blockchainID;
return true
} else if(typeof blockchainID === "string") {
this.blockchainID = blockchainID;
return true;
}
return false;
}
/**
* Takes an address string and returns its {@link https://github.com/feross/buffer|Buffer} representation if valid.
*
* @returns A {@link https://github.com/feross/buffer|Buffer} for the address if valid, undefined if not valid.
*/
parseAddress = (addr:string):Buffer => {
let alias:string = this.getBlockchainAlias();
let blockchainID:string = this.getBlockchainID();
return bintools.parseAddress(addr, blockchainID, alias, AVMConstants.ADDRESSLENGTH);
}
addressFromBuffer = (address:Buffer):string => {
let chainid:string = this.getBlockchainAlias() ? this.getBlockchainAlias() : this.getBlockchainID();
return bintools.addressToString(chainid, address);
}
/**
* Fetches the AVA AssetID and returns it in a Promise.
*
* @returns The the provided string representing the blockchainID
*/
getAVAAssetID = async ():Promise<Buffer> => {
if(typeof this.AVAAssetID === 'undefined'){
let asset:object = await this.getAssetDescription("AVA");
this.AVAAssetID = asset["assetID"];
}
return this.AVAAssetID;
}
/**
* Gets a reference to the keychain for this class.
*
* @returns The instance of [[AVMKeyChain]] for this class
*/
keyChain = ():AVMKeyChain => {
return this.keychain;
}
/**
* @ignore
*/
newKeyChain = ():AVMKeyChain => {
//warning, overwrites the old keychain
let alias = this.getBlockchainAlias();
if(alias){
this.keychain = new AVMKeyChain(alias);
} else {
this.keychain = new AVMKeyChain(this.blockchainID);
}
return this.keychain;
}
/**
* Gets the balance of a particular asset on a blockchain.
*
* @param address The address to pull the asset balance from
* @param assetID The assetID to pull the balance from
*
* @returns Promise with the balance of the assetID as a {@link https://github.com/indutny/bn.js/|BN} on the provided address for the blockchain.
*/
getBalance = async (address:string, assetID:string):Promise<BN> => {
if(typeof this.parseAddress(address) === "undefined"){
/* istanbul ignore next */
throw new Error("Error - AVMAPI.getBalance: Invalid address format " + address);
}
let params = {
"address": address,
"assetID": assetID
};
return this.callMethod("avm.getBalance", params).then((response:RequestResponseData) => {
return new BN(response.data["result"]["balance"], 10);
});
}
/**
* Creates an address (and associated private keys) on a user on a blockchain.
*
* @param username Name of the user to create the address under
* @param password Password to unlock the user and encrypt the private key
*
* @returns Promise for a string representing the address created by the vm.
*/
createAddress = async (username:string, password:string):Promise<string> => {
let params = {
"username": username,
"password": password
};
return this.callMethod("avm.createAddress", params).then((response:RequestResponseData) => {
return response.data["result"]["address"];
});
}
/**
* Create a new fixed-cap, fungible asset. A quantity of it is created at initialization and there no more is ever created.
*
* @param username The user paying the transaction fee (in $AVA) for asset creation
* @param password The password for the user paying the transaction fee (in $AVA) for asset creation
* @param name The human-readable name for the asset
* @param symbol Optional. The shorthand symbol for the asset. Between 0 and 4 characters
* @param initialHolders An array of objects containing the field "address" and "amount" to establish the genesis values for the new asset
*
* ```js
* Example initialHolders:
* [
* {
* "address": "X-7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh",
* "amount": 10000
* },
* {
* "address": "X-7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh",
* "amount": 50000
* }
* ]
* ```
*
* @returns Returns a Promise<string> containing the base 58 string representation of the ID of the newly created asset.
*/
createFixedCapAsset = async (username:string, password:string, name:string, symbol:string, initialHolders:Array<object>):Promise<string> => {
let params = {
"name": name,
"symbol": symbol,
"username": username,
"password": password,
"initialHolders": initialHolders
};
return this.callMethod("avm.createFixedCapAsset", params).then((response:RequestResponseData) => {
return response.data["result"]["assetID"];
});
}
/**
* Create a new variable-cap, fungible asset. No units of the asset exist at initialization. Minters can mint units of this asset using createMintTx, signMintTx and sendMintTx.
*
* @param username The user paying the transaction fee (in $AVA) for asset creation
* @param password The password for the user paying the transaction fee (in $AVA) for asset creation
* @param name The human-readable name for the asset
* @param symbol Optional. The shorthand symbol for the asset -- between 0 and 4 characters
* @param minterSets is a list where each element specifies that threshold of the addresses in minters may together mint more of the asset by signing a minting transaction
*
* ```js
* Example minterSets:
* [
* {
* "minters":[
* "X-4peJsFvhdn7XjhNF4HWAQy6YaJts27s9q"
* ],
* "threshold": 1
* },
* {
* "minters": [
* "X-dcJ6z9duLfyQTgbjq2wBCowkvcPZHVDF",
* "X-2fE6iibqfERz5wenXE6qyvinsxDvFhHZk",
* "X-7ieAJbfrGQbpNZRAQEpZCC1Gs1z5gz4HU"
* ],
* "threshold": 2
* }
* ]
* ```
*
* @returns Returns a Promise<string> containing the base 58 string representation of the ID of the newly created asset.
*/
createVariableCapAsset = async (username:string, password:string, name:string, symbol:string, minterSets:Array<object>):Promise<string> => {
let params = {
"name": name,
"symbol": symbol,
"username": username,
"password": password,
"minterSets": minterSets
};
return this.callMethod("avm.createVariableCapAsset", params).then((response:RequestResponseData) => {
return response.data["result"]["assetID"];
});
}
/**
* Create an unsigned transaction to mint more of an asset.
*
* @param amount The units of the asset to mint
* @param assetID The ID of the asset to mint
* @param to The address to assign the units of the minted asset
* @param minters Addresses of the minters responsible for signing the transaction
*
* @returns Returns a Promise<string> containing the base 58 string representation of the unsigned transaction.
*/
createMintTx = async (amount:number | BN, assetID:Buffer | string, to:string, minters:Array<string>):Promise<string> => {
let asset:string;
let amnt:BN;
if(typeof assetID !== "string"){
asset = bintools.avaSerialize(assetID);
} else {
asset = assetID;
}
if(typeof amount === 'number'){
amnt = new BN(amount);
} else {
amnt = amount;
}
let params = {
"amount": amnt.toString(10),
"assetID": asset,
"to": to,
"minters": minters
};
return this.callMethod("avm.createMintTx", params).then((response:RequestResponseData) => {
return response.data["result"]["tx"];
});
}
/**
* Sign an unsigned or partially signed mint transaction.
*
* @param username The user signing
* @param password The password for the user signing
* @param tx The output of createMintTx or signMintTx
* @param minter The minter signing this transaction
*
* @returns Returns a Promise<string> containing the base 58 string representation of the unsigned transaction.
*/
signMintTx = async (username:string, password:string, tx:string | Buffer, minter:string):Promise<string> => {
if(typeof this.parseAddress(minter) === "undefined"){
/* istanbul ignore next */
throw new Error("Error - AVMAPI.signMintTx: Invalid address format " + minter);
}
let params = {
"username": username,
"password": password,
"tx": tx,
"minter": minter
};
return this.callMethod("avm.signMintTx", params).then((response:RequestResponseData) => {
return response.data["result"]["tx"];
});
}
/**
* Exports the private key for an address.
*
* @param username The name of the user with the private key
* @param password The password used to decrypt the private key
* @param address The address whose private key should be exported
*
* @returns Promise with the decrypted private key as store in the database
*/
exportKey = async (username:string, password:string, address:string):Promise<string> => {
if(typeof this.parseAddress(address) === "undefined"){
/* istanbul ignore next */
throw new Error("Error - AVMAPI.exportKey: Invalid address format " + address);
}
let params = {
"username": username,
"password": password,
"address": address
};
return this.callMethod("avm.exportKey", params).then((response:RequestResponseData) => {
return response.data["result"]["privateKey"];
});
}
/**
* Imports a private key into the node's keystore under an user and for a blockchain.
*
* @param username The name of the user to store the private key
* @param password The password that unlocks the user
* @param privateKey A string representing the private key in the vm's format
*
* @returns The address for the imported private key.
*/
importKey = async (username:string, password:string, privateKey:string):Promise<string> => {
let params = {
"username": username,
"password": password,
"privateKey": privateKey
};
return this.callMethod("avm.importKey", params).then((response:RequestResponseData) => {
return response.data["result"]["address"];
});
}
/**
* Send AVA from the X-Chain to an account on the P-Chain.
*
* After calling this method, you must call the P-Chain’s importAVA method to complete the transfer.
*
* @param username The Keystore user that controls the P-Chain account specified in `to`
* @param password The password of the Keystore user
* @param to The acount on the P-Chain to send the AVA to. Do not include P- in the address
* @param amount Amount of AVA to export as a {@link https://github.com/indutny/bn.js/|BN}
*
* @returns Promise for an unsigned transaction to be signed by the account the the AVA is sent from and pays the transaction fee.
*/
exportAVA = async (username: string, password:string, to:string, amount:BN):Promise<string> => {
let params = {
"to": to,
"amount": amount,
"username": username,
"password": password
}
return this.callMethod("avm.exportAVA", params).then((response:RequestResponseData) => {
return response.data["result"]["txID"];
});
}
/**
* Finalize a transfer of AVA from the P-Chain to the X-Chain.
*
* Before this method is called, you must call the P-Chain’s `exportAVA` method to initiate the transfer.
*
* @param to The address the AVA is sent to. This must be the same as the to argument in the corresponding call to the P-Chain’s exportAVA, except that the prepended X- should be included in this argument
* @param username The Keystore user that controls the address specified in `to`
* @param password The password of the Keystore user
*
* @returns Promise for a string for the transaction, which should be sent to the network by calling issueTx.
*/
importAVA = async (username: string, password:string, to:string):Promise<string> => {
let params = {
"to": to,
"username": username,
"password": password
}
return this.callMethod("avm.importAVA", params).then((response:RequestResponseData) => {
return response.data["result"]["txID"];
});
}
/**
* Lists all the addresses under a user.
*
* @param username The user to list addresses
* @param password The password of the user to list the addresses
*
* @returns Promise of an array of address strings in the format specified by the blockchain.
*/
listAddresses = async (username:string, password:string): Promise<Array<string>> => {
let params = {
"username": username,
"password": password
};
return this.callMethod("avm.listAddresses", params).then((response:RequestResponseData) => {
return response.data["result"]["addresses"];
});
}
/**
* Retrieves all assets for an address on a server and their associated balances.
*
* @param address The address to get a list of assets
*
* @returns Promise of an object mapping assetID strings with {@link https://github.com/indutny/bn.js/|BN} balance for the address on the blockchain.
*/
getAllBalances = async (address:string):Promise<object> => {
if(typeof this.parseAddress(address) === "undefined"){
/* istanbul ignore next */
throw new Error("Error - AVMAPI.listAssets: Invalid address format " + address);
}
let params = {
"address": address
};
return this.callMethod("avm.getAllBalances", params).then((response:RequestResponseData) => {
let r = response.data["result"]["assets"];
let assetIDs = Object.keys(r);
for(let i = 0; i < assetIDs.length; i++){
r[assetIDs[i]] = new BN(r[assetIDs[i]], 10);
}
return r;
});
}
/**
* Retrieves an assets name and symbol.
*
* @param assetID Either a {@link https://github.com/feross/buffer|Buffer} or an AVA serialized string for the AssetID or its alias.
*
* @returns Returns a Promise<object> with keys "name" and "symbol".
*/
getAssetDescription = async(assetID:Buffer | string):Promise<{name:string;symbol:string;assetID:Buffer;denomination:number}> => {
let asset:string;
if(typeof assetID !== "string"){
asset = bintools.avaSerialize(assetID);
} else {
asset = assetID;
}
let params = {
"assetID": asset
};
return this.callMethod("avm.getAssetDescription", params).then((response:RequestResponseData) => {
return {
name: response.data["result"]["name"],
symbol: response.data["result"]["symbol"],
assetID: bintools.avaDeserialize(response.data["result"]["assetID"]),
denomination: parseInt(response.data["result"]["denomination"])
};
});
}
/**
* Returns the status of a provided transaction ID by calling the node's `getTxStatus` method.
*
* @param txid The string representation of the transaction ID
*
* @returns Returns a Promise<string> containing the status retrieved from the node
*/
getTxStatus = async (txid:string):Promise<string> => {
let params = {
"txID": txid
};
return this.callMethod("avm.getTxStatus", params).then((response:RequestResponseData) => {
return response.data["result"]["status"];
});
}
/**
* Retrieves the UTXOs related to the addresses provided from the node's `getUTXOs` method.
*
* @param addresses An array of addresses as strings or addresses as {@link https://github.com/feross/buffer|Buffer}s
* @param persistOpts Options available to persist these UTXOs in local storage
*
* @remarks
* persistOpts is optional and must be of type [[PersistanceOptions]]
*
*/
getUTXOs = async (addresses:Array<string> | Array<Buffer>, persistOpts:PersistanceOptions = undefined ):Promise<UTXOSet> => {
let addrs:Array<string> = this._cleanAddressArray(addresses, "getUTXOs");
let params = {
"addresses": addrs
};
return this.callMethod("avm.getUTXOs", params).then((response:RequestResponseData) => {
let utxos:UTXOSet = new UTXOSet();
let data = response.data["result"]["utxos"];
if(persistOpts && typeof persistOpts === 'object'){
if(this.db.has(persistOpts.getName())){
let selfArray:Array<string> = this.db.get(persistOpts.getName());
if(Array.isArray(selfArray)){
utxos.addArray(data);
let self:UTXOSet = new UTXOSet();
self.addArray(selfArray);
self.mergeByRule(utxos, persistOpts.getMergeRule())
data = self.getAllUTXOStrings();
}
}
this.db.set(persistOpts.getName(), data, persistOpts.getOverwrite());
}
utxos.addArray(data);
return utxos;
});
}
/**
* Helper function which creates an unsigned transaction. For more granular control, you may create your own
* [[TxUnsigned]] manually (with their corresponding [[Input]]s and [[Output]]s.
*
* @param utxoset A set of UTXOs that the transaction is built on
* @param amount The amount of AVA to be spent in $nAVA
* @param toAddresses The addresses to send the funds
* @param fromAddresses The addresses being used to send the funds from the UTXOs provided
* @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs
* @param assetID The assetID of the value being sent
* @param asOf The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN}
* @param locktime The locktime field created in the resulting outputs
* @param threshold The number of signatures required to spend the funds in the resultant UTXO
*
* @returns An unsigned transaction created from the passed in parameters.
*
* @remarks
* This helper exists because the endpoint API should be the primary point of entry for most functionality.
*/
makeUnsignedTx = async (
utxoset:UTXOSet, amount:BN, toAddresses:Array<string>, fromAddresses:Array<string>,
changeAddresses:Array<string>, assetID:Buffer | string = undefined, asOf:BN = UnixNow(),
locktime:BN = new BN(0), threshold:number = 1
):Promise<TxUnsigned> => {
let to:Array<Buffer> = this._cleanAddressArray(toAddresses, "makeUnsignedTx").map(a => bintools.stringToAddress(a));;
let from:Array<Buffer> = this._cleanAddressArray(fromAddresses, "makeUnsignedTx").map(a => bintools.stringToAddress(a));;
let change:Array<Buffer> = this._cleanAddressArray(changeAddresses, "makeUnsignedTx").map(a => bintools.stringToAddress(a));;
if(typeof assetID === "string"){
assetID = bintools.avaDeserialize(assetID);
}
return utxoset.makeUnsignedTx(
this.core.getNetworkID(), bintools.avaDeserialize(this.blockchainID),
amount, to, from, change,
assetID, asOf, locktime, threshold
);
}
/**
* Creates an unsigned transaction. For more granular control, you may create your own
* [[TxCreateAsset]] manually (with their corresponding [[Input]]s, [[Output]]s).
*
* @param utxoset A set of UTXOs that the transaction is built on
* @param fee The amount of AVA to be paid for fees, in $nAVA
* @param creatorAddresses The addresses to send the fees
* @param initialState The [[InitialStates]] that represent the intial state of a created asset
* @param name String for the descriptive name of the asset
* @param symbol String for the ticker symbol of the asset
* @param denomination Optional number for the denomination which is 10^D. D must be >= 0 and <= 32. Ex: $1 AVA = 10^9 $nAVA
*
* @returns An unsigned transaction created from the passed in parameters.
*
*/
makeCreateAssetTx = async (
utxoset:UTXOSet, fee:BN, creatorAddresses:Array<string> | Array<Buffer>,
initialState:InitialStates, name:string,
symbol:string, denomination:number
):Promise<TxCreateAsset> => {
let creators:Array<Buffer> = this._cleanAddressArray(creatorAddresses, "makeCreateAssetTx").map(a => bintools.stringToAddress(a));
/* istanbul ignore next */
if(symbol.length > AVMConstants.SYMBOLMAXLEN){
/* istanbul ignore next */
throw new Error("Error - AVMAPI.makeCreateAssetTx: Symbols may not exceed length of " + AVMConstants.SYMBOLMAXLEN);
}
/* istanbul ignore next */
if(name.length > AVMConstants.ASSETNAMELEN) {
/* istanbul ignore next */
throw new Error("Error - AVMAPI.makeCreateAssetTx: Names may not exceed length of " + AVMConstants.ASSETNAMELEN);
}
let avaAssetID:Buffer = await this.getAVAAssetID();
return utxoset.makeCreateAssetTx(
this.core.getNetworkID(), bintools.avaDeserialize(this.blockchainID), avaAssetID,
fee, creators, initialState, name, symbol, denomination
);
}
/**
* Helper function which takes an unsigned transaction and signs it, returning the resulting [[Tx]].
*
* @param utx The unsigned transaction of type [[TxUnsigned]]
*
* @returns A signed transaction of type [[Tx]]
*/
signTx = (utx:TxUnsigned):Tx => {
return this.keychain.signTx(utx);
}
/**
* Calls the node's issueTx method from the API and returns the resulting transaction ID as a string.
*
* @param tx A string, {@link https://github.com/feross/buffer|Buffer}, or [[Tx]] representing a transaction
*
* @returns A Promise<string> representing the transaction ID of the posted transaction.
*/
issueTx = async (tx:string | Buffer | Tx):Promise<string> => {
let Transaction = new Tx();
if(typeof tx === 'string'){
Transaction.fromString(tx);
} else if(tx instanceof Buffer){
Transaction.fromBuffer(tx);
} else if(tx instanceof Tx) {
Transaction = tx;
} else {
/* istanbul ignore next */
throw new Error("Error - avm.issueTx: provided tx is not expected type of string, Buffer, or Tx");
}
let params = {
"tx": Transaction.toString()
};
return this.callMethod("avm.issueTx", params).then((response:RequestResponseData) => {
return response.data["result"]["txID"];
});
}
/**
* Sends an amount of assetID to the specified address from a list of owned of addresses.
*
* @param username The user that owns the private keys associated with the `from` addresses
* @param password The password unlocking the user
* @param assetID The assetID of the asset to send
* @param amount The amount of the asset to be sent
* @param to The address of the recipient
* @param from An array of addresses managed by the node's keystore for this blockchain which will fund this transaction
*
* @returns Promise for the string representing the transaction's ID.
*/
send = async (username:string, password:string, assetID:string | Buffer, amount:number | BN, to:string, from:Array<string> | Array<Buffer>):Promise<string> => {
let asset:string;
let amnt:BN;
if(typeof this.parseAddress(to) === "undefined"){
/* istanbul ignore next */
throw new Error("Error - AVMAPI.listAssets: Invalid address format " + to);
}
from = this._cleanAddressArray(from, "send")
if(typeof assetID !== "string"){
asset = bintools.avaSerialize(assetID);
} else {
asset = assetID;
}
if(typeof amount === 'number'){
amnt = new BN(amount);
} else {
amnt = amount;
}
let params = {
"username": username,
"password": password,
"assetID": asset,
"amount": amnt.toString(10),
"to": to,
"from": from
};
return this.callMethod("avm.send", params).then((response:RequestResponseData) => {
return response.data["result"]["txID"];
});
}
/**
* @ignore
*/
protected _cleanAddressArray(addresses:Array<string> | Array<Buffer>, caller:string):Array<string> {
let addrs:Array<string> = [];
let chainid:string = this.getBlockchainAlias() ? this.getBlockchainAlias() : this.getBlockchainID();
if(addresses && addresses.length > 0){
for(let i = 0; i < addresses.length; i++){
if(typeof addresses[i] === "string"){
if(typeof this.parseAddress(addresses[i] as string) === "undefined"){
/* istanbul ignore next */
throw new Error("Error - AVMAPI." + caller + ": Invalid address format " + addresses[i]);
}
addrs.push(addresses[i] as string);
} else {
addrs.push(bintools.addressToString(chainid, addresses[i] as Buffer))
}
}
}
return addrs;
}
/**
* This class should not be instantiated directly. Instead use the [[Slopes.addAPI]] method.
*
* @param core A reference to the Slopes class
* @param baseurl Defaults to the string "/ext/bc/avm" as the path to blockchain's baseurl
*/
constructor(core:SlopesCore, baseurl:string = "/ext/bc/avm", blockchainID:string = ""){
super(core, baseurl);
this.blockchainID = blockchainID
let netid:number = core.getNetworkID();
if(netid in Defaults.network && blockchainID in Defaults.network[netid]){
let alias = Defaults.network[netid][blockchainID].alias;
this.keychain = new AVMKeyChain(alias);
} else {
this.keychain = new AVMKeyChain(blockchainID);
}
}
}
export default AVMAPI;