@avalabs/core-wallets-sdk 3.1.0-alpha.18 → 3.1.0-alpha.19
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.
- package/dist/index.d.ts +135 -2
- package/dist/index.js +1 -1
- package/esm/Avalanche/index.d.ts +1 -1
- package/esm/Avalanche/index.js +1 -1
- package/esm/Avalanche/models.d.ts +41 -2
- package/esm/Avalanche/models.js +1 -1
- package/esm/Avalanche/utils/createAvalancheUnsignedTx.js +1 -1
- package/esm/Avalanche/utils/handleSubnetAuth.js +1 -1
- package/esm/Avalanche/utils/parsers/index.js +1 -1
- package/esm/Avalanche/utils/parsers/parseConvertSubnetToL1Tx.js +1 -0
- package/esm/Avalanche/utils/parsers/parseDisableL1ValidatorTx.js +1 -0
- package/esm/Avalanche/utils/parsers/parseIncreaseL1ValidatorBalanceTx.js +1 -0
- package/esm/Avalanche/utils/parsers/parseRegisterL1ValidatorTx.js +1 -0
- package/esm/Avalanche/utils/parsers/parseSetL1ValidatorWeightTx.js +1 -0
- package/esm/Avalanche/wallets/TxBuilderTypes.d.ts +70 -1
- package/esm/Avalanche/wallets/WalletAbstract.d.ts +7 -2
- package/esm/Avalanche/wallets/WalletAbstract.js +1 -1
- package/package.json +5 -5
package/dist/index.d.ts
CHANGED
|
@@ -566,7 +566,7 @@ type ChainIDAlias = 'X' | 'P' | 'C';
|
|
|
566
566
|
/**
|
|
567
567
|
* Types for parsed transaction
|
|
568
568
|
*/
|
|
569
|
-
type Tx = AddValidatorTx | AddDelegatorTx | ExportTx | ImportTx | BaseTx$1 | CreateSubnetTx | CreateChainTx | AddSubnetValidatorTx | RemoveSubnetValidatorTx | AddPermissionlessValidatorTx | AddPermissionlessDelegatorTx | TransformSubnetTx | TransferSubnetOwnershipTx$1 | UnknownTx;
|
|
569
|
+
type Tx = AddValidatorTx | AddDelegatorTx | ExportTx | ImportTx | BaseTx$1 | CreateSubnetTx | CreateChainTx | AddSubnetValidatorTx | RemoveSubnetValidatorTx | AddPermissionlessValidatorTx | AddPermissionlessDelegatorTx | TransformSubnetTx | TransferSubnetOwnershipTx$1 | ConvertSubnetToL1Tx | RegisterL1ValidatorTx | SetL1ValidatorWeightTx | DisableL1ValidatorTx | IncreaseL1ValidatorBalanceTx | UnknownTx;
|
|
570
570
|
interface FeeData {
|
|
571
571
|
totalAvaxBurned: bigint;
|
|
572
572
|
totalAvaxOutput: bigint;
|
|
@@ -586,6 +586,11 @@ declare enum TxType {
|
|
|
586
586
|
Import = "import",
|
|
587
587
|
CreateSubnet = "create_subnet",
|
|
588
588
|
CreateChain = "create_chain",
|
|
589
|
+
ConvertSubnetToL1 = "convert_subnet_to_l1",
|
|
590
|
+
RegisterL1Validator = "register_l1_validator",
|
|
591
|
+
SetL1ValidatorWeight = "set_l1_validator_weight",
|
|
592
|
+
IncreaseL1ValidatorBalance = "increase_l1_validator_balance",
|
|
593
|
+
DisableL1Validator = "disable_l1_validator",
|
|
589
594
|
AddSubnetValidator = "add_subnet_validator",
|
|
590
595
|
RemoveSubnetValidator = "remove_subnet_validator",
|
|
591
596
|
AddPermissionlessValidator = "add_permissionless_validator",
|
|
@@ -664,6 +669,35 @@ interface RemoveSubnetValidatorTx extends TxBase {
|
|
|
664
669
|
nodeID: string;
|
|
665
670
|
subnetID: string;
|
|
666
671
|
}
|
|
672
|
+
interface ConvertSubnetToL1Tx extends TxBase {
|
|
673
|
+
type: TxType.ConvertSubnetToL1;
|
|
674
|
+
managerAddress: string;
|
|
675
|
+
validators: {
|
|
676
|
+
nodeId: string;
|
|
677
|
+
stake: bigint;
|
|
678
|
+
balance: bigint;
|
|
679
|
+
remainingBalanceOwners: string[];
|
|
680
|
+
deactivationOwners: string[];
|
|
681
|
+
}[];
|
|
682
|
+
subnetID: string;
|
|
683
|
+
chainID: string;
|
|
684
|
+
}
|
|
685
|
+
interface RegisterL1ValidatorTx extends TxBase {
|
|
686
|
+
type: TxType.RegisterL1Validator;
|
|
687
|
+
balance: bigint;
|
|
688
|
+
}
|
|
689
|
+
interface SetL1ValidatorWeightTx extends TxBase {
|
|
690
|
+
type: TxType.SetL1ValidatorWeight;
|
|
691
|
+
}
|
|
692
|
+
interface IncreaseL1ValidatorBalanceTx extends TxBase {
|
|
693
|
+
type: TxType.IncreaseL1ValidatorBalance;
|
|
694
|
+
balance: bigint;
|
|
695
|
+
validationId: string;
|
|
696
|
+
}
|
|
697
|
+
interface DisableL1ValidatorTx extends TxBase {
|
|
698
|
+
type: TxType.DisableL1Validator;
|
|
699
|
+
validationId: string;
|
|
700
|
+
}
|
|
667
701
|
interface AddPermissionlessValidatorTx extends TxBase {
|
|
668
702
|
type: TxType.AddPermissionlessValidator;
|
|
669
703
|
nodeID: string;
|
|
@@ -723,6 +757,11 @@ declare function isAddDelegatorTx(tx: Tx): tx is AddDelegatorTx;
|
|
|
723
757
|
declare function isExportTx(tx: Tx): tx is ExportTx;
|
|
724
758
|
declare function isImportTx(tx: Tx): tx is ImportTx;
|
|
725
759
|
declare function isBaseTx(tx: Tx): tx is BaseTx$1;
|
|
760
|
+
declare function isConvertSubnetToL1Tx(tx: Tx): tx is ConvertSubnetToL1Tx;
|
|
761
|
+
declare function isRegisterL1ValidatorTx(tx: Tx): tx is RegisterL1ValidatorTx;
|
|
762
|
+
declare function isSetL1ValidatorWeightTx(tx: Tx): tx is SetL1ValidatorWeightTx;
|
|
763
|
+
declare function isDisableL1ValidatorTx(tx: Tx): tx is DisableL1ValidatorTx;
|
|
764
|
+
declare function isIncreaseL1ValidatorBalance(tx: Tx): tx is IncreaseL1ValidatorBalanceTx;
|
|
726
765
|
declare function isCreateSubnetTx(tx: Tx): tx is CreateSubnetTx;
|
|
727
766
|
declare function isCreateChainTx(tx: Tx): tx is CreateChainTx;
|
|
728
767
|
declare function isAddSubnetValidatorTx(tx: Tx): tx is AddSubnetValidatorTx;
|
|
@@ -846,6 +885,75 @@ type CreateSubnet = {
|
|
|
846
885
|
threshold?: number;
|
|
847
886
|
locktime?: bigint;
|
|
848
887
|
};
|
|
888
|
+
type CreateChain = {
|
|
889
|
+
utxoSet: utils.UtxoSet;
|
|
890
|
+
subnetId: string;
|
|
891
|
+
chainName: string;
|
|
892
|
+
vmID: string;
|
|
893
|
+
fxIds: string[];
|
|
894
|
+
genesisData: Record<string, unknown>;
|
|
895
|
+
subnetAuth: number[];
|
|
896
|
+
feeState?: pvm.FeeState;
|
|
897
|
+
options?: Common.SpendOptions;
|
|
898
|
+
fromAddresses?: string[];
|
|
899
|
+
};
|
|
900
|
+
type ConvertSubnetToL1 = {
|
|
901
|
+
utxoSet: utils.UtxoSet;
|
|
902
|
+
address: string;
|
|
903
|
+
chainId: string;
|
|
904
|
+
subnetId: string;
|
|
905
|
+
subnetAuth: number[];
|
|
906
|
+
options?: Common.SpendOptions;
|
|
907
|
+
feeState: pvm.FeeState;
|
|
908
|
+
fromAddresses?: string[];
|
|
909
|
+
validators: {
|
|
910
|
+
nodeId: string;
|
|
911
|
+
weight: bigint;
|
|
912
|
+
balance: bigint;
|
|
913
|
+
pubKey: string;
|
|
914
|
+
signature: string;
|
|
915
|
+
remainingBalanceOwner: {
|
|
916
|
+
addresses: string[];
|
|
917
|
+
threshold?: number;
|
|
918
|
+
};
|
|
919
|
+
deactivationOwner: {
|
|
920
|
+
addresses: string[];
|
|
921
|
+
threshold?: number;
|
|
922
|
+
};
|
|
923
|
+
}[];
|
|
924
|
+
};
|
|
925
|
+
type RegisterL1Validator = {
|
|
926
|
+
utxoSet: utils.UtxoSet;
|
|
927
|
+
balance: bigint;
|
|
928
|
+
signature: string;
|
|
929
|
+
feeState: pvm.FeeState;
|
|
930
|
+
message: string;
|
|
931
|
+
options?: Common.SpendOptions;
|
|
932
|
+
fromAddresses?: string[];
|
|
933
|
+
};
|
|
934
|
+
type SetL1ValidatorWeight = {
|
|
935
|
+
utxoSet: utils.UtxoSet;
|
|
936
|
+
feeState: pvm.FeeState;
|
|
937
|
+
message: string;
|
|
938
|
+
options?: Common.SpendOptions;
|
|
939
|
+
fromAddresses?: string[];
|
|
940
|
+
};
|
|
941
|
+
type DisableL1Validator = {
|
|
942
|
+
utxoSet: utils.UtxoSet;
|
|
943
|
+
feeState: pvm.FeeState;
|
|
944
|
+
disableAuth: number[];
|
|
945
|
+
validationId: string;
|
|
946
|
+
options?: Common.SpendOptions;
|
|
947
|
+
fromAddresses?: string[];
|
|
948
|
+
};
|
|
949
|
+
type IncreaseL1ValidatorBalance = {
|
|
950
|
+
utxoSet: utils.UtxoSet;
|
|
951
|
+
feeState: pvm.FeeState;
|
|
952
|
+
balance: bigint;
|
|
953
|
+
validationId: string;
|
|
954
|
+
options?: Common.SpendOptions;
|
|
955
|
+
fromAddresses?: string[];
|
|
956
|
+
};
|
|
849
957
|
type AddSubnetValidator = {
|
|
850
958
|
utxoSet: utils.UtxoSet;
|
|
851
959
|
nodeId: string;
|
|
@@ -999,7 +1107,12 @@ declare abstract class WalletAbstract {
|
|
|
999
1107
|
}): Common.UnsignedTx;
|
|
1000
1108
|
consolidateP({ utxoSet, amount, feeState, toAddress, options, }: ConsolidateP): Common.UnsignedTx;
|
|
1001
1109
|
baseTX({ utxoSet, chain, toAddress, amountsPerAsset, feeState, options, fromAddresses, }: BaseTx): Common.UnsignedTx;
|
|
1002
|
-
|
|
1110
|
+
convertSubnetToL1({ utxoSet, chainId, subnetId, subnetAuth, feeState, address, validators, options, fromAddresses, }: ConvertSubnetToL1): Common.UnsignedTx;
|
|
1111
|
+
registerL1Validator({ utxoSet, balance, signature, message, feeState, fromAddresses, options, }: RegisterL1Validator): Common.UnsignedTx;
|
|
1112
|
+
setL1ValidatorWeight({ utxoSet, feeState, message, options, fromAddresses, }: SetL1ValidatorWeight): Common.UnsignedTx;
|
|
1113
|
+
disableL1Validator({ utxoSet, feeState, options, fromAddresses, disableAuth, validationId, }: DisableL1Validator): Common.UnsignedTx;
|
|
1114
|
+
increaseL1ValidatorBalance({ utxoSet, feeState, options, fromAddresses, balance, validationId, }: IncreaseL1ValidatorBalance): Common.UnsignedTx;
|
|
1115
|
+
createBlockchain({ utxoSet, subnetId, chainName, vmID, fxIds, genesisData, subnetAuth, feeState, options, fromAddresses, }: CreateChain): Common.UnsignedTx;
|
|
1003
1116
|
createSubnet({ utxoSet, rewardAddresses, feeState, fromAddresses, options, threshold, locktime, }: CreateSubnet): Common.UnsignedTx;
|
|
1004
1117
|
addSubnetValidator({ utxoSet, nodeId, start, end, weight, subnetId, subnetAuth, feeState, fromAddresses, options, }: AddSubnetValidator): Common.UnsignedTx;
|
|
1005
1118
|
/**
|
|
@@ -1705,9 +1818,11 @@ type index_AddValidatorTx = AddValidatorTx;
|
|
|
1705
1818
|
type index_AddressWallet = AddressWallet;
|
|
1706
1819
|
declare const index_AddressWallet: typeof AddressWallet;
|
|
1707
1820
|
type index_ChainIDAlias = ChainIDAlias;
|
|
1821
|
+
type index_ConvertSubnetToL1Tx = ConvertSubnetToL1Tx;
|
|
1708
1822
|
type index_CreateChainTx = CreateChainTx;
|
|
1709
1823
|
type index_CreateSubnetTx = CreateSubnetTx;
|
|
1710
1824
|
declare const index_DevnetContext: typeof DevnetContext;
|
|
1825
|
+
type index_DisableL1ValidatorTx = DisableL1ValidatorTx;
|
|
1711
1826
|
type index_ExportTx = ExportTx;
|
|
1712
1827
|
type index_FeeData = FeeData;
|
|
1713
1828
|
declare const index_FujiContext: typeof FujiContext;
|
|
@@ -1715,6 +1830,7 @@ type index_GetAvaxBalanceDict = GetAvaxBalanceDict;
|
|
|
1715
1830
|
type index_GetStakedAvaxBalanceDict = GetStakedAvaxBalanceDict;
|
|
1716
1831
|
type index_GlacierOutput = GlacierOutput;
|
|
1717
1832
|
type index_ImportTx = ImportTx;
|
|
1833
|
+
type index_IncreaseL1ValidatorBalanceTx = IncreaseL1ValidatorBalanceTx;
|
|
1718
1834
|
type index_JsonRpcProvider = JsonRpcProvider;
|
|
1719
1835
|
declare const index_JsonRpcProvider: typeof JsonRpcProvider;
|
|
1720
1836
|
type index_LedgerGetXpubResponse = LedgerGetXpubResponse;
|
|
@@ -1728,7 +1844,9 @@ declare const index_MnemonicWallet: typeof MnemonicWallet;
|
|
|
1728
1844
|
type index_MnemonicWalletVoid = MnemonicWalletVoid;
|
|
1729
1845
|
declare const index_MnemonicWalletVoid: typeof MnemonicWalletVoid;
|
|
1730
1846
|
declare const index_P_CHAIN_TX_SIZE_LIMIT: typeof P_CHAIN_TX_SIZE_LIMIT;
|
|
1847
|
+
type index_RegisterL1ValidatorTx = RegisterL1ValidatorTx;
|
|
1731
1848
|
type index_RemoveSubnetValidatorTx = RemoveSubnetValidatorTx;
|
|
1849
|
+
type index_SetL1ValidatorWeightTx = SetL1ValidatorWeightTx;
|
|
1732
1850
|
type index_SignMessageRequest = SignMessageRequest;
|
|
1733
1851
|
type index_SignTxBufferRequest = SignTxBufferRequest;
|
|
1734
1852
|
type index_SignTxRequest = SignTxRequest;
|
|
@@ -1780,12 +1898,17 @@ declare const index_isAddSubnetValidatorTx: typeof isAddSubnetValidatorTx;
|
|
|
1780
1898
|
declare const index_isAddValidatorTx: typeof isAddValidatorTx;
|
|
1781
1899
|
declare const index_isBaseTx: typeof isBaseTx;
|
|
1782
1900
|
declare const index_isBech32Address: typeof isBech32Address;
|
|
1901
|
+
declare const index_isConvertSubnetToL1Tx: typeof isConvertSubnetToL1Tx;
|
|
1783
1902
|
declare const index_isCreateChainTx: typeof isCreateChainTx;
|
|
1784
1903
|
declare const index_isCreateSubnetTx: typeof isCreateSubnetTx;
|
|
1904
|
+
declare const index_isDisableL1ValidatorTx: typeof isDisableL1ValidatorTx;
|
|
1785
1905
|
declare const index_isExportTx: typeof isExportTx;
|
|
1786
1906
|
declare const index_isImportTx: typeof isImportTx;
|
|
1907
|
+
declare const index_isIncreaseL1ValidatorBalance: typeof isIncreaseL1ValidatorBalance;
|
|
1787
1908
|
declare const index_isObsidianApp: typeof isObsidianApp;
|
|
1909
|
+
declare const index_isRegisterL1ValidatorTx: typeof isRegisterL1ValidatorTx;
|
|
1788
1910
|
declare const index_isRemoveSubnetValidatorTx: typeof isRemoveSubnetValidatorTx;
|
|
1911
|
+
declare const index_isSetL1ValidatorWeightTx: typeof isSetL1ValidatorWeightTx;
|
|
1789
1912
|
declare const index_isTransferSubnetOwnershipTx: typeof isTransferSubnetOwnershipTx;
|
|
1790
1913
|
declare const index_isTransformSubnetTx: typeof isTransformSubnetTx;
|
|
1791
1914
|
declare const index_parseAvalancheTx: typeof parseAvalancheTx;
|
|
@@ -1807,9 +1930,11 @@ declare namespace index {
|
|
|
1807
1930
|
index_AddressWallet as AddressWallet,
|
|
1808
1931
|
BaseTx$1 as BaseTx,
|
|
1809
1932
|
index_ChainIDAlias as ChainIDAlias,
|
|
1933
|
+
index_ConvertSubnetToL1Tx as ConvertSubnetToL1Tx,
|
|
1810
1934
|
index_CreateChainTx as CreateChainTx,
|
|
1811
1935
|
index_CreateSubnetTx as CreateSubnetTx,
|
|
1812
1936
|
index_DevnetContext as DevnetContext,
|
|
1937
|
+
index_DisableL1ValidatorTx as DisableL1ValidatorTx,
|
|
1813
1938
|
index_ExportTx as ExportTx,
|
|
1814
1939
|
index_FeeData as FeeData,
|
|
1815
1940
|
index_FujiContext as FujiContext,
|
|
@@ -1817,6 +1942,7 @@ declare namespace index {
|
|
|
1817
1942
|
index_GetStakedAvaxBalanceDict as GetStakedAvaxBalanceDict,
|
|
1818
1943
|
index_GlacierOutput as GlacierOutput,
|
|
1819
1944
|
index_ImportTx as ImportTx,
|
|
1945
|
+
index_IncreaseL1ValidatorBalanceTx as IncreaseL1ValidatorBalanceTx,
|
|
1820
1946
|
index_JsonRpcProvider as JsonRpcProvider,
|
|
1821
1947
|
index_LedgerGetXpubResponse as LedgerGetXpubResponse,
|
|
1822
1948
|
index_LedgerSigner as LedgerSigner,
|
|
@@ -1825,7 +1951,9 @@ declare namespace index {
|
|
|
1825
1951
|
index_MnemonicWallet as MnemonicWallet,
|
|
1826
1952
|
index_MnemonicWalletVoid as MnemonicWalletVoid,
|
|
1827
1953
|
index_P_CHAIN_TX_SIZE_LIMIT as P_CHAIN_TX_SIZE_LIMIT,
|
|
1954
|
+
index_RegisterL1ValidatorTx as RegisterL1ValidatorTx,
|
|
1828
1955
|
index_RemoveSubnetValidatorTx as RemoveSubnetValidatorTx,
|
|
1956
|
+
index_SetL1ValidatorWeightTx as SetL1ValidatorWeightTx,
|
|
1829
1957
|
index_SignMessageRequest as SignMessageRequest,
|
|
1830
1958
|
index_SignTxBufferRequest as SignTxBufferRequest,
|
|
1831
1959
|
index_SignTxRequest as SignTxRequest,
|
|
@@ -1871,12 +1999,17 @@ declare namespace index {
|
|
|
1871
1999
|
index_isAddValidatorTx as isAddValidatorTx,
|
|
1872
2000
|
index_isBaseTx as isBaseTx,
|
|
1873
2001
|
index_isBech32Address as isBech32Address,
|
|
2002
|
+
index_isConvertSubnetToL1Tx as isConvertSubnetToL1Tx,
|
|
1874
2003
|
index_isCreateChainTx as isCreateChainTx,
|
|
1875
2004
|
index_isCreateSubnetTx as isCreateSubnetTx,
|
|
2005
|
+
index_isDisableL1ValidatorTx as isDisableL1ValidatorTx,
|
|
1876
2006
|
index_isExportTx as isExportTx,
|
|
1877
2007
|
index_isImportTx as isImportTx,
|
|
2008
|
+
index_isIncreaseL1ValidatorBalance as isIncreaseL1ValidatorBalance,
|
|
1878
2009
|
index_isObsidianApp as isObsidianApp,
|
|
2010
|
+
index_isRegisterL1ValidatorTx as isRegisterL1ValidatorTx,
|
|
1879
2011
|
index_isRemoveSubnetValidatorTx as isRemoveSubnetValidatorTx,
|
|
2012
|
+
index_isSetL1ValidatorWeightTx as isSetL1ValidatorWeightTx,
|
|
1880
2013
|
index_isTransferSubnetOwnershipTx as isTransferSubnetOwnershipTx,
|
|
1881
2014
|
index_isTransformSubnetTx as isTransformSubnetTx,
|
|
1882
2015
|
index_parseAvalancheTx as parseAvalancheTx,
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),i=require("@avalabs/avalanchejs"),a=require("hdkey"),o=require("buffer"),d=require("@openzeppelin/contracts/build/contracts/ERC20.json"),u=require("bip32"),c=require("bip39"),l=require("@ledgerhq/hw-transport"),p=require("@metamask/eth-sig-util"),h=require("ledger-bitcoin"),g=require("@ledgerhq/hw-app-btc/lib/bip32"),m=require("@noble/hashes/sha256"),f=require("@avalabs/glacier-sdk"),x=require("@avalabs/core-chains-sdk"),v=require("create-hash"),w=require("xss"),b=require("bip32-path"),y=require("@avalabs/hw-app-avalanche");function A(e){return e.reduce(((e,t)=>e+t.value),0)}class I{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:A(r.confirmed),balanceUnconfirmed:A(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function T(t,r,s){const n=new e.Psbt({network:s});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),r.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function S(e,t,s,n,i){const a=[{address:e,value:s}],{inputs:o,outputs:d,fee:u}=r(i,a,n);if(!o||!d)return{fee:u};const c=[d[0]],l=d[1];return l&&c.push({address:t,value:l.value}),{inputs:o,outputs:c,fee:u}}function P(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function B(e,t,r,s,n,i){const a=S(e,t,r,s,P(n));return a.inputs?{...a,psbt:T(a.inputs,a.outputs,i)}:(console.log("Unable to construct transaction, fee needed: ",a.fee),a)}function C(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function k(e){return new s(e,"w0w")}const E="m/44'/60'",D=`${E}/0'`;var V=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(V||{});function M(e,t,r){if(e<0)throw new Error("Account index can not be less than 0.");const s="EVM"===r?"60":"9000";return t==V.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const K=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),O=(e,t)=>{const r=new n.Interface(d.abi).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var U=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"}];class N extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#e="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#e.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#e,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,U,this._parentProvider),this._maxCalls=62)}#e;#t=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#e.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function F(e,t){return u.fromBase58(e).derivePath(`0/${t}`).publicKey}let X=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=M(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=k(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=k(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,i=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+i.v),r:"0x"+i.r,s:"0x"+i.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...i}=t,a=n.TypedDataEncoder.getPrimaryType(i);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:a,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof l.TransportStatusError&&s.statusCode===l.StatusCodes.INS_NOT_SUPPORTED){const s=p.TypedDataUtils.hashStruct(a,r,t,p.SignTypedDataVersion.V4),i=p.TypedDataUtils.hashStruct("EIP712Domain",e,t,p.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,i.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function _(t,r,s,n,i,a){const o=new h.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,i,n,g.pathStringToArray(a))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function H(t,r,s,n){const i=new e.Psbt({network:r}),a=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<a;e++){const r=t.getInputWitnessUtxo(e),a=t.getInputBip32Derivation(e,s);i.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:a?[{path:n,pubkey:s,masterFingerprint:a.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)i.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return i}class R{constructor(t,r){this.pubkey=t,this.provider=r;try{this.ecPair=e.ECPair.fromPublicKey(t)}catch(e){throw new Error("Not a valid public key.")}}ecPair;getAddressP2PKH(){return e.payments.p2pkh({pubkey:this.ecPair.publicKey,network:this.provider.getNetwork()}).address}getAddressBech32(){return C(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,r,s){return B(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class L extends R{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=V.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await c.mnemonicToSeed(e),i=u.fromSeed(n),a=M(t,s,"EVM"),o=i.derivePath(a);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new L(o.privateKey,r)}signTx(e,t){const r=T(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(r))}static fromEthersWallet(e,t){const r=e.privateKey;if(!r)throw new Error("Unable to get private key from ethers wallet.");const s=Buffer.from(r.substring(2),"hex");return new L(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}var $=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))($||{});const q=e=>{switch(e){case"C":return i.EVM;case"X":return i.AVM;case"P":return i.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}},{getTransferableInputsByTx:W,AddressMaps:j}=i.utils,J=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=W(e),o=j.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>i.pvmSerial.isCreateChainTx(e)||i.pvmSerial.isAddSubnetValidatorTx(e)||i.pvmSerial.isRemoveSubnetValidatorTx(e)||i.pvmSerial.isTransformSubnetTx(e)||i.pvmSerial.isTransferSubnetOwnershipTx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),a=i.OutputOwners.fromNative(n.controlKeys.map((e=>i.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new i.utils.AddressMap(a)),r})({tx:e,provider:r,addressMaps:o});return new i.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}return new i.UnsignedTx(e,n,o,s)},{bufferToHex:z,packTx:Y}=i.utils,{publicKeyBytesToAddress:G,recoverPublicKey:Q}=i.secp256k1,Z=new i.Signature(new Uint8Array(Array(65).fill(0))),ee=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(Z);if(!t)return s;const{unsignedTx:n,credentialIndex:i}=t,a=n.getCredentials()[i];if(!a)return s;const o=Y(n.getTx()),d=m.sha256(o),u=Z.toString();for(const e of a.toJSON()){if(e.toString()===u)continue;const t=Q(d,e.toBytes()),r={toHex:()=>z(G(t))},a=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of a)t[0]===i&&(s[t[1]]=e)}return s};function te(e){return i.utils.bufferToHex(i.utils.addChecksum(e.toBytes()))}const{getManagerForVM:re,hexToBuffer:se,unpackWithManager:ne}=i.utils,ie=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=q(t);if(n===i.EVM)throw new Error("EVM transactions are not supported");const a=se(e),o=ne(n,a),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=re(s).unpack(t,i.avaxSerial.SignedTx),o=await J({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new i.Credential(ee(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new i.Credential(ee(e))))}})({tx:o,txBytes:a,provider:r,vm:n,utxos:s});return J({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:ae,format:oe}=i.utils,{publicKeyBytesToAddress:de}=i.secp256k1;class ue{constructor(e,t,r){this.baseUrl=e,this.context=t,this.upgradesInfo=r;const s=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(s)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}isEtnaEnabled(){return!!this.upgradesInfo&&i.utils.isEtnaEnabled(this.upgradesInfo)}getUpgradesInfo(){return this.upgradesInfo}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return i.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new i.avm.AVMApi(this.baseUrl)}getApiP(){return new i.pvm.PVMApi(this.baseUrl)}getApiC(){return new i.evm.EVMApi(this.baseUrl)}getInfo(){return new i.info.InfoApi(this.baseUrl)}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=Buffer.from(s,"hex"),a=de(i);return oe(r,this.getHrp(),a)}getAddressFromBuffer(e,t){return oe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ae(e);return oe(t,this.getHrp(),r)}getApiByVM(e){switch(e){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(e){switch(e){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(e){const t=e.unsignedTx.getVM(),r=te(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,a)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&a(new Error("Timeout")),d=s instanceof i.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),d.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{o()}),1e3)}};o()}))}}const ce={weights:i.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},le={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e9),transformSubnetTxFee:BigInt(1e10),createBlockchainTxFee:BigInt(1e9),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:1,hrp:"avax",platformFeeConfig:ce},pe={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e8),transformSubnetTxFee:BigInt(1e9),createBlockchainTxFee:BigInt(1e8),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:5,hrp:"fuji",platformFeeConfig:ce},he={addPrimaryNetworkDelegatorFee:0n,addPrimaryNetworkValidatorFee:0n,addSubnetDelegatorFee:1000000n,addSubnetValidatorFee:1000000n,avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",createAssetTxFee:1000000n,createBlockchainTxFee:100000000n,createSubnetTxFee:100000000n,hrp:"custom",networkID:76,pBlockchainID:"11111111111111111111111111111111LpoYY",transformSubnetTxFee:100000000n,xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",platformFeeConfig:ce};class ge extends ue{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await i.Context.getContextFromURI(e);try{const r=await new i.info.InfoApi(e).getUpgradesInfo();return new ge(e,t,r)}catch{return new ge(e,t)}}static getDefaultMainnetProvider(e){return new ge(x.AVALANCHE_XP_NETWORK.rpcUrl,le,e)}static getDefaultFujiProvider(e){return new ge(x.AVALANCHE_XP_TEST_NETWORK.rpcUrl,pe,e)}static getDefaultDevnetProvider(e){return new ge(x.AVALANCHE_P_DEV_NETWORK.rpcUrl,he,e)}}const{bytesCompare:me,parseBech32:fe}=i.utils,xe=(e,t)=>"P"===t,ve=(e,t,r)=>{const s=xe(0,t)?e.amount:e.asset?.amount;return new i.TransferOutput(new i.BigIntPr(BigInt(s)),i.OutputOwners.fromNative(e.addresses.map((e=>fe(e)[1])).sort(me),BigInt(r??0),e.threshold))},we=(e,t)=>{const r=((e,t)=>{const r=t===f.Network.FUJI,s=t===f.Network.DEVNET,{cBlockchainID:n,xBlockchainID:i,pBlockchainID:a}=s?he:r?pe:le;if(n===e)return"C";if(i===e)return"X";if(a===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=xe(0,r)?e.txHash:e.creationTxHash,n=xe(0,r)?e.assetId:e.asset?.assetId;return new i.Utxo(i.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),i.Id.fromString(n),((e,t)=>xe(0,t)?e.stakeableLocktime?new i.pvmSerial.StakeableLockOut(new i.BigIntPr(BigInt(e.stakeableLocktime??0)),ve(e,t,e.platformLocktime??0)):ve(e,t,e.platformLocktime):ve(e,t,e.locktime))(e,r))},{unpackWithManager:be,parse:ye,bufferToHex:Ae,AddressMaps:Ie,AddressMap:Te}=i.utils;function Se(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return v("sha256").update(s).digest()}const Pe=1024,Be=1024;async function Ce(e,t,r){const s=e.slice(0,Pe),n=e.slice(Pe),i=await ke(t,{...r,addresses:s});if(n.length){const s=await Ce(n,t,{...r,addresses:e});return i.merge(s)}return i}async function ke(e,t){if(t.addresses.length>Pe)throw new Error(`Can not get UTXOs for more than ${Pe} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new i.utils.UtxoSet(s);if(s.length>=Be){const s=await ke(e,{...t,startIndex:r});return n.merge(s)}return n}function Ee(){return BigInt(Math.floor(Date.now()/1e3))}const{isStakeableLockOut:De,isTransferOut:Ve}=i.utils,Me=e=>{const t=e.output,r=e.getOutputOwners();return{utxoId:e.ID(),assetId:e.getAssetId(),amount:Ve(t)||De(t)?t.amount():BigInt(0),locktime:r.locktime.value(),stakeableLocktime:De(t)?t.getStakeableLocktime():BigInt(0),threshold:r.threshold.value()}};async function Ke(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await Ke(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Oe,hexToBuffer:Ue,unpackWithManager:Ne}=i.utils;function Fe(e,t=!0){try{if(t){const[t]=i.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else i.utils.parseBech32(e);return!0}catch(e){return!1}}const Xe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),_e=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0)),He=e=>{if([le.xBlockchainID,pe.xBlockchainID,he.xBlockchainID].includes(e))return"AVM";if([le.pBlockchainID,pe.pBlockchainID,he.pBlockchainID].includes(e))return"PVM";if([le.cBlockchainID,pe.cBlockchainID,he.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")};var Re={parseAddValidatorTx:e=>i.pvmSerial.isAddValidatorTx(e)?({feeData:t,assetId:r})=>({type:$.AddValidator,chain:e.getVM(),nodeID:e.validator.nodeId.value(),delegationFee:e.shares.value(),stake:Xe(e.stake,r),stakeOuts:e.stake,start:e.validator.startTime.value().toString(),end:e.validator.endTime.value().toString(),rewardOwner:e.getRewardsOwner(),...t}):null,parseAddDelegatorTx:e=>i.pvmSerial.isAddDelegatorTx(e)?({feeData:t,assetId:r})=>({type:$.AddDelegator,chain:e.getVM(),stake:Xe(e.stake,r),stakeOuts:e.stake,rewardOwner:e.getRewardsOwner(),nodeID:e.validator.nodeId.value(),start:e.validator.startTime.value().toString(),end:e.validator.endTime.value().toString(),...t}):null,parseCreateSubnetTx:e=>i.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:$.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>i.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:$.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>i.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:$.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>i.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:$.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>i.pvmSerial.isImportTx(e)||i.avmSerial.isImportTx(e)||i.evmSerial.isImportTx(e)?i.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:He(e.sourceChain.value()),amount:_e(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:He(e.sourceChain.value()),amount:_e(e.ins,r),...t}):null,parseExportTx:e=>i.pvmSerial.isExportTx(e)||i.avmSerial.isExportTx(e)||i.evmSerial.isExportTx(e)?i.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:He(e.destinationChain.toString()),amount:Xe(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:He(e.destination.value()),amount:Xe(e.outs,r),...t}):null,parseBaseTx:e=>i.avmSerial.isAvmBaseTx(e)||i.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,a=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),i.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof i.TransferOutput){const i=n.assetId.value(),a=[...s.values()].indexOf(i),o=e[a],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:i,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===i}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof i.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),o=Ee(),d=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:$.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!i.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return i.pvmSerial.isSigner(e.signer)&&(r=i.utils.bufferToHex(e.signer.proof.publicKey),t=i.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:$.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>i.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:$.AddPermissionlessDelegator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),stakeOuts:e.stake,delegatorRewardsOwner:e.getDelegatorRewardsOwner(),...t}):null,parseTransformSubnetTx:e=>i.pvmSerial.isTransformSubnetTx(e)?({feeData:t})=>({type:$.TransformSubnet,chain:e.getVM(),subnetID:e.subnetID.toString(),assetID:e.assetId.toString(),initialSupply:e.initialSupply.value(),maximumSupply:e.maximumSupply.value(),minConsumptionRate:e.minConsumptionRate.value(),maxConsumptionRate:e.maxConsumptionRate.value(),minValidatorStake:e.minValidatorStake.value(),maxValidatorStake:e.maxValidatorStake.value(),minStakeDuration:e.minStakeDuration.value(),maxStakeDuration:e.maxStakeDuration.value(),minDelegationFee:e.minDelegationFee.value(),minDelegatorStake:e.minDelegatorStake.value(),maxValidatorWeightFactor:Number(e.maxValidatorWeightFactor.toJSON()),uptimeRequirement:e.uptimeRequirement.value(),...t}):null,parseTransferSubnetOwnershipTx:e=>i.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:$.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null};const{getBurnedAmountByTx:Le,getOutputAmounts:$e,getInputAmounts:qe,validateBurnedAmount:We}=i.utils;const{isStakeableLockOut:je,isTransferOut:Je}=i.utils;function ze(e){return e.sort(((e,t)=>{const r=e.output,s=t.output,n=je(r),i=je(s);if(n&&!i)return-1;if(i&&!n)return 1;if(je(r)&&je(s)){const e=r.getStakeableLocktime(),t=s.getStakeableLocktime();if(e<t)return 1;if(e>t)return-1}else if(Je(r)&&Je(s)){if(r.amount()>s.amount())return-1;if(r.amount()<s.amount())return 1}return 0}))}function Ye(e,t){return e.sort(((e,r)=>{const s=e.output,n=r.output;let i=BigInt(0);(Je(s)||je(s))&&(i=s.amount());let a=BigInt(0);(Je(n)||je(n))&&(a=n.amount());const o=t?a-i:i-a;return o>0?1:o<0?-1:0}))}const Ge=e=>Ye(e,!0),Qe=e=>Ye(e,!1);var Ze=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Ze||{});const et="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",tt="11111111111111111111111111111111LpoYY",rt=(e,t)=>e.reduce(((e,t)=>e+Me(t).amount),BigInt(0))-t,st={BaseP:{sortFunction:Ge,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new i.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:rt(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:Qe,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new i.utils.UtxoSet(t),amount:rt(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:ze,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new i.utils.UtxoSet(t),nodeId:et,start:Ee(),end:Ee()+BigInt(1e3),weight:rt(t,e.getProvider().getContext().baseTxFee),subnetId:tt,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(i.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(i.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:ze,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new i.utils.UtxoSet(t),nodeId:et,start:Ee(),end:Ee()+BigInt(1e3),weight:rt(t,e.getProvider().getContext().baseTxFee),subnetId:tt,feeState:r})},ExportP:{sortFunction:Ge,unsignedTxBuilder:(e,t,r)=>e.exportP({amount:rt(t,e.getProvider().getContext().baseTxFee),utxoSet:new i.utils.UtxoSet(t),destination:"X",feeState:r})},ImportP:{sortFunction:Ge,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new i.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function nt(e){return b.validateString(e,!0)&&6===e.split("/").length}function it(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:at,hexToBuffer:ot}=i.utils,dt=new Error("Tx type is not supported post-etna");class ut{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Ce(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Ke(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(e),s=this.provider.getChainID(t);return Ce(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=at(s)[2],a=this.provider.getAvaxID(),o=i.TransferableOutput.fromNative(a,e,[n]),d=Ye(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>at(e)[2])),l=at(this.getChangeAddress("X"))[2];return i.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:a}){const o=this.provider.getChainID(t),d=this.getAddresses("P").map((e=>at(e)[2])),u=at(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const c=at(r)[2],l=e.getUTXOs();if(this.provider.isEtnaEnabled()){if(!n)throw new Error("feeState parameter is required post E-upgrade");return i.pvm.e.newImportTx({fromAddressesBytes:d,utxos:l,toAddressesBytes:[c],sourceChainId:o,threshold:s,feeState:n,locktime:a},this.provider.getContext())}return i.pvm.newImportTx(this.provider.getContext(),o,l,[c],d,{changeAddresses:[u]})}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>at(e)[2])),a=at(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=at(r)[2];return i.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[a]})}importC(e,r,s,n,a){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>at(e)[2]));a=a||this.getAddressEVM();const u=Buffer.from(t.strip0x(a),"hex");return i.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const a=ot(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=at(n)[2],u=s/BigInt(1e9);return i.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,a,[d],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const a=at(n)[2],o=this.provider.getAvaxID(),d=i.TransferableOutput.fromNative(o,e,[a]),u=Ye(t.getUTXOs(),!0),c=this.provider.getChainID(r),l=this.getAddresses("P").map((e=>at(e)[2])),p=at(this.getChangeAddress("P"))[2];return this.provider.isEtnaEnabled()?(it(s),i.pvm.e.newExportTx({fromAddressesBytes:l,utxos:u,outputs:[d],destinationChainId:c,feeState:s},this.provider.getContext())):i.pvm.newExportTx(this.provider.getContext(),c,l,u,[d],{changeAddresses:[p]})}addValidator(e,t,r,s,n,a,o){const d=ze(e.getUTXOs()),u=this.getAddresses("P").map((e=>at(e)[2])),c=o?.rewardAddress||this.getCurrentAddress("P"),l=at(c)[2],p=at(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw dt;return i.pvm.newAddValidatorTx(this.provider.getContext(),d,u,t,s,n,r,[l],a,{changeAddresses:[p]})}addDelegator(e,t,r,s,n,a){const o=ze(e.getUTXOs()),d=this.getAddresses("P").map((e=>at(e)[2])),u=a?.rewardAddress||this.getCurrentAddress("P"),c=at(u)[2],l=at(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw dt;return i.pvm.newAddDelegatorTx(this.provider.getContext(),o,d,t,s,n,r,[c],{changeAddresses:[l]})}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const a=Qe(e.getUTXOs());s=s??this.getCurrentAddress("P");const o=at(s)[2],d=this.provider.getContext(),u=[i.TransferableOutput.fromNative(d.avaxAssetID,t,[o])],c=this.getAddresses("P").map((e=>at(e)[2]));return this.provider.isEtnaEnabled()?(it(r),i.pvm.e.newBaseTx({fromAddressesBytes:c,utxos:a,outputs:u,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},d)):i.pvm.newBaseTx(this.provider.getContext(),c,a,u,n)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:a,fromAddresses:o}){const[d,u,c]=at(r);if(d!==t||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const l=Object.entries(s).map((([e,t])=>i.TransferableOutput.fromNative(e,t,[c]))),p=Ye(e.getUTXOs(),!0),h=(o??this.getAddresses(t)).map((e=>at(e)[2]));return"X"===t?i.avm.newBaseTx(this.provider.getContext(),h,p,l,a):this.provider.isEtnaEnabled()?(it(n),i.pvm.e.newBaseTx({fromAddressesBytes:h,utxos:p,outputs:l,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext())):i.pvm.newBaseTx(this.provider.getContext(),h,p,l,a)}createBlockchain(e,t,r,s,n,a,o,d,u){const c=Ye(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>at(e)[2]));if(this.provider.isEtnaEnabled())throw dt;return i.pvm.newCreateBlockchainTx(this.provider.getContext(),c,l,t,r,s,n,a,o,d)}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:a,locktime:o}){const d=Ye(e.getUTXOs(),!0),u=(s??this.getAddresses("P")).map((e=>at(e)[2])),c=t.map((e=>at(e)[2]));return this.provider.isEtnaEnabled()?(it(r),i.pvm.e.newCreateSubnetTx({fromAddressesBytes:u,utxos:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:a,locktime:o,subnetOwners:c},this.provider.getContext())):i.pvm.newCreateSubnetTx(this.provider.getContext(),d,u,c,n,a??1,o??BigInt(0))}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:o,feeState:d,fromAddresses:u,options:c}){const l=Ye(e.getUTXOs(),!0),p=(u??this.getAddresses("P")).map((e=>at(e)[2]));return this.provider.isEtnaEnabled()?(it(d),i.pvm.e.newAddSubnetValidatorTx({fromAddressesBytes:p,utxos:l,minIssuanceTime:c?.minIssuanceTime,memo:c?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:o,feeState:d},this.provider.getContext())):i.pvm.newAddSubnetValidatorTx(this.provider.getContext(),l,p,t,r,s,n,a,o,c)}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:o,feeState:d,fromAddresses:u,rewardAddresses:c,delegatorRewardAddresses:l,publicKey:p,signature:h,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=ze(e.getUTXOs()),w=(u??this.getAddresses("P")).map((e=>at(e)[2])),b=(c??[this.getCurrentAddress("P")]).map((e=>at(e)[2])),y=(l??[this.getCurrentAddress("P")]).map((e=>at(e)[2]));if(!(a!==i.networkIDs.PrimaryNetworkID.toString()||p&&h))throw new Error("Must provide public key and signature for primary subnet.");const A=at(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return it(d),i.pvm.e.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:y,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:g?.changeAddresses?g.changeAddresses:[A],nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:o,feeState:d,publicKey:p,rewardAddresses:b,signature:h,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext());const I={changeAddresses:[A],...g??{}};return i.pvm.newAddPermissionlessValidatorTx(this.provider.getContext(),v,w,t,a,r,s,n,b,y,o,I,void 0,void 0,p,h)}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,fromAddresses:o,rewardAddresses:d,options:u,locktime:c,feeState:l,threshold:p,stakingAssetId:h}){const g=ze(e.getUTXOs()),m=(o??this.getAddresses("P")).map((e=>at(e)[2])),f=(d??[this.getCurrentAddress("P")]).map((e=>at(e)[2])),x=at(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return it(l),i.pvm.e.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,changeAddressesBytes:u?.changeAddresses?u.changeAddresses:[x],nodeId:t,start:r,end:s,weight:n,subnetId:a,rewardAddresses:f,locktime:c,stakingAssetId:h,threshold:p,feeState:l},this.provider.getContext());const v={changeAddresses:[x],...u??{}};return i.pvm.newAddPermissionlessDelegatorTx(this.provider.getContext(),g,m,t,a,r,s,n,f,v,void 0,void 0)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:a,options:o}){const d=Ye(e.getUTXOs(),!0),u=(n??this.getAddresses("P")).map((e=>at(e)[2]));return this.provider.isEtnaEnabled()?(it(a),i.pvm.e.newRemoveSubnetValidatorTx({fromAddressesBytes:u,utxos:d,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:a},this.provider.getContext())):i.pvm.newRemoveSubnetValidatorTx(this.provider.getContext(),d,u,t,r,s,o)}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:a,options:o,threshold:d,locktime:u}){const c=Ye(e.getUTXOs(),!0),l=(a??this.getAddresses("P")).map((e=>at(e)[2])),p=s.map((e=>at(e)[2]));return this.provider.isEtnaEnabled()?(it(n),i.pvm.e.newTransferSubnetOwnershipTx({fromAddressesBytes:l,utxos:c,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,subnetId:t,subnetAuth:r,subnetOwners:p,feeState:n,threshold:d,locktime:u},this.provider.getContext())):i.pvm.newTransferSubnetOwnershipTx(this.provider.getContext(),c,l,t,r,p,o,d??1,u??BigInt(0))}transformSubnetTx(e,t,r,s,n,a,o,d,u,c,l,p,h,g,m,f,x,v){const w=Ye(e.getUTXOs(),!0),b=(x??this.getAddresses("P")).map((e=>at(e)[2]));if(this.provider.isEtnaEnabled())throw dt;return i.pvm.newTransformSubnetTx(this.provider.getContext(),w,b,t,r,s,n,a,o,d,u,c,l,p,h,g,m,f,v)}}class ct extends ut{constructor(e,t,r){if(super(r),this.pubkeyXP=e,this.pubkeyC=t,33!==t.length||33!==e.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(e,r,s){const i=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(i,"hex"),d=Buffer.from(a,"hex");return new ct(o,d,s)}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!nt(r)||!nt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),i=u.fromSeed(n),a=i.derivePath(r),o=i.derivePath(t);return ct.fromPublicKey(o.publicKey,a.publicKey,s)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return n.computeAddress(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(e){return[this.getAddress(e)]}getChangeAddress(e){return this.getAddress(e)}getCurrentAddress(e){return this.getAddress(e)}}const lt={type:"zondax",getApp:e=>new y(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,r={show:!1,hrp:"avax"}){const s=this.getApp(e);return{publicKey:(await s.getAddressAndPubKey(t.toString(),r.show,r.hrp)).publicKey}},async getXPUB(e,t){const r=this.getApp(e),s=await r.getExtendedPubKey(t,!1);return{pubKey:s.publicKey,chainCode:s.chain_code}},async signHash(e,t,r,s){const n=this.getApp(e),i=s.map((e=>e.toString(!0))),a=await n.signHash(r.toString(),i,t),o=a.signatures||new Map;return{hash:a.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const i=this.getApp(e),a=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await i.sign(r.toString(),a,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function pt(e){return!(await lt.getVersion(e)>="0.6.0")}const{parse:ht}=i.utils;class gt extends ut{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new ct(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),i=s.derivePath(M(0,V.BIP44,"EVM")).neutered();return new gt(n.toBase58(),i.publicKey,t)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(ht(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(ht(e)[2])))}getRawAddressC(){return Buffer.from(ht(this.getCurrentAddress("C"))[2])}}const{isTransferOut:mt,isStakeableLockOut:ft}=i.utils;function xt(e){const t=e.output;return mt(t)||ft(t)?t.getOwners():[]}function vt(e){const t=e.getTx();return i.avmSerial.isExportTx(t)||i.pvmSerial.isExportTx(t)?new Set(t.outs.map(xt).flat()):i.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(xt).flat()):new Set((t.baseTx?.outputs??[]).map(xt).flat())}const{parse:wt}=i.utils;class bt extends gt{constructor(e,t,r){super(e,t,r)}getAdditionalAddressesByIndices(e,t,r){return"C"===r?[]:e.map((e=>{const s=this.getAddressAtIndex(e,t,r),[,,n]=wt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await pt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=k(e),i=await lt.getXPUB(e,bt.getAccountPath("X")),a=u.fromPublicKey(i.pubKey,i.chainCode),o=M(0,V.BIP44,"EVM"),d=await s.getAddress(o,!1),c=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new bt(a.toBase58(),l,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),i=new Set([...s,...r??[]]),a=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(i.has(t)){const e=[...i].indexOf(t);o.add(`1/${e}`)}else if(a.has(t)){const e=[...a].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),i=Buffer.from(t.toBytes()),a="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,a),u=this.getAdditionalAddressesByIndices(s??[],!0,a),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>b.fromString(e))),l=[...vt(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>b.fromString(e)));return(await this.signTxBuffer({buffer:i,chain:a,transport:e.transport,signers:c,change:p})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=b.fromString(bt.getAccountPath(e.chain));return[...(await lt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:yt}=i.utils;class At extends gt{constructor(e,t,r){const s=u.fromBase58(e).neutered(),i=new n.SigningKey(t),a=Buffer.from(yt(i.compressedPublicKey),"hex");super(s.toBase58(),a,r),this.evmPrivKey=t,this.accountNode=u.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),i=s.derivePath(M(0,V.BIP44,"EVM"));if(!i.privateKey)throw new Error("Unable to derive EVM private key.");return new At(n.toBase58(),i.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await i.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:It,sign:Tt,signHash:St}=i.secp256k1,{addChecksum:Pt}=i.utils;class Bt extends ct{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(It(e)),Buffer.from(It(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!nt(r)||!nt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),i=u.fromSeed(n),a=i.derivePath(t),o=i.derivePath(r);if(!a.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Bt(a.privateKey,o.privateKey,s)}async signMessage(e){const t=Se(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Pt(await St(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await i.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Tt(e.buffer,t))]}}const{strip0x:Ct}=i.utils;class kt extends ct{constructor(e,t,r,s,a){const o=i.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=i.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),a),this.pathXP=t,this.pathC=s,!nt(t)||!nt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,i){if(await pt(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!nt(t)||!nt(r))throw new Error("Invalid path configuration.");const a=new s(e),o=await a.getAddress(r,!1),d=await a.getAddress(t,!1),u=Buffer.from(Ct(o.publicKey),"hex"),c=Buffer.from(Ct(d.publicKey),"hex"),l=Buffer.from(Ct(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Ct(n.SigningKey.computePublicKey(c,!0)),"hex");return new kt(p,t,l,r,i)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=b.fromString(this.getAccountPath(e.chain)),r=b.fromString(this.getPartialSignerPath(e.chain));return[...(await lt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Et}=i.utils;var Dt=Object.freeze({__proto__:null,AbstractProvider:ue,AddressWallet:class extends ut{constructor(e,t,r,s,i){if(super(i),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=r,this.xpChangeAddress=s,r.length<1)throw new Error("Must have at least 1 xp address.");if(!n.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(r.some((e=>!Fe(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!Fe(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(s)}setChangeAddress(e){if(!Fe(e,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=e}getAddressEVM(){return this.addressC}getAddresses(e){return("C"===e?[this.addressCoreEth]:this.xpAddresses).map((t=>this.provider.formatAddress(t,e)))}getChangeAddress(e){const t="C"===e?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(t,e)}getCurrentAddress(e){const t="C"===e?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(t,e)}},DevnetContext:he,FujiContext:pe,JsonRpcProvider:ge,LedgerSigner:kt,LedgerWallet:bt,MainnetContext:le,MnemonicWallet:At,MnemonicWalletVoid:gt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=u.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof i.EVMUnsignedTx||"C"===t?i.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):i.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Et(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),i=`0/${this.activeAccountIndex}`,a=new Map;if("C"===n||!this.accountNode)return a;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[i,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&a.set(t,e)}return a}getAddressBipPaths(e,t){return 0===t.size?[b.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(b.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),i=this.getAddressBipPaths(r.getAddresses(),n),a=this.getAddressBipPaths([...vt(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:i,change:a})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=b.fromString(this.getAccountPath(e.chain));return[...(await lt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||b.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=Se(e.message),s=(await lt.signHash(e.transport,r,b.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(M(t,V.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=this.getSigningKeys(n,r,s);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await i.addTxSignatures({unsignedTx:t,privateKeys:a}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=Se(e.message),s=await i.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Ze,StaticSigner:Bt,TxType:$,WalletAbstract:ut,WalletVoid:ct,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await ie({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const o=a.getCredentials(),d=a.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=o[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new i.Credential(s)),e}),[]),u=new i.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,d);return{signedTxHex:te(new i.avaxSerial.SignedTx(a.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:we,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=be(r,e),a=ye(t)[2],o=Ae(a);if(i.evmSerial.isExportTx(n))return new i.EVMUnsignedTx(n,[],new Ie([Te.fromJSON([[o,0]])]));if(i.evmSerial.isImportTx(n)){const e=Ie.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[a]);return new i.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:J,digestMessage:Se,emptySignature:Z,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const i=n?"1":"0",a=u.fromBase58(e).derivePath(`${i}/${t}`).publicKey;return r.getAddress(a,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return u.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),i=Ee();return n.forEach((e=>{const t=Me(e);s[t.threshold>1?"multisig":t.locktime>i?"locked":t.stakeableLocktime>i?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getLedgerProvider:async function(e){return lt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:i,unsignedTxBuilder:a}=st[r],o=Ee(),d=i(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=Me(e);return t<o&&(s<o||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),u=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let i=-1;for(;s<=n;){const a=Math.floor((s+n)/2);t(e.slice(0,a+1))<=r?(i=a,s=a+1):n=a-1}return i}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*Me(t).threshold)),0);return 6+e.toBytes().length+t}(a(e,t,n))}catch(e){return console.log("Unable to estimate size of utxos",{e:e,utxos:t.map(Me)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:ke,getPchainUnixNow:async function(e){const t=e?x.AVALANCHE_XP_TEST_NETWORK.rpcUrl:x.AVALANCHE_XP_NETWORK.rpcUrl,r=await new i.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:Ke,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[i.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Ce,getUnixNow:Ee,getUtxoInfo:Me,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:a})=>{const o=q(t),d=Ue(e),u=Ne(o,d);if(i.evmSerial.isExportTx(u))return[];const c=(e=>{if(i.evmSerial.isImportTx(e)||i.avmSerial.isImportTx(e)||i.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case i.EVM:return f.BlockchainId.C_CHAIN;case i.AVM:return f.BlockchainId.X_CHAIN;case i.PVM:return f.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Oe(u),p=new f.Glacier({BASE:s,TOKEN:n,HEADERS:a}),h=[...new Set(l.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(h.map((e=>p.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:r,txHash:e}))));return l.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const i=we(n,r);return e.push(i),e}),[])},getVmByChainAlias:q,getXpubFromMnemonic:function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=c.mnemonicToSeedSync(e);return u.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:Fe,isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isObsidianApp:pt,isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50}={}){try{const n=t.getContext(),a=e.getTx(),o=(e=>{for(const t of Object.values(Re)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(a),d=Le(a,n),u=$e(a),c=qe(a).get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0),p=u.get(n.avaxAssetID)??BigInt(0);let h,g=BigInt(0);i.evmSerial.isImportExportTx(a)?g=await t.getApiC().getBaseFee()/BigInt(1e9):"PVM"===a.vm&&(h=t.getUpgradesInfo(),g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0))));const{isValid:m,txFee:f}=We({upgradesInfo:h,unsignedTx:e,context:n,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f},assetId:n.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:$.Unknown}}},populateCredential:ee,signedTxToHex:te,sortUTXOsByAmount:Ye,sortUTXOsByAmountAscending:Qe,sortUTXOsByAmountDescending:Ge,sortUTXOsStaking:ze,verifyDerivationPath:nt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Dt,exports.BitcoinLedgerWallet=class extends R{constructor(e,t,r,s,n){super(e,r),this.derivationPath=t,this.transport=s,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const r=function(e){return new h(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),i=await r.getMasterFingerprint(),a=_(e,t,n,Buffer.from(i,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(a,o,d),c=H(a,n,s,this.derivationPath);if(u.forEach((e=>{const[t,r]=e;c.updateInput(t,{partialSig:[{signature:r.signature,pubkey:r.pubkey}]})})),!c.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return c.finalizeAllInputs(),c.extractTransaction()}},exports.BitcoinProvider=class extends I{constructor(e=!0,r,s,n,i){super(),this.isMainnet=e,this.extraParams=i;const a=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#r=new t.HttpClient(s||o,a);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#s=new t.HttpClient(n||d,a)}#r;#s;async#n(e){return this.isMainnet?(await Promise.all(e.map((e=>this.#s.post("",e,{},this.extraParams))))).flat():this.#s.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#r.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0){const r=await this.#r.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!r?.length)return{confirmed:[],unconfirmed:[]};const s=r.map(this._parseUtxo),n=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return n(s);return n(await this.getScriptsForUtxos(s))}async getAddressFromScript(e){const t=await this.#s.post("",{jsonrpc:"2.0",id:`decode-script-${e}`,method:"decodescript",params:[e]},{},this.extraParams);if(t.result)return t.result.address;throw new Error(`Unable to resolve address for script: ${e}. ${t.error.message}`)}async getScriptsForUtxos(e){const[t,r]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),s=r.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),n=s.length?(await this.#n(s)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...t,...r.map(((e,t)=>({...e,script:n[t]?.result?.scriptPubKey.hex})))]}_parseUtxo(e){return{...e,txHash:e.txid,index:e.vout,value:Number(e.value),blockHeight:e.height,script:e.script,confirmations:e.confirmations}}async getBalances(e){const t=await this.#r.post(`/api/v2/address/${e}`,{},{},this.extraParams);return{available:BigInt(t.balance),pending:BigInt(t.unconfirmedBalance),final:BigInt(t.balance)+BigInt(t.unconfirmedBalance)}}async getChainHeight(){return(await this.#s.post("",{jsonrpc:"2.0",id:"nownodes",method:"getblockcount",params:[]},{},this.extraParams)).result}async getFeeRates(){const e={jsonrpc:"2.0",method:"estimatesmartfee"},t=await this.#n([{...e,id:"1",params:[1]},{...e,id:"2",params:[3]},{...e,id:"3",params:[6]}]).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(t[0]/1024)||1,medium:Math.ceil(t[1]/1024)||1,low:Math.ceil(t[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#s.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#r.post(`/api/v2/tx/${e}`,{},{},this.extraParams);return{block:t.blockHeight,fees:Number(t.fees),confirmations:t.confirmations,amount:Number(t.value),hash:t.txid,addresses:Array.from(new Set([...t.vin.map((e=>e.addresses||[])).flat(),...t.vout.map((e=>e.addresses||[])).flat()])),blockTime:t.blockTime,inputs:[...t.vin.map((e=>({...e,value:Number(e.value)})))],outputs:[...t.vout.map((e=>({...e,value:Number(e.value)})))]}}async getTxHistory(e){const t=await this.#r.post(`/api/v2/address/${e}`,{},{},this.extraParams);return await Promise.allSettled(t.txids?.slice(0,25).map((async t=>{try{const r=await this.#r.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const r=t.vin.filter((t=>t.addresses?.includes(e))),s=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),i=t.vout.filter((t=>!t.addresses?.includes(e))),a=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=a>o;let u=o-a;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=i.map((e=>e.addresses||[])).flat(),p=d?l:c,h=p.filter(((e,t)=>p.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:h,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,r)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:r=1,pollInterval:s=500}={}){try{return await this.getTransaction(e)}catch(n){if(r>=t)throw n;return await new Promise((e=>setTimeout(e,s))),this.waitForTx(e,{maxAttempts:t,attempt:r+1,pollInterval:s})}}},exports.BitcoinProviderAbstract=I,exports.BitcoinWallet=L,exports.BitcoinWalletAbstract=R,exports.BitcoinWalletVoid=class extends R{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=V,exports.ETH_ACCOUNT_PATH=D,exports.ETH_COIN_PATH=E,exports.JsonRpcBatchInternal=N,exports.LedgerSigner=X,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.createPSBTV2=_,exports.createPsbt=T,exports.createTransferTx=B,exports.createWalletPolicy=function(e,t,r,s){const n=new h.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new h.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=M,exports.getAddressFromXPub=function(e,t){const r=F(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=u.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=F,exports.getAppEth=k,exports.getBech32Address=C,exports.getBech32AddressFromXPub=function(e,t,r){return C(F(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return C(Buffer.from(s,"hex"),r)},exports.getEvmAddressFromPubKey=function(e){return n.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e){const t=await e.send(176,1,0,0),r=t.readUInt8(1),s=t.readUInt8(2+r),n=t.subarray(2,2+r),i=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:i.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=k(e),n=await s.getAddress(r??D,t,!0),i=new a;return i.publicKey=o.Buffer.from(n.publicKey,"hex"),i.chainCode=o.Buffer.from(n.chainCode,"hex"),i.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=A(e);if(!n)return 0;const{fee:i}=S(t,r,n,s,e);return n-i},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=k(e),i=M(t,r,s),a=await n.getAddress(i,!1,!1);return Buffer.from(a.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(i.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getTransferTxDetails=function(e,t,r,s,n){const i=S(e,t,r,s,P(n));return i.inputs||console.log("Unable to construct transaction, fee needed: ",i.fee),i},exports.getVoidSigner=function(e,t){return new n.VoidSigner(e,t)},exports.getWalletFromMnemonic=function(e,t,r){if(!(t>=0&&t%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return n.HDNodeWallet.fromMnemonic(n.Mnemonic.fromPhrase(e),M(t,r,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await c.mnemonicToSeed(e);return u.fromSeed(t).derivePath(D).neutered().toBase58()},exports.isERC20Transfer=O,exports.isNativeTxn=K,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),t)),{})},exports.onBalanceChange=async(e,t,r,s)=>{const n=new Set(e.map((e=>e.toLowerCase()))),i=new Set(t.map((e=>e.toLowerCase()))),a=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&i.has(e.to.toLowerCase())&&O(e,n)?s(e,{type:"erc20",contractAddress:e.to}):K(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",a);return{unsubscribe:()=>o.off("block",a)}},exports.openLedgerApp=async function(e,t){try{return(await e.send(224,216,0,0,Buffer.from(t,"ascii"))).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.psbt2ToPsbt0=H,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=S;
|
|
1
|
+
"use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@avalabs/avalanchejs"),i=require("hdkey"),o=require("buffer"),d=require("@openzeppelin/contracts/build/contracts/ERC20.json"),u=require("bip32"),c=require("bip39"),l=require("@ledgerhq/hw-transport"),p=require("@metamask/eth-sig-util"),h=require("ledger-bitcoin"),g=require("@ledgerhq/hw-app-btc/lib/bip32"),m=require("@noble/hashes/sha256"),f=require("@avalabs/glacier-sdk"),x=require("@avalabs/core-chains-sdk"),v=require("create-hash"),w=require("xss"),b=require("bip32-path"),A=require("@avalabs/hw-app-avalanche");function y(e){return e.reduce(((e,t)=>e+t.value),0)}class I{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:y(r.confirmed),balanceUnconfirmed:y(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function T(t,r,s){const n=new e.Psbt({network:s});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),r.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function S(e,t,s,n,a){const i=[{address:e,value:s}],{inputs:o,outputs:d,fee:u}=r(a,i,n);if(!o||!d)return{fee:u};const c=[d[0]],l=d[1];return l&&c.push({address:t,value:l.value}),{inputs:o,outputs:c,fee:u}}function B(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function P(e,t,r,s,n,a){const i=S(e,t,r,s,B(n));return i.inputs?{...i,psbt:T(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function C(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function E(e){return new s(e,"w0w")}const k="m/44'/60'",D=`${k}/0'`;var V=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(V||{});function M(e,t,r){if(e<0)throw new Error("Account index can not be less than 0.");const s="EVM"===r?"60":"9000";return t==V.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const O=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),U=(e,t)=>{const r=new n.Interface(d.abi).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var K=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"}];class N extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#e="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#e.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#e,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,K,this._parentProvider),this._maxCalls=62)}#e;#t=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#e.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function _(e,t){return u.fromBase58(e).derivePath(`0/${t}`).publicKey}let F=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=M(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=E(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=E(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,a=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof l.TransportStatusError&&s.statusCode===l.StatusCodes.INS_NOT_SUPPORTED){const s=p.TypedDataUtils.hashStruct(i,r,t,p.SignTypedDataVersion.V4),a=p.TypedDataUtils.hashStruct("EIP712Domain",e,t,p.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function X(t,r,s,n,a,i){const o=new h.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,g.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function L(t,r,s,n){const a=new e.Psbt({network:r}),i=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<i;e++){const r=t.getInputWitnessUtxo(e),i=t.getInputBip32Derivation(e,s);a.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:i?[{path:n,pubkey:s,masterFingerprint:i.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)a.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return a}class H{constructor(t,r){this.pubkey=t,this.provider=r;try{this.ecPair=e.ECPair.fromPublicKey(t)}catch(e){throw new Error("Not a valid public key.")}}ecPair;getAddressP2PKH(){return e.payments.p2pkh({pubkey:this.ecPair.publicKey,network:this.provider.getNetwork()}).address}getAddressBech32(){return C(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,r,s){return P(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class R extends H{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=V.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await c.mnemonicToSeed(e),a=u.fromSeed(n),i=M(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new R(o.privateKey,r)}signTx(e,t){const r=T(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(r))}static fromEthersWallet(e,t){const r=e.privateKey;if(!r)throw new Error("Unable to get private key from ethers wallet.");const s=Buffer.from(r.substring(2),"hex");return new R(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}var $=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.ConvertSubnetToL1="convert_subnet_to_l1",e.RegisterL1Validator="register_l1_validator",e.SetL1ValidatorWeight="set_l1_validator_weight",e.IncreaseL1ValidatorBalance="increase_l1_validator_balance",e.DisableL1Validator="disable_l1_validator",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))($||{});const q=e=>{switch(e){case"C":return a.EVM;case"X":return a.AVM;case"P":return a.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}},{getTransferableInputsByTx:W,AddressMaps:j}=a.utils,J=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const i=W(e),o=j.fromTransferableInputs(i,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>a.pvmSerial.isCreateChainTx(e)||a.pvmSerial.isAddSubnetValidatorTx(e)||a.pvmSerial.isRemoveSubnetValidatorTx(e)||a.pvmSerial.isTransformSubnetTx(e)||a.pvmSerial.isTransferSubnetOwnershipTx(e)||a.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),i=a.OutputOwners.fromNative(n.controlKeys.map((e=>a.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new a.utils.AddressMap(i)),r})({tx:e,provider:r,addressMaps:o});return new a.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else if(a.pvmSerial.isDisableL1ValidatorTx(e))try{const{deactivationOwner:t}=await r.getApiP().getL1Validator(e.validationId.toString()),s=e.getDisableAuth().values(),n=t.addresses.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);o.push(new a.utils.AddressMap(n))}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}return new a.UnsignedTx(e,n,o,s)},{bufferToHex:z,packTx:Y}=a.utils,{publicKeyBytesToAddress:G,recoverPublicKey:Q}=a.secp256k1,Z=new a.Signature(new Uint8Array(Array(65).fill(0))),ee=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(Z);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=Y(n.getTx()),d=m.sha256(o),u=Z.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=Q(d,e.toBytes()),r={toHex:()=>z(G(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function te(e){return a.utils.bufferToHex(a.utils.addChecksum(e.toBytes()))}const{getManagerForVM:re,hexToBuffer:se,unpackWithManager:ne}=a.utils,ae=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=q(t);if(n===a.EVM)throw new Error("EVM transactions are not supported");const i=se(e),o=ne(n,i),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const i=re(s).unpack(t,a.avaxSerial.SignedTx),o=await J({tx:e,utxos:n,provider:r,credentials:i.getCredentials()});return e.getSigIndices().map(((e,t)=>new a.Credential(ee(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new a.Credential(ee(e))))}})({tx:o,txBytes:i,provider:r,vm:n,utxos:s});return J({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:ie,format:oe}=a.utils,{publicKeyBytesToAddress:de}=a.secp256k1;class ue{constructor(e,t,r){this.baseUrl=e,this.context=t,this.upgradesInfo=r;const s=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(s)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}isEtnaEnabled(){return!!this.upgradesInfo&&a.utils.isEtnaEnabled(this.upgradesInfo)}getUpgradesInfo(){return this.upgradesInfo}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return a.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new a.avm.AVMApi(this.baseUrl)}getApiP(){return new a.pvm.PVMApi(this.baseUrl)}getApiC(){return new a.evm.EVMApi(this.baseUrl)}getInfo(){return new a.info.InfoApi(this.baseUrl)}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=de(a);return oe(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return oe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ie(e);return oe(t,this.getHrp(),r)}getApiByVM(e){switch(e){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(e){switch(e){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(e){const t=e.unsignedTx.getVM(),r=te(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,i)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&i(new Error("Timeout")),d=s instanceof a.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),d.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{o()}),1e3)}};o()}))}}const ce={weights:a.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},le={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e9),transformSubnetTxFee:BigInt(1e10),createBlockchainTxFee:BigInt(1e9),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:1,hrp:"avax",platformFeeConfig:ce},pe={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e8),transformSubnetTxFee:BigInt(1e9),createBlockchainTxFee:BigInt(1e8),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:5,hrp:"fuji",platformFeeConfig:ce},he={addPrimaryNetworkDelegatorFee:0n,addPrimaryNetworkValidatorFee:0n,addSubnetDelegatorFee:1000000n,addSubnetValidatorFee:1000000n,avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",createAssetTxFee:1000000n,createBlockchainTxFee:100000000n,createSubnetTxFee:100000000n,hrp:"custom",networkID:76,pBlockchainID:"11111111111111111111111111111111LpoYY",transformSubnetTxFee:100000000n,xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",platformFeeConfig:ce};class ge extends ue{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await a.Context.getContextFromURI(e);try{const r=await new a.info.InfoApi(e).getUpgradesInfo();return new ge(e,t,r)}catch{return new ge(e,t)}}static getDefaultMainnetProvider(e){return new ge(x.AVALANCHE_XP_NETWORK.rpcUrl,le,e)}static getDefaultFujiProvider(e){return new ge(x.AVALANCHE_XP_TEST_NETWORK.rpcUrl,pe,e)}static getDefaultDevnetProvider(e){return new ge(x.AVALANCHE_P_DEV_NETWORK.rpcUrl,he,e)}}const{bytesCompare:me,parseBech32:fe}=a.utils,xe=(e,t)=>"P"===t,ve=(e,t,r)=>{const s=xe(0,t)?e.amount:e.asset?.amount;return new a.TransferOutput(new a.BigIntPr(BigInt(s)),a.OutputOwners.fromNative(e.addresses.map((e=>fe(e)[1])).sort(me),BigInt(r??0),e.threshold))},we=(e,t)=>{const r=((e,t)=>{const r=t===f.Network.FUJI,s=t===f.Network.DEVNET,{cBlockchainID:n,xBlockchainID:a,pBlockchainID:i}=s?he:r?pe:le;if(n===e)return"C";if(a===e)return"X";if(i===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=xe(0,r)?e.txHash:e.creationTxHash,n=xe(0,r)?e.assetId:e.asset?.assetId;return new a.Utxo(a.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),a.Id.fromString(n),((e,t)=>xe(0,t)?e.stakeableLocktime?new a.pvmSerial.StakeableLockOut(new a.BigIntPr(BigInt(e.stakeableLocktime??0)),ve(e,t,e.platformLocktime??0)):ve(e,t,e.platformLocktime):ve(e,t,e.locktime))(e,r))},{unpackWithManager:be,parse:Ae,bufferToHex:ye,AddressMaps:Ie,AddressMap:Te}=a.utils;function Se(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return v("sha256").update(s).digest()}const Be=1024,Pe=1024;async function Ce(e,t,r){const s=e.slice(0,Be),n=e.slice(Be),a=await Ee(t,{...r,addresses:s});if(n.length){const s=await Ce(n,t,{...r,addresses:e});return a.merge(s)}return a}async function Ee(e,t){if(t.addresses.length>Be)throw new Error(`Can not get UTXOs for more than ${Be} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new a.utils.UtxoSet(s);if(s.length>=Pe){const s=await Ee(e,{...t,startIndex:r});return n.merge(s)}return n}function ke(){return BigInt(Math.floor(Date.now()/1e3))}const{isStakeableLockOut:De,isTransferOut:Ve}=a.utils,Me=e=>{const t=e.output,r=e.getOutputOwners();return{utxoId:e.ID(),assetId:e.getAssetId(),amount:Ve(t)||De(t)?t.amount():BigInt(0),locktime:r.locktime.value(),stakeableLocktime:De(t)?t.getStakeableLocktime():BigInt(0),threshold:r.threshold.value()}};async function Oe(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await Oe(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Ue,hexToBuffer:Ke,unpackWithManager:Ne}=a.utils;function _e(e,t=!0){try{if(t){const[t]=a.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else a.utils.parseBech32(e);return!0}catch(e){return!1}}const Fe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),Xe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0)),Le=e=>{if([le.xBlockchainID,pe.xBlockchainID,he.xBlockchainID].includes(e))return"AVM";if([le.pBlockchainID,pe.pBlockchainID,he.pBlockchainID].includes(e))return"PVM";if([le.cBlockchainID,pe.cBlockchainID,he.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")};var He={parseAddValidatorTx:e=>a.pvmSerial.isAddValidatorTx(e)?({feeData:t,assetId:r})=>({type:$.AddValidator,chain:e.getVM(),nodeID:e.validator.nodeId.value(),delegationFee:e.shares.value(),stake:Fe(e.stake,r),stakeOuts:e.stake,start:e.validator.startTime.value().toString(),end:e.validator.endTime.value().toString(),rewardOwner:e.getRewardsOwner(),...t}):null,parseAddDelegatorTx:e=>a.pvmSerial.isAddDelegatorTx(e)?({feeData:t,assetId:r})=>({type:$.AddDelegator,chain:e.getVM(),stake:Fe(e.stake,r),stakeOuts:e.stake,rewardOwner:e.getRewardsOwner(),nodeID:e.validator.nodeId.value(),start:e.validator.startTime.value().toString(),end:e.validator.endTime.value().toString(),...t}):null,parseCreateSubnetTx:e=>a.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:$.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>a.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:$.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>a.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:$.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>a.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:$.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>a.pvmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.evmSerial.isImportTx(e)?a.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:Le(e.sourceChain.value()),amount:Xe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:Le(e.sourceChain.value()),amount:Xe(e.ins,r),...t}):null,parseExportTx:e=>a.pvmSerial.isExportTx(e)||a.avmSerial.isExportTx(e)||a.evmSerial.isExportTx(e)?a.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:Le(e.destinationChain.toString()),amount:Fe(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:Le(e.destination.value()),amount:Fe(e.outs,r),...t}):null,parseBaseTx:e=>a.avmSerial.isAvmBaseTx(e)||a.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,i=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),a.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof a.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof a.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),o=ke(),d=i.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:$.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!a.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return a.pvmSerial.isSigner(e.signer)&&(r=a.utils.bufferToHex(e.signer.proof.publicKey),t=a.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:$.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>a.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:$.AddPermissionlessDelegator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),stakeOuts:e.stake,delegatorRewardsOwner:e.getDelegatorRewardsOwner(),...t}):null,parseTransformSubnetTx:e=>a.pvmSerial.isTransformSubnetTx(e)?({feeData:t})=>({type:$.TransformSubnet,chain:e.getVM(),subnetID:e.subnetID.toString(),assetID:e.assetId.toString(),initialSupply:e.initialSupply.value(),maximumSupply:e.maximumSupply.value(),minConsumptionRate:e.minConsumptionRate.value(),maxConsumptionRate:e.maxConsumptionRate.value(),minValidatorStake:e.minValidatorStake.value(),maxValidatorStake:e.maxValidatorStake.value(),minStakeDuration:e.minStakeDuration.value(),maxStakeDuration:e.maxStakeDuration.value(),minDelegationFee:e.minDelegationFee.value(),minDelegatorStake:e.minDelegatorStake.value(),maxValidatorWeightFactor:Number(e.maxValidatorWeightFactor.toJSON()),uptimeRequirement:e.uptimeRequirement.value(),...t}):null,parseTransferSubnetOwnershipTx:e=>a.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:$.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>a.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:$.ConvertSubnetToL1,chain:e.getVM(),managerAddress:n(a.Address.fromHex(e.address.toString("hex"))),validators:e.validators.map((e=>({nodeId:a.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>a.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:$.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>a.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:$.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>a.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:$.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>a.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:$.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:Re,getOutputAmounts:$e,getInputAmounts:qe,validateBurnedAmount:We}=a.utils;const{isStakeableLockOut:je,isTransferOut:Je}=a.utils;function ze(e){return e.sort(((e,t)=>{const r=e.output,s=t.output,n=je(r),a=je(s);if(n&&!a)return-1;if(a&&!n)return 1;if(je(r)&&je(s)){const e=r.getStakeableLocktime(),t=s.getStakeableLocktime();if(e<t)return 1;if(e>t)return-1}else if(Je(r)&&Je(s)){if(r.amount()>s.amount())return-1;if(r.amount()<s.amount())return 1}return 0}))}function Ye(e,t){return e.sort(((e,r)=>{const s=e.output,n=r.output;let a=BigInt(0);(Je(s)||je(s))&&(a=s.amount());let i=BigInt(0);(Je(n)||je(n))&&(i=n.amount());const o=t?i-a:a-i;return o>0?1:o<0?-1:0}))}const Ge=e=>Ye(e,!0),Qe=e=>Ye(e,!1);var Ze=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Ze||{});const et="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",tt="11111111111111111111111111111111LpoYY",rt=(e,t)=>e.reduce(((e,t)=>e+Me(t).amount),BigInt(0))-t,st={BaseP:{sortFunction:Ge,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new a.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:rt(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:Qe,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new a.utils.UtxoSet(t),amount:rt(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:ze,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new a.utils.UtxoSet(t),nodeId:et,start:ke(),end:ke()+BigInt(1e3),weight:rt(t,e.getProvider().getContext().baseTxFee),subnetId:tt,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(a.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(a.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:ze,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new a.utils.UtxoSet(t),nodeId:et,start:ke(),end:ke()+BigInt(1e3),weight:rt(t,e.getProvider().getContext().baseTxFee),subnetId:tt,feeState:r})},ExportP:{sortFunction:Ge,unsignedTxBuilder:(e,t,r)=>e.exportP({amount:rt(t,e.getProvider().getContext().baseTxFee),utxoSet:new a.utils.UtxoSet(t),destination:"X",feeState:r})},ImportP:{sortFunction:Ge,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new a.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function nt(e){return b.validateString(e,!0)&&6===e.split("/").length}function at(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:it,hexToBuffer:ot}=a.utils,dt=new Error("Tx type is not supported post-etna");class ut{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Ce(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Oe(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(e),s=this.provider.getChainID(t);return Ce(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=it(s)[2],i=this.provider.getAvaxID(),o=a.TransferableOutput.fromNative(i,e,[n]),d=Ye(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>it(e)[2])),l=it(this.getChangeAddress("X"))[2];return a.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:i}){const o=this.provider.getChainID(t),d=this.getAddresses("P").map((e=>it(e)[2])),u=it(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const c=it(r)[2],l=e.getUTXOs();if(this.provider.isEtnaEnabled()){if(!n)throw new Error("feeState parameter is required post E-upgrade");return a.pvm.e.newImportTx({fromAddressesBytes:d,utxos:l,toAddressesBytes:[c],sourceChainId:o,threshold:s,feeState:n,locktime:i},this.provider.getContext())}return a.pvm.newImportTx(this.provider.getContext(),o,l,[c],d,{changeAddresses:[u]})}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>it(e)[2])),i=it(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=it(r)[2];return a.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[i]})}importC(e,r,s,n,i){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>it(e)[2]));i=i||this.getAddressEVM();const u=Buffer.from(t.strip0x(i),"hex");return a.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const i=ot(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=it(n)[2],u=s/BigInt(1e9);return a.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,i,[d],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const i=it(n)[2],o=this.provider.getAvaxID(),d=a.TransferableOutput.fromNative(o,e,[i]),u=Ye(t.getUTXOs(),!0),c=this.provider.getChainID(r),l=this.getAddresses("P").map((e=>it(e)[2])),p=it(this.getChangeAddress("P"))[2];return this.provider.isEtnaEnabled()?(at(s),a.pvm.e.newExportTx({fromAddressesBytes:l,utxos:u,outputs:[d],destinationChainId:c,feeState:s},this.provider.getContext())):a.pvm.newExportTx(this.provider.getContext(),c,l,u,[d],{changeAddresses:[p]})}addValidator(e,t,r,s,n,i,o){const d=ze(e.getUTXOs()),u=this.getAddresses("P").map((e=>it(e)[2])),c=o?.rewardAddress||this.getCurrentAddress("P"),l=it(c)[2],p=it(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw dt;return a.pvm.newAddValidatorTx(this.provider.getContext(),d,u,t,s,n,r,[l],i,{changeAddresses:[p]})}addDelegator(e,t,r,s,n,i){const o=ze(e.getUTXOs()),d=this.getAddresses("P").map((e=>it(e)[2])),u=i?.rewardAddress||this.getCurrentAddress("P"),c=it(u)[2],l=it(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw dt;return a.pvm.newAddDelegatorTx(this.provider.getContext(),o,d,t,s,n,r,[c],{changeAddresses:[l]})}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const i=Qe(e.getUTXOs());s=s??this.getCurrentAddress("P");const o=it(s)[2],d=this.provider.getContext(),u=[a.TransferableOutput.fromNative(d.avaxAssetID,t,[o])],c=this.getAddresses("P").map((e=>it(e)[2]));return this.provider.isEtnaEnabled()?(at(r),a.pvm.e.newBaseTx({fromAddressesBytes:c,utxos:i,outputs:u,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},d)):a.pvm.newBaseTx(this.provider.getContext(),c,i,u,n)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:i,fromAddresses:o}){const[d,u,c]=it(r);if(d!==t||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const l=Object.entries(s).map((([e,t])=>a.TransferableOutput.fromNative(e,t,[c]))),p=Ye(e.getUTXOs(),!0),h=(o??this.getAddresses(t)).map((e=>it(e)[2]));return"X"===t?a.avm.newBaseTx(this.provider.getContext(),h,p,l,i):this.provider.isEtnaEnabled()?(at(n),a.pvm.e.newBaseTx({fromAddressesBytes:h,utxos:p,outputs:l,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:n},this.provider.getContext())):a.pvm.newBaseTx(this.provider.getContext(),h,p,l,i)}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:i,validators:o,options:d,fromAddresses:u}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const c=(u??this.getAddresses("P")).map((e=>it(e)[2])),l=o.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:i,remainingBalanceOwner:o})=>{const d=new a.pvmSerial.ProofOfPossession(Uint8Array.from(a.utils.hexToBuffer(t)),Uint8Array.from(a.utils.hexToBuffer(r))),u=a.PChainOwner.fromNative(o.addresses.map((e=>it(e)[2])),o.threshold??1),c=a.PChainOwner.fromNative(i.addresses.map((e=>it(e)[2])),i.threshold??1);return a.L1Validator.fromNative(e,n,s,d,u,c)}));return a.pvm.e.newConvertSubnetToL1Tx({changeAddressesBytes:d?.changeAddresses??c,validators:l,fromAddressesBytes:c,address:it(i)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:Ye(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:i,options:o}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const d=(i??this.getAddresses("P")).map((e=>it(e)[2]));return a.pvm.e.newRegisterL1ValidatorTx({utxos:Ye(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(a.utils.hexToBuffer(r)),changeAddressesBytes:o?.changeAddresses??d,feeState:n,fromAddressesBytes:d,memo:o?.memo,message:Uint8Array.from(a.utils.hexToBuffer(s)),minIssuanceTime:o?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(n??this.getAddresses("P")).map((e=>it(e)[2]));return a.pvm.e.newSetL1ValidatorWeightTx({utxos:Ye(e.getUTXOs(),!0),changeAddressesBytes:s?.changeAddresses??i,feeState:t,fromAddressesBytes:i,memo:s?.memo,message:Uint8Array.from(a.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const o=(s??this.getAddresses("P")).map((e=>it(e)[2]));return a.pvm.e.newDisableL1ValidatorTx({disableAuth:n,validationId:i,utxos:Ye(e.getUTXOs(),!0),changeAddressesBytes:r?.changeAddresses??o,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const o=(s??this.getAddresses("P")).map((e=>it(e)[2]));return a.pvm.e.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:i,utxos:Ye(e.getUTXOs(),!0),changeAddressesBytes:r?.changeAddresses??o,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:i,subnetAuth:o,feeState:d,options:u,fromAddresses:c}){const l=Ye(e.getUTXOs(),!0),p=(c??this.getAddresses("P")).map((e=>it(e)[2]));if(this.provider.isEtnaEnabled()){at(d);const e=(c??this.getAddresses("P")).map((e=>it(e)[2])),p=it(this.getChangeAddress("P"))[2];return a.pvm.e.newCreateChainTx({chainName:r,feeState:d,fromAddressesBytes:e,fxIds:n,genesisData:i,subnetAuth:o,subnetId:t,utxos:l,vmId:s,changeAddressesBytes:u?.changeAddresses??[p]},this.provider.getContext())}return a.pvm.newCreateBlockchainTx(this.provider.getContext(),l,p,t,r,s,n,i,o,u)}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:i,locktime:o}){const d=Ye(e.getUTXOs(),!0),u=(s??this.getAddresses("P")).map((e=>it(e)[2])),c=t.map((e=>it(e)[2]));return this.provider.isEtnaEnabled()?(at(r),a.pvm.e.newCreateSubnetTx({fromAddressesBytes:u,utxos:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:i,locktime:o,subnetOwners:c},this.provider.getContext())):a.pvm.newCreateSubnetTx(this.provider.getContext(),d,u,c,n,i??1,o??BigInt(0))}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d,fromAddresses:u,options:c}){const l=Ye(e.getUTXOs(),!0),p=(u??this.getAddresses("P")).map((e=>it(e)[2]));return this.provider.isEtnaEnabled()?(at(d),a.pvm.e.newAddSubnetValidatorTx({fromAddressesBytes:p,utxos:l,minIssuanceTime:c?.minIssuanceTime,memo:c?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d},this.provider.getContext())):a.pvm.newAddSubnetValidatorTx(this.provider.getContext(),l,p,t,r,s,n,i,o,c)}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,fromAddresses:u,rewardAddresses:c,delegatorRewardAddresses:l,publicKey:p,signature:h,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=ze(e.getUTXOs()),w=(u??this.getAddresses("P")).map((e=>it(e)[2])),b=(c??[this.getCurrentAddress("P")]).map((e=>it(e)[2])),A=(l??[this.getCurrentAddress("P")]).map((e=>it(e)[2]));if(!(i!==a.networkIDs.PrimaryNetworkID.toString()||p&&h))throw new Error("Must provide public key and signature for primary subnet.");const y=it(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return at(d),a.pvm.e.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:A,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:g?.changeAddresses?g.changeAddresses:[y],nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,publicKey:p,rewardAddresses:b,signature:h,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext());const I={changeAddresses:[y],...g??{}};return a.pvm.newAddPermissionlessValidatorTx(this.provider.getContext(),v,w,t,i,r,s,n,b,A,o,I,void 0,void 0,p,h)}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,fromAddresses:o,rewardAddresses:d,options:u,locktime:c,feeState:l,threshold:p,stakingAssetId:h}){const g=ze(e.getUTXOs()),m=(o??this.getAddresses("P")).map((e=>it(e)[2])),f=(d??[this.getCurrentAddress("P")]).map((e=>it(e)[2])),x=it(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return at(l),a.pvm.e.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,changeAddressesBytes:u?.changeAddresses?u.changeAddresses:[x],nodeId:t,start:r,end:s,weight:n,subnetId:i,rewardAddresses:f,locktime:c,stakingAssetId:h,threshold:p,feeState:l},this.provider.getContext());const v={changeAddresses:[x],...u??{}};return a.pvm.newAddPermissionlessDelegatorTx(this.provider.getContext(),g,m,t,i,r,s,n,f,v,void 0,void 0)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:i,options:o}){const d=Ye(e.getUTXOs(),!0),u=(n??this.getAddresses("P")).map((e=>it(e)[2]));return this.provider.isEtnaEnabled()?(at(i),a.pvm.e.newRemoveSubnetValidatorTx({fromAddressesBytes:u,utxos:d,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:i},this.provider.getContext())):a.pvm.newRemoveSubnetValidatorTx(this.provider.getContext(),d,u,t,r,s,o)}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:i,options:o,threshold:d,locktime:u}){const c=Ye(e.getUTXOs(),!0),l=(i??this.getAddresses("P")).map((e=>it(e)[2])),p=s.map((e=>it(e)[2]));return this.provider.isEtnaEnabled()?(at(n),a.pvm.e.newTransferSubnetOwnershipTx({fromAddressesBytes:l,utxos:c,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,subnetId:t,subnetAuth:r,subnetOwners:p,feeState:n,threshold:d,locktime:u},this.provider.getContext())):a.pvm.newTransferSubnetOwnershipTx(this.provider.getContext(),c,l,t,r,p,o,d??1,u??BigInt(0))}transformSubnetTx(e,t,r,s,n,i,o,d,u,c,l,p,h,g,m,f,x,v){const w=Ye(e.getUTXOs(),!0),b=(x??this.getAddresses("P")).map((e=>it(e)[2]));if(this.provider.isEtnaEnabled())throw dt;return a.pvm.newTransformSubnetTx(this.provider.getContext(),w,b,t,r,s,n,i,o,d,u,c,l,p,h,g,m,f,v)}}class ct extends ut{constructor(e,t,r){if(super(r),this.pubkeyXP=e,this.pubkeyC=t,33!==t.length||33!==e.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(e,r,s){const a=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new ct(o,d,s)}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!nt(r)||!nt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return ct.fromPublicKey(o.publicKey,i.publicKey,s)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return n.computeAddress(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(e){return[this.getAddress(e)]}getChangeAddress(e){return this.getAddress(e)}getCurrentAddress(e){return this.getAddress(e)}}const lt={type:"zondax",getApp:e=>new A(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,r={show:!1,hrp:"avax"}){const s=this.getApp(e);return{publicKey:(await s.getAddressAndPubKey(t.toString(),r.show,r.hrp)).publicKey}},async getXPUB(e,t){const r=this.getApp(e),s=await r.getExtendedPubKey(t,!1);return{pubKey:s.publicKey,chainCode:s.chain_code}},async signHash(e,t,r,s){const n=this.getApp(e),a=s.map((e=>e.toString(!0))),i=await n.signHash(r.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const a=this.getApp(e),i=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(r.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function pt(e){return!(await lt.getVersion(e)>="0.6.0")}const{parse:ht}=a.utils;class gt extends ut{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new ct(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath(M(0,V.BIP44,"EVM")).neutered();return new gt(n.toBase58(),a.publicKey,t)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(ht(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(ht(e)[2])))}getRawAddressC(){return Buffer.from(ht(this.getCurrentAddress("C"))[2])}}const{isTransferOut:mt,isStakeableLockOut:ft}=a.utils;function xt(e){const t=e.output;return mt(t)||ft(t)?t.getOwners():[]}function vt(e){const t=e.getTx();return a.avmSerial.isExportTx(t)||a.pvmSerial.isExportTx(t)?new Set(t.outs.map(xt).flat()):a.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(xt).flat()):new Set((t.baseTx?.outputs??[]).map(xt).flat())}const{parse:wt}=a.utils;class bt extends gt{constructor(e,t,r){super(e,t,r)}getAdditionalAddressesByIndices(e,t,r){return"C"===r?[]:e.map((e=>{const s=this.getAddressAtIndex(e,t,r),[,,n]=wt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await pt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=E(e),a=await lt.getXPUB(e,bt.getAccountPath("X")),i=u.fromPublicKey(a.pubKey,a.chainCode),o=M(0,V.BIP44,"EVM"),d=await s.getAddress(o,!1),c=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new bt(i.toBase58(),l,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>b.fromString(e))),l=[...vt(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>b.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:p})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=b.fromString(bt.getAccountPath(e.chain));return[...(await lt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:At}=a.utils;class yt extends gt{constructor(e,t,r){const s=u.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(At(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=u.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath(M(0,V.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new yt(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:It,sign:Tt,signHash:St}=a.secp256k1,{addChecksum:Bt}=a.utils;class Pt extends ct{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(It(e)),Buffer.from(It(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!nt(r)||!nt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(t),o=a.derivePath(r);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Pt(i.privateKey,o.privateKey,s)}async signMessage(e){const t=Se(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Bt(await St(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Tt(e.buffer,t))]}}const{strip0x:Ct}=a.utils;class Et extends ct{constructor(e,t,r,s,i){const o=a.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=a.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),i),this.pathXP=t,this.pathC=s,!nt(t)||!nt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await pt(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!nt(t)||!nt(r))throw new Error("Invalid path configuration.");const i=new s(e),o=await i.getAddress(r,!1),d=await i.getAddress(t,!1),u=Buffer.from(Ct(o.publicKey),"hex"),c=Buffer.from(Ct(d.publicKey),"hex"),l=Buffer.from(Ct(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Ct(n.SigningKey.computePublicKey(c,!0)),"hex");return new Et(p,t,l,r,a)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=b.fromString(this.getAccountPath(e.chain)),r=b.fromString(this.getPartialSignerPath(e.chain));return[...(await lt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:kt}=a.utils;var Dt=Object.freeze({__proto__:null,AbstractProvider:ue,AddressWallet:class extends ut{constructor(e,t,r,s,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=r,this.xpChangeAddress=s,r.length<1)throw new Error("Must have at least 1 xp address.");if(!n.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(r.some((e=>!_e(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!_e(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(s)}setChangeAddress(e){if(!_e(e,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=e}getAddressEVM(){return this.addressC}getAddresses(e){return("C"===e?[this.addressCoreEth]:this.xpAddresses).map((t=>this.provider.formatAddress(t,e)))}getChangeAddress(e){const t="C"===e?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(t,e)}getCurrentAddress(e){const t="C"===e?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(t,e)}},DevnetContext:he,FujiContext:pe,JsonRpcProvider:ge,LedgerSigner:Et,LedgerWallet:bt,MainnetContext:le,MnemonicWallet:yt,MnemonicWalletVoid:gt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=u.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof a.EVMUnsignedTx||"C"===t?a.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):a.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(kt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),a=`0/${this.activeAccountIndex}`,i=new Map;if("C"===n||!this.accountNode)return i;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[a,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&i.set(t,e)}return i}getAddressBipPaths(e,t){return 0===t.size?[b.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(b.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(r.getAddresses(),n),i=this.getAddressBipPaths([...vt(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=b.fromString(this.getAccountPath(e.chain));return[...(await lt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||b.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=Se(e.message),s=(await lt.signHash(e.transport,r,b.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(M(t,V.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),i=this.getSigningKeys(n,r,s);if(!i?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await a.addTxSignatures({unsignedTx:t,privateKeys:i}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=Se(e.message),s=await a.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Ze,StaticSigner:Pt,TxType:$,WalletAbstract:ut,WalletVoid:ct,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const i=await ae({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>i.addSignature(e))));const o=i.getCredentials(),d=i.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=o[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new a.Credential(s)),e}),[]),u=new a.UnsignedTx(i.getTx(),i.getInputUtxos(),i.addressMaps,d);return{signedTxHex:te(new a.avaxSerial.SignedTx(i.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:we,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=be(r,e),i=Ae(t)[2],o=ye(i);if(a.evmSerial.isExportTx(n))return new a.EVMUnsignedTx(n,[],new Ie([Te.fromJSON([[o,0]])]));if(a.evmSerial.isImportTx(n)){const e=Ie.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new a.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:J,digestMessage:Se,emptySignature:Z,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=u.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(i,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return u.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=ke();return n.forEach((e=>{const t=Me(e);s[t.threshold>1?"multisig":t.locktime>a?"locked":t.stakeableLocktime>a?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getLedgerProvider:async function(e){return lt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=st[r],o=ke(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=Me(e);return t<o&&(s<o||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),u=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let a=-1;for(;s<=n;){const i=Math.floor((s+n)/2);t(e.slice(0,i+1))<=r?(a=i,s=i+1):n=i-1}return a}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*Me(t).threshold)),0);return 6+e.toBytes().length+t}(i(e,t,n))}catch(e){return console.log("Unable to estimate size of utxos",{e:e,utxos:t.map(Me)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:Ee,getPchainUnixNow:async function(e){const t=e?x.AVALANCHE_XP_TEST_NETWORK.rpcUrl:x.AVALANCHE_XP_NETWORK.rpcUrl,r=await new a.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:Oe,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[a.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Ce,getUnixNow:ke,getUtxoInfo:Me,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:i})=>{const o=q(t),d=Ke(e),u=Ne(o,d);if(a.evmSerial.isExportTx(u))return[];const c=(e=>{if(a.evmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case a.EVM:return f.BlockchainId.C_CHAIN;case a.AVM:return f.BlockchainId.X_CHAIN;case a.PVM:return f.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Ue(u),p=new f.Glacier({BASE:s,TOKEN:n,HEADERS:i}),h=[...new Set(l.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(h.map((e=>p.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:r,txHash:e}))));return l.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=we(n,r);return e.push(a),e}),[])},getVmByChainAlias:q,getXpubFromMnemonic:function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=c.mnemonicToSeedSync(e);return u.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:_e,isConvertSubnetToL1Tx:function(e){return"convert_subnet_to_l1"===e.type},isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isDisableL1ValidatorTx:function(e){return"disable_l1_validator"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isIncreaseL1ValidatorBalance:function(e){return"increase_l1_validator_balance"===e.type},isObsidianApp:pt,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50}={}){try{const n=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(He)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=Re(i,n),u=$e(i),c=qe(i).get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0),p=u.get(n.avaxAssetID)??BigInt(0);let h,g=BigInt(0);a.evmSerial.isImportExportTx(i)?g=await t.getApiC().getBaseFee()/BigInt(1e9):"PVM"===i.vm&&(h=t.getUpgradesInfo(),g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0))));const{isValid:m,txFee:f}=We({upgradesInfo:h,unsignedTx:e,context:n,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f},assetId:n.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:$.Unknown}}},populateCredential:ee,signedTxToHex:te,sortUTXOsByAmount:Ye,sortUTXOsByAmountAscending:Qe,sortUTXOsByAmountDescending:Ge,sortUTXOsStaking:ze,verifyDerivationPath:nt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Dt,exports.BitcoinLedgerWallet=class extends H{constructor(e,t,r,s,n){super(e,r),this.derivationPath=t,this.transport=s,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const r=function(e){return new h(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=X(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=L(i,n,s,this.derivationPath);if(u.forEach((e=>{const[t,r]=e;c.updateInput(t,{partialSig:[{signature:r.signature,pubkey:r.pubkey}]})})),!c.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return c.finalizeAllInputs(),c.extractTransaction()}},exports.BitcoinProvider=class extends I{constructor(e=!0,r,s,n,a){super(),this.isMainnet=e,this.extraParams=a;const i=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#r=new t.HttpClient(s||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#s=new t.HttpClient(n||d,i)}#r;#s;async#n(e){return this.isMainnet?(await Promise.all(e.map((e=>this.#s.post("",e,{},this.extraParams))))).flat():this.#s.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#r.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0){const r=await this.#r.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!r?.length)return{confirmed:[],unconfirmed:[]};const s=r.map(this._parseUtxo),n=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return n(s);return n(await this.getScriptsForUtxos(s))}async getAddressFromScript(e){const t=await this.#s.post("",{jsonrpc:"2.0",id:`decode-script-${e}`,method:"decodescript",params:[e]},{},this.extraParams);if(t.result)return t.result.address;throw new Error(`Unable to resolve address for script: ${e}. ${t.error.message}`)}async getScriptsForUtxos(e){const[t,r]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),s=r.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),n=s.length?(await this.#n(s)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...t,...r.map(((e,t)=>({...e,script:n[t]?.result?.scriptPubKey.hex})))]}_parseUtxo(e){return{...e,txHash:e.txid,index:e.vout,value:Number(e.value),blockHeight:e.height,script:e.script,confirmations:e.confirmations}}async getBalances(e){const t=await this.#r.post(`/api/v2/address/${e}`,{},{},this.extraParams);return{available:BigInt(t.balance),pending:BigInt(t.unconfirmedBalance),final:BigInt(t.balance)+BigInt(t.unconfirmedBalance)}}async getChainHeight(){return(await this.#s.post("",{jsonrpc:"2.0",id:"nownodes",method:"getblockcount",params:[]},{},this.extraParams)).result}async getFeeRates(){const e={jsonrpc:"2.0",method:"estimatesmartfee"},t=await this.#n([{...e,id:"1",params:[1]},{...e,id:"2",params:[3]},{...e,id:"3",params:[6]}]).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(t[0]/1024)||1,medium:Math.ceil(t[1]/1024)||1,low:Math.ceil(t[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#s.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#r.post(`/api/v2/tx/${e}`,{},{},this.extraParams);return{block:t.blockHeight,fees:Number(t.fees),confirmations:t.confirmations,amount:Number(t.value),hash:t.txid,addresses:Array.from(new Set([...t.vin.map((e=>e.addresses||[])).flat(),...t.vout.map((e=>e.addresses||[])).flat()])),blockTime:t.blockTime,inputs:[...t.vin.map((e=>({...e,value:Number(e.value)})))],outputs:[...t.vout.map((e=>({...e,value:Number(e.value)})))]}}async getTxHistory(e){const t=await this.#r.post(`/api/v2/address/${e}`,{},{},this.extraParams);return await Promise.allSettled(t.txids?.slice(0,25).map((async t=>{try{const r=await this.#r.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const r=t.vin.filter((t=>t.addresses?.includes(e))),s=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),a=t.vout.filter((t=>!t.addresses?.includes(e))),i=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=i>o;let u=o-i;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=a.map((e=>e.addresses||[])).flat(),p=d?l:c,h=p.filter(((e,t)=>p.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:h,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,r)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:r=1,pollInterval:s=500}={}){try{return await this.getTransaction(e)}catch(n){if(r>=t)throw n;return await new Promise((e=>setTimeout(e,s))),this.waitForTx(e,{maxAttempts:t,attempt:r+1,pollInterval:s})}}},exports.BitcoinProviderAbstract=I,exports.BitcoinWallet=R,exports.BitcoinWalletAbstract=H,exports.BitcoinWalletVoid=class extends H{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=V,exports.ETH_ACCOUNT_PATH=D,exports.ETH_COIN_PATH=k,exports.JsonRpcBatchInternal=N,exports.LedgerSigner=F,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.createPSBTV2=X,exports.createPsbt=T,exports.createTransferTx=P,exports.createWalletPolicy=function(e,t,r,s){const n=new h.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new h.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=M,exports.getAddressFromXPub=function(e,t){const r=_(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=u.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=_,exports.getAppEth=E,exports.getBech32Address=C,exports.getBech32AddressFromXPub=function(e,t,r){return C(_(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return C(Buffer.from(s,"hex"),r)},exports.getEvmAddressFromPubKey=function(e){return n.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e){const t=await e.send(176,1,0,0),r=t.readUInt8(1),s=t.readUInt8(2+r),n=t.subarray(2,2+r),a=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:a.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=E(e),n=await s.getAddress(r??D,t,!0),a=new i;return a.publicKey=o.Buffer.from(n.publicKey,"hex"),a.chainCode=o.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=y(e);if(!n)return 0;const{fee:a}=S(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=E(e),a=M(t,r,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(a.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getTransferTxDetails=function(e,t,r,s,n){const a=S(e,t,r,s,B(n));return a.inputs||console.log("Unable to construct transaction, fee needed: ",a.fee),a},exports.getVoidSigner=function(e,t){return new n.VoidSigner(e,t)},exports.getWalletFromMnemonic=function(e,t,r){if(!(t>=0&&t%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return n.HDNodeWallet.fromMnemonic(n.Mnemonic.fromPhrase(e),M(t,r,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await c.mnemonicToSeed(e);return u.fromSeed(t).derivePath(D).neutered().toBase58()},exports.isERC20Transfer=U,exports.isNativeTxn=O,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),t)),{})},exports.onBalanceChange=async(e,t,r,s)=>{const n=new Set(e.map((e=>e.toLowerCase()))),a=new Set(t.map((e=>e.toLowerCase()))),i=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&a.has(e.to.toLowerCase())&&U(e,n)?s(e,{type:"erc20",contractAddress:e.to}):O(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",i);return{unsubscribe:()=>o.off("block",i)}},exports.openLedgerApp=async function(e,t){try{return(await e.send(224,216,0,0,Buffer.from(t,"ascii"))).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.psbt2ToPsbt0=L,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=S;
|
package/esm/Avalanche/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { AddDelegatorTx, AddPermissionlessDelegatorTx, AddPermissionlessValidatorTx, AddSubnetValidatorTx, AddValidatorTx, BaseTx, ChainIDAlias, CreateChainTx, CreateSubnetTx, ExportTx, FeeData, ImportTx, RemoveSubnetValidatorTx, TransferSubnetOwnershipTx, TransformSubnetTx, Tx, TxBase, TxType, UnknownTx, isAddDelegatorTx, isAddPermissionlessDelegatorTx, isAddPermissionlessValidatorTx, isAddSubnetValidatorTx, isAddValidatorTx, isBaseTx, isCreateChainTx, isCreateSubnetTx, isExportTx, isImportTx, isRemoveSubnetValidatorTx, isTransferSubnetOwnershipTx, isTransformSubnetTx } from './models.js';
|
|
1
|
+
export { AddDelegatorTx, AddPermissionlessDelegatorTx, AddPermissionlessValidatorTx, AddSubnetValidatorTx, AddValidatorTx, BaseTx, ChainIDAlias, ConvertSubnetToL1Tx, CreateChainTx, CreateSubnetTx, DisableL1ValidatorTx, ExportTx, FeeData, ImportTx, IncreaseL1ValidatorBalanceTx, RegisterL1ValidatorTx, RemoveSubnetValidatorTx, SetL1ValidatorWeightTx, TransferSubnetOwnershipTx, TransformSubnetTx, Tx, TxBase, TxType, UnknownTx, isAddDelegatorTx, isAddPermissionlessDelegatorTx, isAddPermissionlessValidatorTx, isAddSubnetValidatorTx, isAddValidatorTx, isBaseTx, isConvertSubnetToL1Tx, isCreateChainTx, isCreateSubnetTx, isDisableL1ValidatorTx, isExportTx, isImportTx, isIncreaseL1ValidatorBalance, isRegisterL1ValidatorTx, isRemoveSubnetValidatorTx, isSetL1ValidatorWeightTx, isTransferSubnetOwnershipTx, isTransformSubnetTx } from './models.js';
|
|
2
2
|
export { WalletAbstract } from './wallets/WalletAbstract.js';
|
|
3
3
|
export { WalletVoid } from './wallets/WalletVoid.js';
|
|
4
4
|
export { isObsidianApp } from './wallets/ledger/isObsidianApp.js';
|
package/esm/Avalanche/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{TxType,isAddDelegatorTx,isAddPermissionlessDelegatorTx,isAddPermissionlessValidatorTx,isAddSubnetValidatorTx,isAddValidatorTx,isBaseTx,isCreateChainTx,isCreateSubnetTx,isExportTx,isImportTx,isRemoveSubnetValidatorTx,isTransferSubnetOwnershipTx,isTransformSubnetTx}from"./models.js";export{WalletAbstract}from"./wallets/WalletAbstract.js";export{WalletVoid}from"./wallets/WalletVoid.js";export{isObsidianApp}from"./wallets/ledger/isObsidianApp.js";export{getLedgerProvider}from"./wallets/ledger/getLedgerProvider.js";export{AddressWallet}from"./wallets/AddressWallet.js";export{MnemonicWalletVoid}from"./wallets/legacy/MnemonicWalletVoid.js";export{LedgerWallet}from"./wallets/legacy/LedgerWallet.js";export{MnemonicWallet}from"./wallets/legacy/MnemonicWallet.js";export{StaticSigner}from"./wallets/StaticSigner.js";export{SimpleSigner}from"./wallets/SimpleSigner.js";export{LedgerSigner}from"./wallets/ledger/LedgerSigner.js";export{SimpleLedgerSigner}from"./wallets/ledger/SimpleLedgerSigner.js";export{AbstractProvider}from"./providers/AbstractProvider.js";export{JsonRpcProvider}from"./providers/JsonRpcProvider.js";export{DevnetContext,FujiContext,MainnetContext}from"./providers/constants.js";export{addSignaturesToAvalancheTx}from"./utils/addSignaturesToAvalancheTx.js";export{convertGlacierUtxo}from"./utils/convertGlacierUtxo.js";export{createAvalancheEvmUnsignedTx}from"./utils/createAvalancheEvmUnsignedTx.js";export{createAvalancheUnsignedTx}from"./utils/createAvalancheUnsignedTx.js";export{digestMessage}from"./utils/digestMessage.js";export{getAddressFromXpub}from"./utils/getAddressFromXpub.js";export{getAddressPublicKeyFromXpub}from"./utils/getAddressPublicKeyFromXpub.js";export{getPaginatedUTXOs,getUTXOsForAddresses}from"./utils/getAllUTXOs.js";export{getAssetBalance}from"./utils/getAssetBalance.js";export{getPchainUnixNow}from"./utils/getPchainUnixNow.js";export{getStakedAssetBalance}from"./utils/getStakedAssetBalance.js";export{getStakeForAddresses}from"./utils/getStakeForAddresses.js";export{getUnixNow}from"./utils/getUnixNow.js";export{getUtxoInfo}from"./utils/getUtxoInfo.js";export{getUtxosByTxFromGlacier}from"./utils/getUtxosByTxFromGlacier.js";export{getVmByChainAlias}from"./utils/getVmByChainAlias.js";export{getXpubFromMnemonic}from"./utils/getXpubFromMnemonic.js";export{isBech32Address}from"./utils/isBech32Address.js";export{parseAvalancheTx}from"./utils/parseAvalancheTx.js";export{emptySignature,populateCredential}from"./utils/populateCredential.js";export{signedTxToHex}from"./utils/signedTxToHex.js";export{sortUTXOsByAmount,sortUTXOsByAmountAscending,sortUTXOsByAmountDescending,sortUTXOsStaking}from"./utils/sortUTXOs.js";export{P_CHAIN_TX_SIZE_LIMIT,SizeSupportedTx,getMaximumUtxoSet}from"./utils/txSizeLimits.js";export{verifyDerivationPath}from"./utils/verifyDerivationPath.js";
|
|
1
|
+
export{TxType,isAddDelegatorTx,isAddPermissionlessDelegatorTx,isAddPermissionlessValidatorTx,isAddSubnetValidatorTx,isAddValidatorTx,isBaseTx,isConvertSubnetToL1Tx,isCreateChainTx,isCreateSubnetTx,isDisableL1ValidatorTx,isExportTx,isImportTx,isIncreaseL1ValidatorBalance,isRegisterL1ValidatorTx,isRemoveSubnetValidatorTx,isSetL1ValidatorWeightTx,isTransferSubnetOwnershipTx,isTransformSubnetTx}from"./models.js";export{WalletAbstract}from"./wallets/WalletAbstract.js";export{WalletVoid}from"./wallets/WalletVoid.js";export{isObsidianApp}from"./wallets/ledger/isObsidianApp.js";export{getLedgerProvider}from"./wallets/ledger/getLedgerProvider.js";export{AddressWallet}from"./wallets/AddressWallet.js";export{MnemonicWalletVoid}from"./wallets/legacy/MnemonicWalletVoid.js";export{LedgerWallet}from"./wallets/legacy/LedgerWallet.js";export{MnemonicWallet}from"./wallets/legacy/MnemonicWallet.js";export{StaticSigner}from"./wallets/StaticSigner.js";export{SimpleSigner}from"./wallets/SimpleSigner.js";export{LedgerSigner}from"./wallets/ledger/LedgerSigner.js";export{SimpleLedgerSigner}from"./wallets/ledger/SimpleLedgerSigner.js";export{AbstractProvider}from"./providers/AbstractProvider.js";export{JsonRpcProvider}from"./providers/JsonRpcProvider.js";export{DevnetContext,FujiContext,MainnetContext}from"./providers/constants.js";export{addSignaturesToAvalancheTx}from"./utils/addSignaturesToAvalancheTx.js";export{convertGlacierUtxo}from"./utils/convertGlacierUtxo.js";export{createAvalancheEvmUnsignedTx}from"./utils/createAvalancheEvmUnsignedTx.js";export{createAvalancheUnsignedTx}from"./utils/createAvalancheUnsignedTx.js";export{digestMessage}from"./utils/digestMessage.js";export{getAddressFromXpub}from"./utils/getAddressFromXpub.js";export{getAddressPublicKeyFromXpub}from"./utils/getAddressPublicKeyFromXpub.js";export{getPaginatedUTXOs,getUTXOsForAddresses}from"./utils/getAllUTXOs.js";export{getAssetBalance}from"./utils/getAssetBalance.js";export{getPchainUnixNow}from"./utils/getPchainUnixNow.js";export{getStakedAssetBalance}from"./utils/getStakedAssetBalance.js";export{getStakeForAddresses}from"./utils/getStakeForAddresses.js";export{getUnixNow}from"./utils/getUnixNow.js";export{getUtxoInfo}from"./utils/getUtxoInfo.js";export{getUtxosByTxFromGlacier}from"./utils/getUtxosByTxFromGlacier.js";export{getVmByChainAlias}from"./utils/getVmByChainAlias.js";export{getXpubFromMnemonic}from"./utils/getXpubFromMnemonic.js";export{isBech32Address}from"./utils/isBech32Address.js";export{parseAvalancheTx}from"./utils/parseAvalancheTx.js";export{emptySignature,populateCredential}from"./utils/populateCredential.js";export{signedTxToHex}from"./utils/signedTxToHex.js";export{sortUTXOsByAmount,sortUTXOsByAmountAscending,sortUTXOsByAmountDescending,sortUTXOsStaking}from"./utils/sortUTXOs.js";export{P_CHAIN_TX_SIZE_LIMIT,SizeSupportedTx,getMaximumUtxoSet}from"./utils/txSizeLimits.js";export{verifyDerivationPath}from"./utils/verifyDerivationPath.js";
|
|
@@ -4,7 +4,7 @@ type ChainIDAlias = 'X' | 'P' | 'C';
|
|
|
4
4
|
/**
|
|
5
5
|
* Types for parsed transaction
|
|
6
6
|
*/
|
|
7
|
-
type Tx = AddValidatorTx | AddDelegatorTx | ExportTx | ImportTx | BaseTx | CreateSubnetTx | CreateChainTx | AddSubnetValidatorTx | RemoveSubnetValidatorTx | AddPermissionlessValidatorTx | AddPermissionlessDelegatorTx | TransformSubnetTx | TransferSubnetOwnershipTx | UnknownTx;
|
|
7
|
+
type Tx = AddValidatorTx | AddDelegatorTx | ExportTx | ImportTx | BaseTx | CreateSubnetTx | CreateChainTx | AddSubnetValidatorTx | RemoveSubnetValidatorTx | AddPermissionlessValidatorTx | AddPermissionlessDelegatorTx | TransformSubnetTx | TransferSubnetOwnershipTx | ConvertSubnetToL1Tx | RegisterL1ValidatorTx | SetL1ValidatorWeightTx | DisableL1ValidatorTx | IncreaseL1ValidatorBalanceTx | UnknownTx;
|
|
8
8
|
interface FeeData {
|
|
9
9
|
totalAvaxBurned: bigint;
|
|
10
10
|
totalAvaxOutput: bigint;
|
|
@@ -24,6 +24,11 @@ declare enum TxType {
|
|
|
24
24
|
Import = "import",
|
|
25
25
|
CreateSubnet = "create_subnet",
|
|
26
26
|
CreateChain = "create_chain",
|
|
27
|
+
ConvertSubnetToL1 = "convert_subnet_to_l1",
|
|
28
|
+
RegisterL1Validator = "register_l1_validator",
|
|
29
|
+
SetL1ValidatorWeight = "set_l1_validator_weight",
|
|
30
|
+
IncreaseL1ValidatorBalance = "increase_l1_validator_balance",
|
|
31
|
+
DisableL1Validator = "disable_l1_validator",
|
|
27
32
|
AddSubnetValidator = "add_subnet_validator",
|
|
28
33
|
RemoveSubnetValidator = "remove_subnet_validator",
|
|
29
34
|
AddPermissionlessValidator = "add_permissionless_validator",
|
|
@@ -102,6 +107,35 @@ interface RemoveSubnetValidatorTx extends TxBase {
|
|
|
102
107
|
nodeID: string;
|
|
103
108
|
subnetID: string;
|
|
104
109
|
}
|
|
110
|
+
interface ConvertSubnetToL1Tx extends TxBase {
|
|
111
|
+
type: TxType.ConvertSubnetToL1;
|
|
112
|
+
managerAddress: string;
|
|
113
|
+
validators: {
|
|
114
|
+
nodeId: string;
|
|
115
|
+
stake: bigint;
|
|
116
|
+
balance: bigint;
|
|
117
|
+
remainingBalanceOwners: string[];
|
|
118
|
+
deactivationOwners: string[];
|
|
119
|
+
}[];
|
|
120
|
+
subnetID: string;
|
|
121
|
+
chainID: string;
|
|
122
|
+
}
|
|
123
|
+
interface RegisterL1ValidatorTx extends TxBase {
|
|
124
|
+
type: TxType.RegisterL1Validator;
|
|
125
|
+
balance: bigint;
|
|
126
|
+
}
|
|
127
|
+
interface SetL1ValidatorWeightTx extends TxBase {
|
|
128
|
+
type: TxType.SetL1ValidatorWeight;
|
|
129
|
+
}
|
|
130
|
+
interface IncreaseL1ValidatorBalanceTx extends TxBase {
|
|
131
|
+
type: TxType.IncreaseL1ValidatorBalance;
|
|
132
|
+
balance: bigint;
|
|
133
|
+
validationId: string;
|
|
134
|
+
}
|
|
135
|
+
interface DisableL1ValidatorTx extends TxBase {
|
|
136
|
+
type: TxType.DisableL1Validator;
|
|
137
|
+
validationId: string;
|
|
138
|
+
}
|
|
105
139
|
interface AddPermissionlessValidatorTx extends TxBase {
|
|
106
140
|
type: TxType.AddPermissionlessValidator;
|
|
107
141
|
nodeID: string;
|
|
@@ -161,6 +195,11 @@ declare function isAddDelegatorTx(tx: Tx): tx is AddDelegatorTx;
|
|
|
161
195
|
declare function isExportTx(tx: Tx): tx is ExportTx;
|
|
162
196
|
declare function isImportTx(tx: Tx): tx is ImportTx;
|
|
163
197
|
declare function isBaseTx(tx: Tx): tx is BaseTx;
|
|
198
|
+
declare function isConvertSubnetToL1Tx(tx: Tx): tx is ConvertSubnetToL1Tx;
|
|
199
|
+
declare function isRegisterL1ValidatorTx(tx: Tx): tx is RegisterL1ValidatorTx;
|
|
200
|
+
declare function isSetL1ValidatorWeightTx(tx: Tx): tx is SetL1ValidatorWeightTx;
|
|
201
|
+
declare function isDisableL1ValidatorTx(tx: Tx): tx is DisableL1ValidatorTx;
|
|
202
|
+
declare function isIncreaseL1ValidatorBalance(tx: Tx): tx is IncreaseL1ValidatorBalanceTx;
|
|
164
203
|
declare function isCreateSubnetTx(tx: Tx): tx is CreateSubnetTx;
|
|
165
204
|
declare function isCreateChainTx(tx: Tx): tx is CreateChainTx;
|
|
166
205
|
declare function isAddSubnetValidatorTx(tx: Tx): tx is AddSubnetValidatorTx;
|
|
@@ -170,4 +209,4 @@ declare function isAddPermissionlessDelegatorTx(tx: Tx): tx is AddPermissionless
|
|
|
170
209
|
declare function isTransformSubnetTx(tx: Tx): tx is TransformSubnetTx;
|
|
171
210
|
declare function isTransferSubnetOwnershipTx(tx: Tx): tx is TransferSubnetOwnershipTx;
|
|
172
211
|
|
|
173
|
-
export { AddDelegatorTx, AddPermissionlessDelegatorTx, AddPermissionlessValidatorTx, AddSubnetValidatorTx, AddValidatorTx, BaseTx, ChainIDAlias, CreateChainTx, CreateSubnetTx, ExportTx, FeeData, ImportTx, RemoveSubnetValidatorTx, TransferSubnetOwnershipTx, TransformSubnetTx, Tx, TxBase, TxType, UnknownTx, isAddDelegatorTx, isAddPermissionlessDelegatorTx, isAddPermissionlessValidatorTx, isAddSubnetValidatorTx, isAddValidatorTx, isBaseTx, isCreateChainTx, isCreateSubnetTx, isExportTx, isImportTx, isRemoveSubnetValidatorTx, isTransferSubnetOwnershipTx, isTransformSubnetTx };
|
|
212
|
+
export { AddDelegatorTx, AddPermissionlessDelegatorTx, AddPermissionlessValidatorTx, AddSubnetValidatorTx, AddValidatorTx, BaseTx, ChainIDAlias, ConvertSubnetToL1Tx, CreateChainTx, CreateSubnetTx, DisableL1ValidatorTx, ExportTx, FeeData, ImportTx, IncreaseL1ValidatorBalanceTx, RegisterL1ValidatorTx, RemoveSubnetValidatorTx, SetL1ValidatorWeightTx, TransferSubnetOwnershipTx, TransformSubnetTx, Tx, TxBase, TxType, UnknownTx, isAddDelegatorTx, isAddPermissionlessDelegatorTx, isAddPermissionlessValidatorTx, isAddSubnetValidatorTx, isAddValidatorTx, isBaseTx, isConvertSubnetToL1Tx, isCreateChainTx, isCreateSubnetTx, isDisableL1ValidatorTx, isExportTx, isImportTx, isIncreaseL1ValidatorBalance, isRegisterL1ValidatorTx, isRemoveSubnetValidatorTx, isSetL1ValidatorWeightTx, isTransferSubnetOwnershipTx, isTransformSubnetTx };
|
package/esm/Avalanche/models.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))(e||{});function t(e){return"add_validator"===e.type}function r(e){return"add_delegator"===e.type}function n(e){return"export"===e.type}function a(e){return"import"===e.type}function o(e){return"base"===e.type}function d(e){return"
|
|
1
|
+
var e=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.ConvertSubnetToL1="convert_subnet_to_l1",e.RegisterL1Validator="register_l1_validator",e.SetL1ValidatorWeight="set_l1_validator_weight",e.IncreaseL1ValidatorBalance="increase_l1_validator_balance",e.DisableL1Validator="disable_l1_validator",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))(e||{});function t(e){return"add_validator"===e.type}function r(e){return"add_delegator"===e.type}function n(e){return"export"===e.type}function a(e){return"import"===e.type}function o(e){return"base"===e.type}function i(e){return"convert_subnet_to_l1"===e.type}function d(e){return"register_l1_validator"===e.type}function s(e){return"set_l1_validator_weight"===e.type}function _(e){return"disable_l1_validator"===e.type}function u(e){return"increase_l1_validator_balance"===e.type}function l(e){return"create_subnet"===e.type}function c(e){return"create_chain"===e.type}function p(e){return"add_subnet_validator"===e.type}function b(e){return"remove_subnet_validator"===e.type}function f(e){return"add_permissionless_validator"===e.type}function v(e){return"add_permissionless_delegator"===e.type}function y(e){return"transform_subnet"===e.type}function m(e){return"transfer_subnet_ownership"===e.type}export{e as TxType,r as isAddDelegatorTx,v as isAddPermissionlessDelegatorTx,f as isAddPermissionlessValidatorTx,p as isAddSubnetValidatorTx,t as isAddValidatorTx,o as isBaseTx,i as isConvertSubnetToL1Tx,c as isCreateChainTx,l as isCreateSubnetTx,_ as isDisableL1ValidatorTx,n as isExportTx,a as isImportTx,u as isIncreaseL1ValidatorBalance,d as isRegisterL1ValidatorTx,b as isRemoveSubnetValidatorTx,s as isSetL1ValidatorWeightTx,m as isTransferSubnetOwnershipTx,y as isTransformSubnetTx};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{UnsignedTx as r,utils as
|
|
1
|
+
import{UnsignedTx as e,pvmSerial as r,utils as a}from"@avalabs/avalanchejs";import{isSubnetTx as t,handleSubnetAuth as s}from"./handleSubnetAuth.js";const{getTransferableInputsByTx:n,AddressMaps:i}=a,o=async({tx:o,fromAddressBytes:d,provider:l,credentials:u,utxos:p})=>{const h=n(o),c=i.fromTransferableInputs(h,p,BigInt(Math.floor((new Date).getTime()/1e3)),d);if(t(o))try{const r=await s({tx:o,provider:l,addressMaps:c});return new e(o,p,r,u)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else if(r.isDisableL1ValidatorTx(o))try{const{deactivationOwner:e}=await l.getApiP().getL1Validator(o.validationId.toString()),r=o.getDisableAuth().values(),t=e.addresses.reduce(((e,a,t)=>(r.includes(t)&&e.push([a,t]),e)),[]);c.push(new a.AddressMap(t))}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}return new e(o,p,c,u)};export{o as createAvalancheUnsignedTx,o as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pvmSerial as e,OutputOwners as t,utils as s}from"@avalabs/avalanchejs";const a=t=>e.isCreateChainTx(t)||e.isAddSubnetValidatorTx(t)||e.isRemoveSubnetValidatorTx(t)||e.isTransformSubnetTx(t)||e.isTransferSubnetOwnershipTx(t),r=async({tx:e,provider:a,addressMaps:r})=>{const n=e.getSubnetAuth().values(),i=await a.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),u=t.fromNative(i.controlKeys.map((e=>s.parse(e)[2])),BigInt(i.locktime),Number(i.threshold)).addrs.reduce(((e,t,s)=>(n.includes(s)&&e.push([t,s]),e)),[]);return r.push(new s.AddressMap(u)),r};export{r as handleSubnetAuth,a as isSubnetTx};
|
|
1
|
+
import{pvmSerial as e,OutputOwners as t,utils as s}from"@avalabs/avalanchejs";const a=t=>e.isCreateChainTx(t)||e.isAddSubnetValidatorTx(t)||e.isRemoveSubnetValidatorTx(t)||e.isTransformSubnetTx(t)||e.isTransferSubnetOwnershipTx(t)||e.isConvertSubnetToL1Tx(t),r=async({tx:e,provider:a,addressMaps:r})=>{const n=e.getSubnetAuth().values(),i=await a.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),u=t.fromNative(i.controlKeys.map((e=>s.parse(e)[2])),BigInt(i.locktime),Number(i.threshold)).addrs.reduce(((e,t,s)=>(n.includes(s)&&e.push([t,s]),e)),[]);return r.push(new s.AddressMap(u)),r};export{r as handleSubnetAuth,a as isSubnetTx};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import r from"./parseAddValidatorTx.js";import e from"./parseAddDelegatorTx.js";import
|
|
1
|
+
import r from"./parseAddValidatorTx.js";import e from"./parseAddDelegatorTx.js";import a from"./parseCreateSubnetTx.js";import s from"./parseCreateChainTx.js";import o from"./parseAddSubnetValidorTx.js";import t from"./parseImportTx.js";import p from"./parseExportTx.js";import i from"./parseBaseTx.js";import m from"./parseAddPermissionlessValidatorTx.js";import T from"./parseAddPermissionlessDelegatorTx.js";import x from"./parseRemoveSubnetValidatorTx.js";import d from"./parseTransformSubnetTx.js";import n from"./parseTransferSubnetOwnershipTx.js";import l from"./parseConvertSubnetToL1Tx.js";import f from"./parseRegisterL1ValidatorTx.js";import j from"./parseSetL1ValidatorWeightTx.js";import V from"./parseDisableL1ValidatorTx.js";import b from"./parseIncreaseL1ValidatorBalanceTx.js";var S={parseAddValidatorTx:r,parseAddDelegatorTx:e,parseCreateSubnetTx:a,parseCreateChainTx:s,parseAddSubnetValidatorTx:o,parseRemoveSubnetValidatorTx:x,parseImportTx:t,parseExportTx:p,parseBaseTx:i,parseAddPermissionlessValidatorTx:m,parseAddPermissionlessDelegatorTx:T,parseTransformSubnetTx:d,parseTransferSubnetOwnershipTx:n,parseConvertSubnetTx:l,parseRegisterL1ValidatorTx:f,parseIncreaseL1ValidatorBalanceTx:b,parseSetL1ValidatorWeightTx:j,parseDisableL1ValidatorTx:V};export{S as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pvmSerial as e,Address as a,NodeId as n}from"@avalabs/avalanchejs";import{TxType as t}from"../../models.js";const r=r=>e.isConvertSubnetToL1Tx(r)?({feeData:e,provider:o})=>{const s=o.getHrp(),i=e=>`P-${e.toString(s)}`;return{type:t.ConvertSubnetToL1,chain:r.getVM(),managerAddress:i(a.fromHex(r.address.toString("hex"))),validators:r.validators.map((e=>({nodeId:n.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(i),deactivationOwners:e.deactivationOwner.addresses.map(i)}))),chainID:r.chainID.value(),subnetID:r.subnetID.value(),...e}}:null;export{r as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pvmSerial as a}from"@avalabs/avalanchejs";import{TxType as t}from"../../models.js";const i=i=>a.isDisableL1ValidatorTx(i)?({feeData:a})=>({type:t.DisableL1Validator,chain:i.getVM(),validationId:i.validationId.toString(),...a}):null;export{i as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pvmSerial as a}from"@avalabs/avalanchejs";import{TxType as e}from"../../models.js";const l=l=>a.isIncreaseL1ValidatorBalanceTx(l)?({feeData:a})=>({type:e.IncreaseL1ValidatorBalance,chain:l.getVM(),balance:l.balance.value(),validationId:l.validationId.toString(),...a}):null;export{l as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pvmSerial as a}from"@avalabs/avalanchejs";import{TxType as e}from"../../models.js";const t=t=>a.isRegisterL1ValidatorTx(t)?({feeData:a})=>({type:e.RegisterL1Validator,chain:t.getVM(),balance:t.balance.value(),...a}):null;export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pvmSerial as a}from"@avalabs/avalanchejs";import{TxType as t}from"../../models.js";const e=e=>a.isSetL1ValidatorWeightTx(e)?({feeData:a})=>({type:t.SetL1ValidatorWeight,chain:e.getVM(),...a}):null;export{e as default};
|
|
@@ -40,6 +40,75 @@ type CreateSubnet = {
|
|
|
40
40
|
threshold?: number;
|
|
41
41
|
locktime?: bigint;
|
|
42
42
|
};
|
|
43
|
+
type CreateChain = {
|
|
44
|
+
utxoSet: utils.UtxoSet;
|
|
45
|
+
subnetId: string;
|
|
46
|
+
chainName: string;
|
|
47
|
+
vmID: string;
|
|
48
|
+
fxIds: string[];
|
|
49
|
+
genesisData: Record<string, unknown>;
|
|
50
|
+
subnetAuth: number[];
|
|
51
|
+
feeState?: pvm.FeeState;
|
|
52
|
+
options?: Common.SpendOptions;
|
|
53
|
+
fromAddresses?: string[];
|
|
54
|
+
};
|
|
55
|
+
type ConvertSubnetToL1 = {
|
|
56
|
+
utxoSet: utils.UtxoSet;
|
|
57
|
+
address: string;
|
|
58
|
+
chainId: string;
|
|
59
|
+
subnetId: string;
|
|
60
|
+
subnetAuth: number[];
|
|
61
|
+
options?: Common.SpendOptions;
|
|
62
|
+
feeState: pvm.FeeState;
|
|
63
|
+
fromAddresses?: string[];
|
|
64
|
+
validators: {
|
|
65
|
+
nodeId: string;
|
|
66
|
+
weight: bigint;
|
|
67
|
+
balance: bigint;
|
|
68
|
+
pubKey: string;
|
|
69
|
+
signature: string;
|
|
70
|
+
remainingBalanceOwner: {
|
|
71
|
+
addresses: string[];
|
|
72
|
+
threshold?: number;
|
|
73
|
+
};
|
|
74
|
+
deactivationOwner: {
|
|
75
|
+
addresses: string[];
|
|
76
|
+
threshold?: number;
|
|
77
|
+
};
|
|
78
|
+
}[];
|
|
79
|
+
};
|
|
80
|
+
type RegisterL1Validator = {
|
|
81
|
+
utxoSet: utils.UtxoSet;
|
|
82
|
+
balance: bigint;
|
|
83
|
+
signature: string;
|
|
84
|
+
feeState: pvm.FeeState;
|
|
85
|
+
message: string;
|
|
86
|
+
options?: Common.SpendOptions;
|
|
87
|
+
fromAddresses?: string[];
|
|
88
|
+
};
|
|
89
|
+
type SetL1ValidatorWeight = {
|
|
90
|
+
utxoSet: utils.UtxoSet;
|
|
91
|
+
feeState: pvm.FeeState;
|
|
92
|
+
message: string;
|
|
93
|
+
options?: Common.SpendOptions;
|
|
94
|
+
fromAddresses?: string[];
|
|
95
|
+
};
|
|
96
|
+
type DisableL1Validator = {
|
|
97
|
+
utxoSet: utils.UtxoSet;
|
|
98
|
+
feeState: pvm.FeeState;
|
|
99
|
+
disableAuth: number[];
|
|
100
|
+
validationId: string;
|
|
101
|
+
options?: Common.SpendOptions;
|
|
102
|
+
fromAddresses?: string[];
|
|
103
|
+
};
|
|
104
|
+
type IncreaseL1ValidatorBalance = {
|
|
105
|
+
utxoSet: utils.UtxoSet;
|
|
106
|
+
feeState: pvm.FeeState;
|
|
107
|
+
balance: bigint;
|
|
108
|
+
validationId: string;
|
|
109
|
+
options?: Common.SpendOptions;
|
|
110
|
+
fromAddresses?: string[];
|
|
111
|
+
};
|
|
43
112
|
type AddSubnetValidator = {
|
|
44
113
|
utxoSet: utils.UtxoSet;
|
|
45
114
|
nodeId: string;
|
|
@@ -107,4 +176,4 @@ type TransferSubnetOwnershipTx = {
|
|
|
107
176
|
locktime?: bigint;
|
|
108
177
|
};
|
|
109
178
|
|
|
110
|
-
export { AddPermissionlessDelegator, AddPermissionlessValidator, AddSubnetValidator, BaseTx, ConsolidateP, CreateSubnet, ExportP, ImportP, RemoveSubnetValidator, TransferSubnetOwnershipTx };
|
|
179
|
+
export { AddPermissionlessDelegator, AddPermissionlessValidator, AddSubnetValidator, BaseTx, ConsolidateP, ConvertSubnetToL1, CreateChain, CreateSubnet, DisableL1Validator, ExportP, ImportP, IncreaseL1ValidatorBalance, RegisterL1Validator, RemoveSubnetValidator, SetL1ValidatorWeight, TransferSubnetOwnershipTx };
|
|
@@ -2,7 +2,7 @@ import * as _avalabs_avalanchejs from '@avalabs/avalanchejs';
|
|
|
2
2
|
import { utils, pvm, Common } from '@avalabs/avalanchejs';
|
|
3
3
|
import { AbstractProvider } from '../providers/AbstractProvider.js';
|
|
4
4
|
import { ChainIDAlias } from '../models.js';
|
|
5
|
-
import { ImportP, ExportP, ConsolidateP, BaseTx, CreateSubnet, AddSubnetValidator, AddPermissionlessValidator, AddPermissionlessDelegator, RemoveSubnetValidator, TransferSubnetOwnershipTx } from './TxBuilderTypes.js';
|
|
5
|
+
import { ImportP, ExportP, ConsolidateP, BaseTx, ConvertSubnetToL1, RegisterL1Validator, SetL1ValidatorWeight, DisableL1Validator, IncreaseL1ValidatorBalance, CreateChain, CreateSubnet, AddSubnetValidator, AddPermissionlessValidator, AddPermissionlessDelegator, RemoveSubnetValidator, TransferSubnetOwnershipTx } from './TxBuilderTypes.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* An abstract class that that is shared by all wallet classes.
|
|
@@ -90,7 +90,12 @@ declare abstract class WalletAbstract {
|
|
|
90
90
|
}): Common.UnsignedTx;
|
|
91
91
|
consolidateP({ utxoSet, amount, feeState, toAddress, options, }: ConsolidateP): Common.UnsignedTx;
|
|
92
92
|
baseTX({ utxoSet, chain, toAddress, amountsPerAsset, feeState, options, fromAddresses, }: BaseTx): Common.UnsignedTx;
|
|
93
|
-
|
|
93
|
+
convertSubnetToL1({ utxoSet, chainId, subnetId, subnetAuth, feeState, address, validators, options, fromAddresses, }: ConvertSubnetToL1): Common.UnsignedTx;
|
|
94
|
+
registerL1Validator({ utxoSet, balance, signature, message, feeState, fromAddresses, options, }: RegisterL1Validator): Common.UnsignedTx;
|
|
95
|
+
setL1ValidatorWeight({ utxoSet, feeState, message, options, fromAddresses, }: SetL1ValidatorWeight): Common.UnsignedTx;
|
|
96
|
+
disableL1Validator({ utxoSet, feeState, options, fromAddresses, disableAuth, validationId, }: DisableL1Validator): Common.UnsignedTx;
|
|
97
|
+
increaseL1ValidatorBalance({ utxoSet, feeState, options, fromAddresses, balance, validationId, }: IncreaseL1ValidatorBalance): Common.UnsignedTx;
|
|
98
|
+
createBlockchain({ utxoSet, subnetId, chainName, vmID, fxIds, genesisData, subnetAuth, feeState, options, fromAddresses, }: CreateChain): Common.UnsignedTx;
|
|
94
99
|
createSubnet({ utxoSet, rewardAddresses, feeState, fromAddresses, options, threshold, locktime, }: CreateSubnet): Common.UnsignedTx;
|
|
95
100
|
addSubnetValidator({ utxoSet, nodeId, start, end, weight, subnetId, subnetAuth, feeState, fromAddresses, options, }: AddSubnetValidator): Common.UnsignedTx;
|
|
96
101
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TransferableOutput as e,avm as t,pvm as s,evm as r,networkIDs as d,utils as i}from"@avalabs/avalanchejs";import"../utils/populateCredential.js";import"@avalabs/glacier-sdk";import{strip0x as o}from"@avalabs/core-utils-sdk";import"ethers";import"../providers/constants.js";import"@avalabs/core-chains-sdk";import"create-hash";import"bip32";import{getUTXOsForAddresses as n}from"../utils/getAllUTXOs.js";import{getStakeForAddresses as a}from"../utils/getStakeForAddresses.js";import"bip39";import"xss";import{sortUTXOsByAmount as h,sortUTXOsStaking as m,sortUTXOsByAmountAscending as g}from"../utils/sortUTXOs.js";import"bip32-path";import{assertFeeStateProvided as p}from"../../utils/assertFeeStateProvided.js";const{parse:u,hexToBuffer:A}=i,c=new Error("Tx type is not supported post-etna");class x{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return n(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return a(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const s=this.provider.getApi(e),r=this.provider.getChainID(t);return n(this.getAddresses(e),s,{sourceChain:r,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(s,r,d,i){i=i||this.getCurrentAddress(d);const o=u(i)[2],n=this.provider.getAvaxID(),a=e.fromNative(n,s,[o]),m=h(r.getUTXOs(),!0),g=this.provider.getChainID(d),p=this.getAddresses("X").map((e=>u(e)[2])),A=u(this.getChangeAddress("X"))[2];return t.newExportTx(this.provider.getContext(),g,p,m,[a],{threshold:1,changeAddresses:[A]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:d,feeState:i,locktime:o}){const n=this.provider.getChainID(t),a=this.getAddresses("P").map((e=>u(e)[2])),h=u(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const m=u(r)[2],g=e.getUTXOs();if(this.provider.isEtnaEnabled()){if(!i)throw new Error("feeState parameter is required post E-upgrade");return s.e.newImportTx({fromAddressesBytes:a,utxos:g,toAddressesBytes:[m],sourceChainId:n,threshold:d,feeState:i,locktime:o},this.provider.getContext())}return s.newImportTx(this.provider.getContext(),n,g,[m],a,{changeAddresses:[h]})}importX(e,s,r){const d=this.provider.getChainID(s),i=this.getAddresses("X").map((e=>u(e)[2])),o=u(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const n=u(r)[2];return t.newImportTx(this.provider.getContext(),d,e.getUTXOs(),[n],i,{changeAddresses:[o]})}importC(e,t,s,d,i){const n=this.provider.getChainID(t),a=this.getAddresses("C").map((e=>u(e)[2]));i=i||this.getAddressEVM();const h=Buffer.from(o(i),"hex");return r.newImportTxFromBaseFee(this.provider.getContext(),h,a,e.getUTXOs(),n,s,d)}exportC(e,t,s,d,i){const o=A(this.getAddressEVM()),n=this.provider.getChainID(t);i=i||this.getCurrentAddress(t);const a=u(i)[2],h=d/BigInt(1e9);return r.newExportTxFromBaseFee(this.provider.getContext(),h,e,n,o,[a],s)}exportP({amount:t,utxoSet:r,destination:d,feeState:i,toAddress:o}){o=o||this.getCurrentAddress(d);const n=u(o)[2],a=this.provider.getAvaxID(),m=e.fromNative(a,t,[n]),g=h(r.getUTXOs(),!0),A=this.provider.getChainID(d),c=this.getAddresses("P").map((e=>u(e)[2])),x=u(this.getChangeAddress("P"))[2];return this.provider.isEtnaEnabled()?(p(i),s.e.newExportTx({fromAddressesBytes:c,utxos:g,outputs:[m],destinationChainId:A,feeState:i},this.provider.getContext())):s.newExportTx(this.provider.getContext(),A,c,g,[m],{changeAddresses:[x]})}addValidator(e,t,r,d,i,o,n){const a=m(e.getUTXOs()),h=this.getAddresses("P").map((e=>u(e)[2])),g=n?.rewardAddress||this.getCurrentAddress("P"),p=u(g)[2],A=u(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw c;return s.newAddValidatorTx(this.provider.getContext(),a,h,t,d,i,r,[p],o,{changeAddresses:[A]})}addDelegator(e,t,r,d,i,o){const n=m(e.getUTXOs()),a=this.getAddresses("P").map((e=>u(e)[2])),h=o?.rewardAddress||this.getCurrentAddress("P"),g=u(h)[2],p=u(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw c;return s.newAddDelegatorTx(this.provider.getContext(),n,a,t,d,i,r,[g],{changeAddresses:[p]})}consolidateP({utxoSet:t,amount:r,feeState:d,toAddress:i,options:o}){const n=g(t.getUTXOs());i=i??this.getCurrentAddress("P");const a=u(i)[2],h=this.provider.getContext(),m=[e.fromNative(h.avaxAssetID,r,[a])],A=this.getAddresses("P").map((e=>u(e)[2]));return this.provider.isEtnaEnabled()?(p(d),s.e.newBaseTx({fromAddressesBytes:A,utxos:n,outputs:m,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,feeState:d},h)):s.newBaseTx(this.provider.getContext(),A,n,m,o)}baseTX({utxoSet:r,chain:d,toAddress:i,amountsPerAsset:o,feeState:n,options:a,fromAddresses:m}){const[g,A,c]=u(i);if(g!==d||A!==this.provider.getHrp())throw new Error(`Invalid recipient address "${i}"`);const x=Object.entries(o).map((([t,s])=>e.fromNative(t,s,[c]))),v=h(r.getUTXOs(),!0),l=(m??this.getAddresses(d)).map((e=>u(e)[2]));return"X"===d?t.newBaseTx(this.provider.getContext(),l,v,x,a):this.provider.isEtnaEnabled()?(p(n),s.e.newBaseTx({fromAddressesBytes:l,utxos:v,outputs:x,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext())):s.newBaseTx(this.provider.getContext(),l,v,x,a)}createBlockchain(e,t,r,d,i,o,n,a,m){const g=h(e.getUTXOs(),!0),p=(m??this.getAddresses("P")).map((e=>u(e)[2]));if(this.provider.isEtnaEnabled())throw c;return s.newCreateBlockchainTx(this.provider.getContext(),g,p,t,r,d,i,o,n,a)}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:d,options:i,threshold:o,locktime:n}){const a=h(e.getUTXOs(),!0),m=(d??this.getAddresses("P")).map((e=>u(e)[2])),g=t.map((e=>u(e)[2]));return this.provider.isEtnaEnabled()?(p(r),s.e.newCreateSubnetTx({fromAddressesBytes:m,utxos:a,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:r,threshold:o,locktime:n,subnetOwners:g},this.provider.getContext())):s.newCreateSubnetTx(this.provider.getContext(),a,m,g,i,o??1,n??BigInt(0))}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:d,weight:i,subnetId:o,subnetAuth:n,feeState:a,fromAddresses:m,options:g}){const A=h(e.getUTXOs(),!0),c=(m??this.getAddresses("P")).map((e=>u(e)[2]));return this.provider.isEtnaEnabled()?(p(a),s.e.newAddSubnetValidatorTx({fromAddressesBytes:c,utxos:A,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,nodeId:t,start:r,end:d,weight:i,subnetId:o,subnetAuth:n,feeState:a},this.provider.getContext())):s.newAddSubnetValidatorTx(this.provider.getContext(),A,c,t,r,d,i,o,n,g)}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:i,weight:o,subnetId:n,shares:a,feeState:h,fromAddresses:g,rewardAddresses:A,delegatorRewardAddresses:c,publicKey:x,signature:v,options:l,threshold:T,locktime:f,stakingAssetId:C}){const w=m(e.getUTXOs()),b=(g??this.getAddresses("P")).map((e=>u(e)[2])),I=(A??[this.getCurrentAddress("P")]).map((e=>u(e)[2])),S=(c??[this.getCurrentAddress("P")]).map((e=>u(e)[2]));if(!(n!==d.PrimaryNetworkID.toString()||x&&v))throw new Error("Must provide public key and signature for primary subnet.");const P=u(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return p(h),s.e.newAddPermissionlessValidatorTx({fromAddressesBytes:b,delegatorRewardsOwner:S,utxos:w,minIssuanceTime:l?.minIssuanceTime,memo:l?.memo,changeAddressesBytes:l?.changeAddresses?l.changeAddresses:[P],nodeId:t,start:r,end:i,weight:o,subnetId:n,shares:a,feeState:h,publicKey:x,rewardAddresses:I,signature:v,locktime:f,threshold:T,stakingAssetId:C},this.provider.getContext());const E={changeAddresses:[P],...l??{}};return s.newAddPermissionlessValidatorTx(this.provider.getContext(),w,b,t,n,r,i,o,I,S,a,E,void 0,void 0,x,v)}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:d,weight:i,subnetId:o,fromAddresses:n,rewardAddresses:a,options:h,locktime:g,feeState:A,threshold:c,stakingAssetId:x}){const v=m(e.getUTXOs()),l=(n??this.getAddresses("P")).map((e=>u(e)[2])),T=(a??[this.getCurrentAddress("P")]).map((e=>u(e)[2])),f=u(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return p(A),s.e.newAddPermissionlessDelegatorTx({fromAddressesBytes:l,utxos:v,minIssuanceTime:h?.minIssuanceTime,memo:h?.memo,changeAddressesBytes:h?.changeAddresses?h.changeAddresses:[f],nodeId:t,start:r,end:d,weight:i,subnetId:o,rewardAddresses:T,locktime:g,stakingAssetId:x,threshold:c,feeState:A},this.provider.getContext());const C={changeAddresses:[f],...h??{}};return s.newAddPermissionlessDelegatorTx(this.provider.getContext(),v,l,t,o,r,d,i,T,C,void 0,void 0)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:d,fromAddresses:i,feeState:o,options:n}){const a=h(e.getUTXOs(),!0),m=(i??this.getAddresses("P")).map((e=>u(e)[2]));return this.provider.isEtnaEnabled()?(p(o),s.e.newRemoveSubnetValidatorTx({fromAddressesBytes:m,utxos:a,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,nodeId:t,subnetId:r,subnetAuth:d,feeState:o},this.provider.getContext())):s.newRemoveSubnetValidatorTx(this.provider.getContext(),a,m,t,r,d,n)}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:d,feeState:i,fromAddresses:o,options:n,threshold:a,locktime:m}){const g=h(e.getUTXOs(),!0),A=(o??this.getAddresses("P")).map((e=>u(e)[2])),c=d.map((e=>u(e)[2]));return this.provider.isEtnaEnabled()?(p(i),s.e.newTransferSubnetOwnershipTx({fromAddressesBytes:A,utxos:g,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,subnetId:t,subnetAuth:r,subnetOwners:c,feeState:i,threshold:a,locktime:m},this.provider.getContext())):s.newTransferSubnetOwnershipTx(this.provider.getContext(),g,A,t,r,c,n,a??1,m??BigInt(0))}transformSubnetTx(e,t,r,d,i,o,n,a,m,g,p,A,x,v,l,T,f,C){const w=h(e.getUTXOs(),!0),b=(f??this.getAddresses("P")).map((e=>u(e)[2]));if(this.provider.isEtnaEnabled())throw c;return s.newTransformSubnetTx(this.provider.getContext(),w,b,t,r,d,i,o,n,a,m,g,p,A,x,v,l,T,C)}}export{x as WalletAbstract};
|
|
1
|
+
import{TransferableOutput as e,avm as t,pvm as s,evm as r,pvmSerial as d,utils as o,PChainOwner as i,L1Validator as n,networkIDs as a}from"@avalabs/avalanchejs";import"../utils/populateCredential.js";import"@avalabs/glacier-sdk";import{strip0x as h}from"@avalabs/core-utils-sdk";import"ethers";import"../providers/constants.js";import"@avalabs/core-chains-sdk";import"create-hash";import"bip32";import{getUTXOsForAddresses as m}from"../utils/getAllUTXOs.js";import{getStakeForAddresses as u}from"../utils/getStakeForAddresses.js";import"bip39";import"xss";import{sortUTXOsByAmount as g,sortUTXOsStaking as p,sortUTXOsByAmountAscending as A}from"../utils/sortUTXOs.js";import"bip32-path";import{assertFeeStateProvided as c}from"../../utils/assertFeeStateProvided.js";const{parse:x,hexToBuffer:f}=o,l=new Error("Tx type is not supported post-etna");class v{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return m(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return u(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const s=this.provider.getApi(e),r=this.provider.getChainID(t);return m(this.getAddresses(e),s,{sourceChain:r,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(s,r,d,o){o=o||this.getCurrentAddress(d);const i=x(o)[2],n=this.provider.getAvaxID(),a=e.fromNative(n,s,[i]),h=g(r.getUTXOs(),!0),m=this.provider.getChainID(d),u=this.getAddresses("X").map((e=>x(e)[2])),p=x(this.getChangeAddress("X"))[2];return t.newExportTx(this.provider.getContext(),m,u,h,[a],{threshold:1,changeAddresses:[p]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:d,feeState:o,locktime:i}){const n=this.provider.getChainID(t),a=this.getAddresses("P").map((e=>x(e)[2])),h=x(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const m=x(r)[2],u=e.getUTXOs();if(this.provider.isEtnaEnabled()){if(!o)throw new Error("feeState parameter is required post E-upgrade");return s.e.newImportTx({fromAddressesBytes:a,utxos:u,toAddressesBytes:[m],sourceChainId:n,threshold:d,feeState:o,locktime:i},this.provider.getContext())}return s.newImportTx(this.provider.getContext(),n,u,[m],a,{changeAddresses:[h]})}importX(e,s,r){const d=this.provider.getChainID(s),o=this.getAddresses("X").map((e=>x(e)[2])),i=x(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const n=x(r)[2];return t.newImportTx(this.provider.getContext(),d,e.getUTXOs(),[n],o,{changeAddresses:[i]})}importC(e,t,s,d,o){const i=this.provider.getChainID(t),n=this.getAddresses("C").map((e=>x(e)[2]));o=o||this.getAddressEVM();const a=Buffer.from(h(o),"hex");return r.newImportTxFromBaseFee(this.provider.getContext(),a,n,e.getUTXOs(),i,s,d)}exportC(e,t,s,d,o){const i=f(this.getAddressEVM()),n=this.provider.getChainID(t);o=o||this.getCurrentAddress(t);const a=x(o)[2],h=d/BigInt(1e9);return r.newExportTxFromBaseFee(this.provider.getContext(),h,e,n,i,[a],s)}exportP({amount:t,utxoSet:r,destination:d,feeState:o,toAddress:i}){i=i||this.getCurrentAddress(d);const n=x(i)[2],a=this.provider.getAvaxID(),h=e.fromNative(a,t,[n]),m=g(r.getUTXOs(),!0),u=this.provider.getChainID(d),p=this.getAddresses("P").map((e=>x(e)[2])),A=x(this.getChangeAddress("P"))[2];return this.provider.isEtnaEnabled()?(c(o),s.e.newExportTx({fromAddressesBytes:p,utxos:m,outputs:[h],destinationChainId:u,feeState:o},this.provider.getContext())):s.newExportTx(this.provider.getContext(),u,p,m,[h],{changeAddresses:[A]})}addValidator(e,t,r,d,o,i,n){const a=p(e.getUTXOs()),h=this.getAddresses("P").map((e=>x(e)[2])),m=n?.rewardAddress||this.getCurrentAddress("P"),u=x(m)[2],g=x(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw l;return s.newAddValidatorTx(this.provider.getContext(),a,h,t,d,o,r,[u],i,{changeAddresses:[g]})}addDelegator(e,t,r,d,o,i){const n=p(e.getUTXOs()),a=this.getAddresses("P").map((e=>x(e)[2])),h=i?.rewardAddress||this.getCurrentAddress("P"),m=x(h)[2],u=x(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw l;return s.newAddDelegatorTx(this.provider.getContext(),n,a,t,d,o,r,[m],{changeAddresses:[u]})}consolidateP({utxoSet:t,amount:r,feeState:d,toAddress:o,options:i}){const n=A(t.getUTXOs());o=o??this.getCurrentAddress("P");const a=x(o)[2],h=this.provider.getContext(),m=[e.fromNative(h.avaxAssetID,r,[a])],u=this.getAddresses("P").map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(d),s.e.newBaseTx({fromAddressesBytes:u,utxos:n,outputs:m,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:d},h)):s.newBaseTx(this.provider.getContext(),u,n,m,i)}baseTX({utxoSet:r,chain:d,toAddress:o,amountsPerAsset:i,feeState:n,options:a,fromAddresses:h}){const[m,u,p]=x(o);if(m!==d||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${o}"`);const A=Object.entries(i).map((([t,s])=>e.fromNative(t,s,[p]))),f=g(r.getUTXOs(),!0),l=(h??this.getAddresses(d)).map((e=>x(e)[2]));return"X"===d?t.newBaseTx(this.provider.getContext(),l,f,A,a):this.provider.isEtnaEnabled()?(c(n),s.e.newBaseTx({fromAddressesBytes:l,utxos:f,outputs:A,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext())):s.newBaseTx(this.provider.getContext(),l,f,A,a)}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:a,feeState:h,address:m,validators:u,options:p,fromAddresses:A}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const c=(A??this.getAddresses("P")).map((e=>x(e)[2])),f=u.map((({nodeId:e,pubKey:t,signature:s,balance:r,weight:a,deactivationOwner:h,remainingBalanceOwner:m})=>{const u=new d.ProofOfPossession(Uint8Array.from(o.hexToBuffer(t)),Uint8Array.from(o.hexToBuffer(s))),g=i.fromNative(m.addresses.map((e=>x(e)[2])),m.threshold??1),p=i.fromNative(h.addresses.map((e=>x(e)[2])),h.threshold??1);return n.fromNative(e,a,r,u,g,p)}));return s.e.newConvertSubnetToL1Tx({changeAddressesBytes:p?.changeAddresses??c,validators:f,fromAddressesBytes:c,address:x(m)[2],chainId:t,subnetId:r,subnetAuth:a,feeState:h,utxos:g(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:d,feeState:i,fromAddresses:n,options:a}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const h=(n??this.getAddresses("P")).map((e=>x(e)[2]));return s.e.newRegisterL1ValidatorTx({utxos:g(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(o.hexToBuffer(r)),changeAddressesBytes:a?.changeAddresses??h,feeState:i,fromAddressesBytes:h,memo:a?.memo,message:Uint8Array.from(o.hexToBuffer(d)),minIssuanceTime:a?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:d,fromAddresses:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const n=(i??this.getAddresses("P")).map((e=>x(e)[2]));return s.e.newSetL1ValidatorWeightTx({utxos:g(e.getUTXOs(),!0),changeAddressesBytes:d?.changeAddresses??n,feeState:t,fromAddressesBytes:n,memo:d?.memo,message:Uint8Array.from(o.hexToBuffer(r)),minIssuanceTime:d?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:d,disableAuth:o,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const n=(d??this.getAddresses("P")).map((e=>x(e)[2]));return s.e.newDisableL1ValidatorTx({disableAuth:o,validationId:i,utxos:g(e.getUTXOs(),!0),changeAddressesBytes:r?.changeAddresses??n,feeState:t,fromAddressesBytes:n,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:d,balance:o,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const n=(d??this.getAddresses("P")).map((e=>x(e)[2]));return s.e.newIncreaseL1ValidatorBalanceTx({balance:o,validationId:i,utxos:g(e.getUTXOs(),!0),changeAddressesBytes:r?.changeAddresses??n,feeState:t,fromAddressesBytes:n,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:d,fxIds:o,genesisData:i,subnetAuth:n,feeState:a,options:h,fromAddresses:m}){const u=g(e.getUTXOs(),!0),p=(m??this.getAddresses("P")).map((e=>x(e)[2]));if(this.provider.isEtnaEnabled()){c(a);const e=(m??this.getAddresses("P")).map((e=>x(e)[2])),g=x(this.getChangeAddress("P"))[2];return s.e.newCreateChainTx({chainName:r,feeState:a,fromAddressesBytes:e,fxIds:o,genesisData:i,subnetAuth:n,subnetId:t,utxos:u,vmId:d,changeAddressesBytes:h?.changeAddresses??[g]},this.provider.getContext())}return s.newCreateBlockchainTx(this.provider.getContext(),u,p,t,r,d,o,i,n,h)}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:d,options:o,threshold:i,locktime:n}){const a=g(e.getUTXOs(),!0),h=(d??this.getAddresses("P")).map((e=>x(e)[2])),m=t.map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(r),s.e.newCreateSubnetTx({fromAddressesBytes:h,utxos:a,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,feeState:r,threshold:i,locktime:n,subnetOwners:m},this.provider.getContext())):s.newCreateSubnetTx(this.provider.getContext(),a,h,m,o,i??1,n??BigInt(0))}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:d,weight:o,subnetId:i,subnetAuth:n,feeState:a,fromAddresses:h,options:m}){const u=g(e.getUTXOs(),!0),p=(h??this.getAddresses("P")).map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(a),s.e.newAddSubnetValidatorTx({fromAddressesBytes:p,utxos:u,minIssuanceTime:m?.minIssuanceTime,memo:m?.memo,nodeId:t,start:r,end:d,weight:o,subnetId:i,subnetAuth:n,feeState:a},this.provider.getContext())):s.newAddSubnetValidatorTx(this.provider.getContext(),u,p,t,r,d,o,i,n,m)}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:d,weight:o,subnetId:i,shares:n,feeState:h,fromAddresses:m,rewardAddresses:u,delegatorRewardAddresses:g,publicKey:A,signature:f,options:l,threshold:v,locktime:T,stakingAssetId:b}){const w=p(e.getUTXOs()),I=(m??this.getAddresses("P")).map((e=>x(e)[2])),C=(u??[this.getCurrentAddress("P")]).map((e=>x(e)[2])),S=(g??[this.getCurrentAddress("P")]).map((e=>x(e)[2]));if(!(i!==a.PrimaryNetworkID.toString()||A&&f))throw new Error("Must provide public key and signature for primary subnet.");const E=x(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return c(h),s.e.newAddPermissionlessValidatorTx({fromAddressesBytes:I,delegatorRewardsOwner:S,utxos:w,minIssuanceTime:l?.minIssuanceTime,memo:l?.memo,changeAddressesBytes:l?.changeAddresses?l.changeAddresses:[E],nodeId:t,start:r,end:d,weight:o,subnetId:i,shares:n,feeState:h,publicKey:A,rewardAddresses:C,signature:f,locktime:T,threshold:v,stakingAssetId:b},this.provider.getContext());const P={changeAddresses:[E],...l??{}};return s.newAddPermissionlessValidatorTx(this.provider.getContext(),w,I,t,i,r,d,o,C,S,n,P,void 0,void 0,A,f)}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:d,weight:o,subnetId:i,fromAddresses:n,rewardAddresses:a,options:h,locktime:m,feeState:u,threshold:g,stakingAssetId:A}){const f=p(e.getUTXOs()),l=(n??this.getAddresses("P")).map((e=>x(e)[2])),v=(a??[this.getCurrentAddress("P")]).map((e=>x(e)[2])),T=x(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())return c(u),s.e.newAddPermissionlessDelegatorTx({fromAddressesBytes:l,utxos:f,minIssuanceTime:h?.minIssuanceTime,memo:h?.memo,changeAddressesBytes:h?.changeAddresses?h.changeAddresses:[T],nodeId:t,start:r,end:d,weight:o,subnetId:i,rewardAddresses:v,locktime:m,stakingAssetId:A,threshold:g,feeState:u},this.provider.getContext());const b={changeAddresses:[T],...h??{}};return s.newAddPermissionlessDelegatorTx(this.provider.getContext(),f,l,t,i,r,d,o,v,b,void 0,void 0)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:d,fromAddresses:o,feeState:i,options:n}){const a=g(e.getUTXOs(),!0),h=(o??this.getAddresses("P")).map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(i),s.e.newRemoveSubnetValidatorTx({fromAddressesBytes:h,utxos:a,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,nodeId:t,subnetId:r,subnetAuth:d,feeState:i},this.provider.getContext())):s.newRemoveSubnetValidatorTx(this.provider.getContext(),a,h,t,r,d,n)}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:d,feeState:o,fromAddresses:i,options:n,threshold:a,locktime:h}){const m=g(e.getUTXOs(),!0),u=(i??this.getAddresses("P")).map((e=>x(e)[2])),p=d.map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(o),s.e.newTransferSubnetOwnershipTx({fromAddressesBytes:u,utxos:m,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,subnetId:t,subnetAuth:r,subnetOwners:p,feeState:o,threshold:a,locktime:h},this.provider.getContext())):s.newTransferSubnetOwnershipTx(this.provider.getContext(),m,u,t,r,p,n,a??1,h??BigInt(0))}transformSubnetTx(e,t,r,d,o,i,n,a,h,m,u,p,A,c,f,v,T,b){const w=g(e.getUTXOs(),!0),I=(T??this.getAddresses("P")).map((e=>x(e)[2]));if(this.provider.isEtnaEnabled())throw l;return s.newTransformSubnetTx(this.provider.getContext(),w,I,t,r,d,o,i,n,a,h,m,u,p,A,c,f,v,b)}}export{v as WalletAbstract};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@avalabs/core-wallets-sdk",
|
|
3
|
-
"version": "3.1.0-alpha.
|
|
3
|
+
"version": "3.1.0-alpha.19",
|
|
4
4
|
"license": "Limited Ecosystem License",
|
|
5
5
|
"private": false,
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -30,9 +30,9 @@
|
|
|
30
30
|
"ts-jest": "29.1.2"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@avalabs/avalanchejs": "4.1.0-alpha.
|
|
34
|
-
"@avalabs/core-chains-sdk": "3.1.0-alpha.
|
|
35
|
-
"@avalabs/glacier-sdk": "3.1.0-alpha.
|
|
33
|
+
"@avalabs/avalanchejs": "4.1.0-alpha.25",
|
|
34
|
+
"@avalabs/core-chains-sdk": "3.1.0-alpha.19",
|
|
35
|
+
"@avalabs/glacier-sdk": "3.1.0-alpha.19",
|
|
36
36
|
"@avalabs/hw-app-avalanche": "0.14.1",
|
|
37
37
|
"@ledgerhq/hw-app-btc": "10.2.4",
|
|
38
38
|
"@ledgerhq/hw-app-eth": "6.36.1",
|
|
@@ -52,5 +52,5 @@
|
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"ethers": "^6.7.1"
|
|
54
54
|
},
|
|
55
|
-
"gitHead": "
|
|
55
|
+
"gitHead": "080d04940df50d2d08c27b2a2140d77d16d4b80f"
|
|
56
56
|
}
|