-
Notifications
You must be signed in to change notification settings - Fork 162
/
api.ts
2014 lines (1886 loc) · 66.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
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
/**
* @packageDocumentation
* @module API-PlatformVM
*/
import { Buffer } from "buffer/"
import BN from "bn.js"
import AvalancheCore from "../../avalanche"
import { JRPCAPI } from "../../common/jrpcapi"
import { RequestResponseData } from "../../common/apibase"
import {
ErrorResponseObject,
SubnetOwnerError,
SubnetThresholdError
} from "../../utils/errors"
import BinTools from "../../utils/bintools"
import { KeyChain } from "./keychain"
import { Defaults, PlatformChainID, ONEAVAX } from "../../utils/constants"
import { PlatformVMConstants } from "./constants"
import { UnsignedTx, Tx } from "./tx"
import { PayloadBase } from "../../utils/payload"
import { UnixNow, NodeIDStringToBuffer } from "../../utils/helperfunctions"
import { UTXO, UTXOSet } from "../platformvm/utxos"
import { PersistanceOptions } from "../../utils/persistenceoptions"
import {
AddressError,
TransactionError,
ChainIdError,
GooseEggCheckError,
TimeError,
StakeError,
DelegationFeeError
} from "../../utils/errors"
import {
GetCurrentValidatorsParams,
GetPendingValidatorsParams,
GetRewardUTXOsParams,
GetRewardUTXOsResponse,
GetStakeParams,
GetStakeResponse,
Subnet,
GetValidatorsAtParams,
GetValidatorsAtResponse,
CreateAddressParams,
GetUTXOsParams,
GetBalanceResponse,
GetUTXOsResponse,
ListAddressesParams,
SampleValidatorsParams,
AddValidatorParams,
AddDelegatorParams,
CreateSubnetParams,
ExportAVAXParams,
ExportKeyParams,
ImportKeyParams,
ImportAVAXParams,
CreateBlockchainParams,
Blockchain,
GetTxStatusParams,
GetTxStatusResponse,
GetMinStakeResponse,
GetMaxStakeAmountParams
} from "./interfaces"
import { TransferableOutput } from "./outputs"
import { Serialization, SerializedType } from "../../utils"
import { SubnetAuth } from "."
import { GenesisData } from "../avm"
/**
* @ignore
*/
const bintools: BinTools = BinTools.getInstance()
const serialization: Serialization = Serialization.getInstance()
/**
* Class for interacting with a node's PlatformVMAPI
*
* @category RPCAPIs
*
* @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche.
*/
export class PlatformVMAPI extends JRPCAPI {
/**
* @ignore
*/
protected keychain: KeyChain = new KeyChain("", "")
protected blockchainID: string = PlatformChainID
protected blockchainAlias: string = undefined
protected AVAXAssetID: Buffer = undefined
protected txFee: BN = undefined
protected creationTxFee: BN = undefined
protected minValidatorStake: BN = undefined
protected minDelegatorStake: BN = undefined
/**
* Gets the alias for the blockchainID if it exists, otherwise returns `undefined`.
*
* @returns The alias for the blockchainID
*/
getBlockchainAlias = (): string => {
if (typeof this.blockchainAlias === "undefined") {
const netid: number = this.core.getNetworkID()
if (
netid in Defaults.network &&
this.blockchainID in Defaults.network[`${netid}`]
) {
this.blockchainAlias =
Defaults.network[`${netid}`][this.blockchainID]["alias"]
return this.blockchainAlias
} else {
/* istanbul ignore next */
return undefined
}
}
return this.blockchainAlias
}
/**
* Sets the alias for the blockchainID.
*
* @param alias The alias for the blockchainID.
*
*/
setBlockchainAlias = (alias: string): string => {
this.blockchainAlias = alias
/* istanbul ignore next */
return undefined
}
/**
* Gets the blockchainID and returns it.
*
* @returns The blockchainID
*/
getBlockchainID = (): string => 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 => {
const netid: number = this.core.getNetworkID()
if (
typeof blockchainID === "undefined" &&
typeof Defaults.network[`${netid}`] !== "undefined"
) {
this.blockchainID = PlatformChainID //default to P-Chain
return true
}
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 => {
const alias: string = this.getBlockchainAlias()
const blockchainID: string = this.getBlockchainID()
return bintools.parseAddress(
addr,
blockchainID,
alias,
PlatformVMConstants.ADDRESSLENGTH
)
}
addressFromBuffer = (address: Buffer): string => {
const chainid: string = this.getBlockchainAlias()
? this.getBlockchainAlias()
: this.getBlockchainID()
const type: SerializedType = "bech32"
return serialization.bufferToType(
address,
type,
this.core.getHRP(),
chainid
)
}
/**
* Fetches the AVAX AssetID and returns it in a Promise.
*
* @param refresh This function caches the response. Refresh = true will bust the cache.
*
* @returns The the provided string representing the AVAX AssetID
*/
getAVAXAssetID = async (refresh: boolean = false): Promise<Buffer> => {
if (typeof this.AVAXAssetID === "undefined" || refresh) {
const assetID: string = await this.getStakingAssetID()
this.AVAXAssetID = bintools.cb58Decode(assetID)
}
return this.AVAXAssetID
}
/**
* Overrides the defaults and sets the cache to a specific AVAX AssetID
*
* @param avaxAssetID A cb58 string or Buffer representing the AVAX AssetID
*
* @returns The the provided string representing the AVAX AssetID
*/
setAVAXAssetID = (avaxAssetID: string | Buffer) => {
if (typeof avaxAssetID === "string") {
avaxAssetID = bintools.cb58Decode(avaxAssetID)
}
this.AVAXAssetID = avaxAssetID
}
/**
* Gets the default tx fee for this chain.
*
* @returns The default tx fee as a {@link https://github.com/indutny/bn.js/|BN}
*/
getDefaultTxFee = (): BN => {
return this.core.getNetworkID() in Defaults.network
? new BN(Defaults.network[this.core.getNetworkID()]["P"]["txFee"])
: new BN(0)
}
/**
* Gets the tx fee for this chain.
*
* @returns The tx fee as a {@link https://github.com/indutny/bn.js/|BN}
*/
getTxFee = (): BN => {
if (typeof this.txFee === "undefined") {
this.txFee = this.getDefaultTxFee()
}
return this.txFee
}
/**
* Gets the CreateSubnetTx fee.
*
* @returns The CreateSubnetTx fee as a {@link https://github.com/indutny/bn.js/|BN}
*/
getCreateSubnetTxFee = (): BN => {
return this.core.getNetworkID() in Defaults.network
? new BN(
Defaults.network[this.core.getNetworkID()]["P"]["createSubnetTx"]
)
: new BN(0)
}
/**
* Gets the CreateChainTx fee.
*
* @returns The CreateChainTx fee as a {@link https://github.com/indutny/bn.js/|BN}
*/
getCreateChainTxFee = (): BN => {
return this.core.getNetworkID() in Defaults.network
? new BN(Defaults.network[this.core.getNetworkID()]["P"]["createChainTx"])
: new BN(0)
}
/**
* Sets the tx fee for this chain.
*
* @param fee The tx fee amount to set as {@link https://github.com/indutny/bn.js/|BN}
*/
setTxFee = (fee: BN) => {
this.txFee = fee
}
/**
* Gets the default creation fee for this chain.
*
* @returns The default creation fee as a {@link https://github.com/indutny/bn.js/|BN}
*/
getDefaultCreationTxFee = (): BN => {
return this.core.getNetworkID() in Defaults.network
? new BN(Defaults.network[this.core.getNetworkID()]["P"]["creationTxFee"])
: new BN(0)
}
/**
* Gets the creation fee for this chain.
*
* @returns The creation fee as a {@link https://github.com/indutny/bn.js/|BN}
*/
getCreationTxFee = (): BN => {
if (typeof this.creationTxFee === "undefined") {
this.creationTxFee = this.getDefaultCreationTxFee()
}
return this.creationTxFee
}
/**
* Sets the creation fee for this chain.
*
* @param fee The creation fee amount to set as {@link https://github.com/indutny/bn.js/|BN}
*/
setCreationTxFee = (fee: BN) => {
this.creationTxFee = fee
}
/**
* Gets a reference to the keychain for this class.
*
* @returns The instance of [[]] for this class
*/
keyChain = (): KeyChain => this.keychain
/**
* @ignore
*/
newKeyChain = (): KeyChain => {
// warning, overwrites the old keychain
const alias = this.getBlockchainAlias()
if (alias) {
this.keychain = new KeyChain(this.core.getHRP(), alias)
} else {
this.keychain = new KeyChain(this.core.getHRP(), this.blockchainID)
}
return this.keychain
}
/**
* Helper function which determines if a tx is a goose egg transaction.
*
* @param utx An UnsignedTx
*
* @returns boolean true if passes goose egg test and false if fails.
*
* @remarks
* A "Goose Egg Transaction" is when the fee far exceeds a reasonable amount
*/
checkGooseEgg = async (
utx: UnsignedTx,
outTotal: BN = new BN(0)
): Promise<boolean> => {
const avaxAssetID: Buffer = await this.getAVAXAssetID()
let outputTotal: BN = outTotal.gt(new BN(0))
? outTotal
: utx.getOutputTotal(avaxAssetID)
const fee: BN = utx.getBurn(avaxAssetID)
if (fee.lte(ONEAVAX.mul(new BN(10))) || fee.lte(outputTotal)) {
return true
} else {
return false
}
}
/**
* Retrieves an assetID for a subnet"s staking assset.
*
* @returns Returns a Promise string with cb58 encoded value of the assetID.
*/
getStakingAssetID = async (): Promise<string> => {
const response: RequestResponseData = await this.callMethod(
"platform.getStakingAssetID"
)
return response.data.result.assetID
}
/**
* Creates a new blockchain.
*
* @param username The username of the Keystore user that controls the new account
* @param password The password of the Keystore user that controls the new account
* @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} or an cb58 serialized string for the SubnetID or its alias.
* @param vmID The ID of the Virtual Machine the blockchain runs. Can also be an alias of the Virtual Machine.
* @param fxIDs The ids of the FXs the VM is running.
* @param name A human-readable name for the new blockchain
* @param genesis The base 58 (with checksum) representation of the genesis state of the new blockchain. Virtual Machines should have a static API method named buildGenesis that can be used to generate genesisData.
*
* @returns Promise for the unsigned transaction to create this blockchain. Must be signed by a sufficient number of the Subnet’s control keys and by the account paying the transaction fee.
*/
createBlockchain = async (
username: string,
password: string,
subnetID: Buffer | string = undefined,
vmID: string,
fxIDs: number[],
name: string,
genesis: string
): Promise<string> => {
const params: CreateBlockchainParams = {
username,
password,
fxIDs,
vmID,
name,
genesisData: genesis
}
if (typeof subnetID === "string") {
params.subnetID = subnetID
} else if (typeof subnetID !== "undefined") {
params.subnetID = bintools.cb58Encode(subnetID)
}
const response: RequestResponseData = await this.callMethod(
"platform.createBlockchain",
params
)
return response.data.result.txID
}
/**
* Gets the status of a blockchain.
*
* @param blockchainID The blockchainID requesting a status update
*
* @returns Promise for a string of one of: "Validating", "Created", "Preferred", "Unknown".
*/
getBlockchainStatus = async (blockchainID: string): Promise<string> => {
const params: any = {
blockchainID
}
const response: RequestResponseData = await this.callMethod(
"platform.getBlockchainStatus",
params
)
return response.data.result.status
}
/**
* Get the validators and their weights of a subnet or the Primary Network at a given P-Chain height.
*
* @param height The P-Chain height to get the validator set at.
* @param subnetID Optional. A cb58 serialized string for the SubnetID or its alias.
*
* @returns Promise GetValidatorsAtResponse
*/
getValidatorsAt = async (
height: number,
subnetID?: string
): Promise<GetValidatorsAtResponse> => {
const params: GetValidatorsAtParams = {
height
}
if (typeof subnetID !== "undefined") {
params.subnetID = subnetID
}
const response: RequestResponseData = await this.callMethod(
"platform.getValidatorsAt",
params
)
return response.data.result
}
/**
* Create an address in the node's keystore.
*
* @param username The username of the Keystore user that controls the new account
* @param password The password of the Keystore user that controls the new account
*
* @returns Promise for a string of the newly created account address.
*/
createAddress = async (
username: string,
password: string
): Promise<string> => {
const params: CreateAddressParams = {
username,
password
}
const response: RequestResponseData = await this.callMethod(
"platform.createAddress",
params
)
return response.data.result.address
}
/**
* Gets the balance of a particular asset.
*
* @param addresses The addresses to pull the asset balance from
*
* @returns Promise with the balance as a {@link https://github.com/indutny/bn.js/|BN} on the provided address.
*/
getBalance = async (addresses: string[]): Promise<GetBalanceResponse> => {
addresses.forEach(address => {
if (typeof this.parseAddress(address) === "undefined") {
/* istanbul ignore next */
throw new AddressError(
"Error - PlatformVMAPI.getBalance: Invalid address format"
)
}
})
const params: any = {
addresses
}
const response: RequestResponseData = await this.callMethod(
"platform.getBalance",
params
)
return response.data.result
}
/**
* List the addresses controlled by the user.
*
* @param username The username of the Keystore user
* @param password The password of the Keystore user
*
* @returns Promise for an array of addresses.
*/
listAddresses = async (
username: string,
password: string
): Promise<string[]> => {
const params: ListAddressesParams = {
username,
password
}
const response: RequestResponseData = await this.callMethod(
"platform.listAddresses",
params
)
return response.data.result.addresses
}
/**
* Lists the set of current validators.
*
* @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} or an
* cb58 serialized string for the SubnetID or its alias.
* @param nodeIDs Optional. An array of strings
*
* @returns Promise for an array of validators that are currently staking, see: {@link https://docs.avax.network/v1.0/en/api/platform/#platformgetcurrentvalidators|platform.getCurrentValidators documentation}.
*
*/
getCurrentValidators = async (
subnetID: Buffer | string = undefined,
nodeIDs: string[] = undefined
): Promise<object> => {
const params: GetCurrentValidatorsParams = {}
if (typeof subnetID === "string") {
params.subnetID = subnetID
} else if (typeof subnetID !== "undefined") {
params.subnetID = bintools.cb58Encode(subnetID)
}
if (typeof nodeIDs != "undefined" && nodeIDs.length > 0) {
params.nodeIDs = nodeIDs
}
const response: RequestResponseData = await this.callMethod(
"platform.getCurrentValidators",
params
)
return response.data.result
}
/**
* Lists the set of pending validators.
*
* @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer}
* or a cb58 serialized string for the SubnetID or its alias.
* @param nodeIDs Optional. An array of strings
*
* @returns Promise for an array of validators that are pending staking, see: {@link https://docs.avax.network/v1.0/en/api/platform/#platformgetpendingvalidators|platform.getPendingValidators documentation}.
*
*/
getPendingValidators = async (
subnetID: Buffer | string = undefined,
nodeIDs: string[] = undefined
): Promise<object> => {
const params: GetPendingValidatorsParams = {}
if (typeof subnetID === "string") {
params.subnetID = subnetID
} else if (typeof subnetID !== "undefined") {
params.subnetID = bintools.cb58Encode(subnetID)
}
if (typeof nodeIDs != "undefined" && nodeIDs.length > 0) {
params.nodeIDs = nodeIDs
}
const response: RequestResponseData = await this.callMethod(
"platform.getPendingValidators",
params
)
return response.data.result
}
/**
* Samples `Size` validators from the current validator set.
*
* @param sampleSize Of the total universe of validators, select this many at random
* @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} or an
* cb58 serialized string for the SubnetID or its alias.
*
* @returns Promise for an array of validator"s stakingIDs.
*/
sampleValidators = async (
sampleSize: number,
subnetID: Buffer | string = undefined
): Promise<string[]> => {
const params: SampleValidatorsParams = {
size: sampleSize.toString()
}
if (typeof subnetID === "string") {
params.subnetID = subnetID
} else if (typeof subnetID !== "undefined") {
params.subnetID = bintools.cb58Encode(subnetID)
}
const response: RequestResponseData = await this.callMethod(
"platform.sampleValidators",
params
)
return response.data.result.validators
}
/**
* Add a validator to the Primary Network.
*
* @param username The username of the Keystore user
* @param password The password of the Keystore user
* @param nodeID The node ID of the validator
* @param startTime Javascript Date object for the start time to validate
* @param endTime Javascript Date object for the end time to validate
* @param stakeAmount The amount of nAVAX the validator is staking as
* a {@link https://github.com/indutny/bn.js/|BN}
* @param rewardAddress The address the validator reward will go to, if there is one.
* @param delegationFeeRate Optional. A {@link https://github.com/indutny/bn.js/|BN} for the percent fee this validator
* charges when others delegate stake to them. Up to 4 decimal places allowed additional decimal places are ignored.
* Must be between 0 and 100, inclusive. For example, if delegationFeeRate is 1.2345 and someone delegates to this
* validator, then when the delegation period is over, 1.2345% of the reward goes to the validator and the rest goes
* to the delegator.
*
* @returns Promise for a base58 string of the unsigned transaction.
*/
addValidator = async (
username: string,
password: string,
nodeID: string,
startTime: Date,
endTime: Date,
stakeAmount: BN,
rewardAddress: string,
delegationFeeRate: BN = undefined
): Promise<string> => {
const params: AddValidatorParams = {
username,
password,
nodeID,
startTime: startTime.getTime() / 1000,
endTime: endTime.getTime() / 1000,
stakeAmount: stakeAmount.toString(10),
rewardAddress
}
if (typeof delegationFeeRate !== "undefined") {
params.delegationFeeRate = delegationFeeRate.toString(10)
}
const response: RequestResponseData = await this.callMethod(
"platform.addValidator",
params
)
return response.data.result.txID
}
/**
* Add a validator to a Subnet other than the Primary Network. The validator must validate the Primary Network for the entire duration they validate this Subnet.
*
* @param username The username of the Keystore user
* @param password The password of the Keystore user
* @param nodeID The node ID of the validator
* @param subnetID Either a {@link https://github.com/feross/buffer|Buffer} or a cb58 serialized string for the SubnetID or its alias.
* @param startTime Javascript Date object for the start time to validate
* @param endTime Javascript Date object for the end time to validate
* @param weight The validator’s weight used for sampling
*
* @returns Promise for the unsigned transaction. It must be signed (using sign) by the proper number of the Subnet’s control keys and by the key of the account paying the transaction fee before it can be issued.
*/
addSubnetValidator = async (
username: string,
password: string,
nodeID: string,
subnetID: Buffer | string,
startTime: Date,
endTime: Date,
weight: number
): Promise<string> => {
const params: any = {
username,
password,
nodeID,
startTime: startTime.getTime() / 1000,
endTime: endTime.getTime() / 1000,
weight
}
if (typeof subnetID === "string") {
params.subnetID = subnetID
} else if (typeof subnetID !== "undefined") {
params.subnetID = bintools.cb58Encode(subnetID)
}
const response: RequestResponseData = await this.callMethod(
"platform.addSubnetValidator",
params
)
return response.data.result.txID
}
/**
* Add a delegator to the Primary Network.
*
* @param username The username of the Keystore user
* @param password The password of the Keystore user
* @param nodeID The node ID of the delegatee
* @param startTime Javascript Date object for when the delegator starts delegating
* @param endTime Javascript Date object for when the delegator starts delegating
* @param stakeAmount The amount of nAVAX the delegator is staking as
* a {@link https://github.com/indutny/bn.js/|BN}
* @param rewardAddress The address of the account the staked AVAX and validation reward
* (if applicable) are sent to at endTime
*
* @returns Promise for an array of validator"s stakingIDs.
*/
addDelegator = async (
username: string,
password: string,
nodeID: string,
startTime: Date,
endTime: Date,
stakeAmount: BN,
rewardAddress: string
): Promise<string> => {
const params: AddDelegatorParams = {
username,
password,
nodeID,
startTime: startTime.getTime() / 1000,
endTime: endTime.getTime() / 1000,
stakeAmount: stakeAmount.toString(10),
rewardAddress
}
const response: RequestResponseData = await this.callMethod(
"platform.addDelegator",
params
)
return response.data.result.txID
}
/**
* Create an unsigned transaction to create a new Subnet. The unsigned transaction must be
* signed with the key of the account paying the transaction fee. The Subnet’s ID is the ID of the transaction that creates it (ie the response from issueTx when issuing the signed transaction).
*
* @param username The username of the Keystore user
* @param password The password of the Keystore user
* @param controlKeys Array of platform addresses as strings
* @param threshold To add a validator to this Subnet, a transaction must have threshold
* signatures, where each signature is from a key whose address is an element of `controlKeys`
*
* @returns Promise for a string with the unsigned transaction encoded as base58.
*/
createSubnet = async (
username: string,
password: string,
controlKeys: string[],
threshold: number
): Promise<string | ErrorResponseObject> => {
const params: CreateSubnetParams = {
username,
password,
controlKeys,
threshold
}
const response: RequestResponseData = await this.callMethod(
"platform.createSubnet",
params
)
return response.data.result.txID
? response.data.result.txID
: response.data.result
}
/**
* Get the Subnet that validates a given blockchain.
*
* @param blockchainID Either a {@link https://github.com/feross/buffer|Buffer} or a cb58
* encoded string for the blockchainID or its alias.
*
* @returns Promise for a string of the subnetID that validates the blockchain.
*/
validatedBy = async (blockchainID: string): Promise<string> => {
const params: any = {
blockchainID
}
const response: RequestResponseData = await this.callMethod(
"platform.validatedBy",
params
)
return response.data.result.subnetID
}
/**
* Get the IDs of the blockchains a Subnet validates.
*
* @param subnetID Either a {@link https://github.com/feross/buffer|Buffer} or an AVAX
* serialized string for the SubnetID or its alias.
*
* @returns Promise for an array of blockchainIDs the subnet validates.
*/
validates = async (subnetID: Buffer | string): Promise<string[]> => {
const params: any = {
subnetID
}
if (typeof subnetID === "string") {
params.subnetID = subnetID
} else if (typeof subnetID !== "undefined") {
params.subnetID = bintools.cb58Encode(subnetID)
}
const response: RequestResponseData = await this.callMethod(
"platform.validates",
params
)
return response.data.result.blockchainIDs
}
/**
* Get all the blockchains that exist (excluding the P-Chain).
*
* @returns Promise for an array of objects containing fields "id", "subnetID", and "vmID".
*/
getBlockchains = async (): Promise<Blockchain[]> => {
const response: RequestResponseData = await this.callMethod(
"platform.getBlockchains"
)
return response.data.result.blockchains
}
/**
* Send AVAX from an account on the P-Chain to an address on the X-Chain. This transaction
* must be signed with the key of the account that the AVAX is sent from and which pays the
* transaction fee. After issuing this transaction, you must call the X-Chain’s importAVAX
* method to complete the transfer.
*
* @param username The Keystore user that controls the account specified in `to`
* @param password The password of the Keystore user
* @param to The address on the X-Chain to send the AVAX to. Do not include X- in the address
* @param amount Amount of AVAX 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 AVAX is
* sent from and pays the transaction fee.
*/
exportAVAX = async (
username: string,
password: string,
amount: BN,
to: string
): Promise<string | ErrorResponseObject> => {
const params: ExportAVAXParams = {
username,
password,
to,
amount: amount.toString(10)
}
const response: RequestResponseData = await this.callMethod(
"platform.exportAVAX",
params
)
return response.data.result.txID
? response.data.result.txID
: response.data.result
}
/**
* Send AVAX from an account on the P-Chain to an address on the X-Chain. This transaction
* must be signed with the key of the account that the AVAX is sent from and which pays
* the transaction fee. After issuing this transaction, you must call the X-Chain’s
* importAVAX method to complete the transfer.
*
* @param username The Keystore user that controls the account specified in `to`
* @param password The password of the Keystore user
* @param to The ID of the account the AVAX is sent to. This must be the same as the to
* argument in the corresponding call to the X-Chain’s exportAVAX
* @param sourceChain The chainID where the funds are coming from.
*
* @returns Promise for a string for the transaction, which should be sent to the network
* by calling issueTx.
*/
importAVAX = async (
username: string,
password: string,
to: string,
sourceChain: string
): Promise<string | ErrorResponseObject> => {
const params: ImportAVAXParams = {
to,
sourceChain,
username,
password
}
const response: RequestResponseData = await this.callMethod(
"platform.importAVAX",
params
)
return response.data.result.txID
? response.data.result.txID
: response.data.result
}
/**
* 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 = ""
if (typeof tx === "string") {
Transaction = tx
} else if (tx instanceof Buffer) {
const txobj: Tx = new Tx()
txobj.fromBuffer(tx)
Transaction = txobj.toStringHex()
} else if (tx instanceof Tx) {
Transaction = tx.toStringHex()
} else {
/* istanbul ignore next */
throw new TransactionError(
"Error - platform.issueTx: provided tx is not expected type of string, Buffer, or Tx"
)
}
const params: any = {
tx: Transaction.toString(),
encoding: "hex"
}
const response: RequestResponseData = await this.callMethod(
"platform.issueTx",
params
)
return response.data.result.txID
}
/**
* Returns an upper bound on the amount of tokens that exist. Not monotonically increasing because this number can go down if a staker"s reward is denied.
*/
getCurrentSupply = async (): Promise<BN> => {
const response: RequestResponseData = await this.callMethod(
"platform.getCurrentSupply"
)
return new BN(response.data.result.supply, 10)
}
/**
* Returns the height of the platform chain.
*/
getHeight = async (): Promise<BN> => {
const response: RequestResponseData = await this.callMethod(
"platform.getHeight"
)
return new BN(response.data.result.height, 10)
}
/**
* Gets the minimum staking amount.
*
* @param refresh A boolean to bypass the local cached value of Minimum Stake Amount, polling the node instead.
*/
getMinStake = async (
refresh: boolean = false
): Promise<GetMinStakeResponse> => {
if (
refresh !== true &&
typeof this.minValidatorStake !== "undefined" &&
typeof this.minDelegatorStake !== "undefined"
) {
return {
minValidatorStake: this.minValidatorStake,
minDelegatorStake: this.minDelegatorStake
}
}
const response: RequestResponseData = await this.callMethod(
"platform.getMinStake"
)
this.minValidatorStake = new BN(response.data.result.minValidatorStake, 10)
this.minDelegatorStake = new BN(response.data.result.minDelegatorStake, 10)
return {
minValidatorStake: this.minValidatorStake,
minDelegatorStake: this.minDelegatorStake
}
}
/**
* getTotalStake() returns the total amount staked on the Primary Network
*
* @returns A big number representing total staked by validators on the primary network
*/
getTotalStake = async (): Promise<BN> => {
const response: RequestResponseData = await this.callMethod(
"platform.getTotalStake"
)
return new BN(response.data.result.stake, 10)
}