@avalabs/core-wallets-sdk 3.1.0-canary.5b57df61 → 3.1.0-canary.5b6871e3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.ts +210 -94
  4. package/esm/Avalanche/index.d.ts +4 -1
  5. package/esm/Avalanche/index.js +1 -0
  6. package/esm/Avalanche/models.d.ts +15 -11
  7. package/esm/Avalanche/providers/AbstractProvider.d.ts +4 -3
  8. package/esm/Avalanche/utils/digestMessage.d.ts +1 -1
  9. package/esm/Avalanche/utils/getAddressPublicKeyFromXpub.d.ts +1 -1
  10. package/esm/Avalanche/utils/getUtxosByTxFromGlacier.d.ts +2 -1
  11. package/esm/Avalanche/utils/parseAvalancheTx.js +1 -0
  12. package/esm/Avalanche/utils/parsers/parseAddAutoRenewedValidatorTx.js +1 -0
  13. package/esm/Avalanche/utils/parsers/parseAddPermissionlessDelegatorTx.js +1 -0
  14. package/esm/Avalanche/utils/parsers/parseAddPermissionlessValidatorTx.js +1 -0
  15. package/esm/Avalanche/utils/parsers/parseAddSubnetValidorTx.js +1 -0
  16. package/esm/Avalanche/utils/parsers/parseBaseTx.js +1 -0
  17. package/esm/Avalanche/utils/parsers/parseConvertSubnetToL1Tx.js +1 -0
  18. package/esm/Avalanche/utils/parsers/parseCreateChainTx.js +1 -0
  19. package/esm/Avalanche/utils/parsers/parseCreateSubnetTx.js +1 -0
  20. package/esm/Avalanche/utils/parsers/parseDisableL1ValidatorTx.js +1 -0
  21. package/esm/Avalanche/utils/parsers/parseExportTx.js +1 -0
  22. package/esm/Avalanche/utils/parsers/parseImportTx.js +1 -0
  23. package/esm/Avalanche/utils/parsers/parseIncreaseL1ValidatorBalanceTx.js +1 -0
  24. package/esm/Avalanche/utils/parsers/parseRegisterL1ValidatorTx.js +1 -0
  25. package/esm/Avalanche/utils/parsers/parseRemoveSubnetValidatorTx.js +1 -0
  26. package/esm/Avalanche/utils/parsers/parseSetAutoRenewedValidatorConfigTx.js +1 -0
  27. package/esm/Avalanche/utils/parsers/parseSetL1ValidatorWeightTx.js +1 -0
  28. package/esm/Avalanche/utils/parsers/parseTransferSubnetOwnershipTx.js +1 -0
  29. package/esm/Avalanche/utils/parsers/utils/getTxOutputs.js +1 -0
  30. package/esm/Avalanche/utils/sortUTXOs.d.ts +3 -2
  31. package/esm/Avalanche/utils/verifyDerivationPath.js +1 -0
  32. package/esm/Avalanche/utils/withAssetDescriptions.js +1 -0
  33. package/esm/Avalanche/wallets/SimpleSigner.js +1 -0
  34. package/esm/Avalanche/wallets/StaticSigner.d.ts +2 -2
  35. package/esm/Avalanche/wallets/ledger/LedgerLiveSigner.js +1 -0
  36. package/esm/Avalanche/wallets/ledger/LedgerSigner.d.ts +9 -0
  37. package/esm/Avalanche/wallets/ledger/LedgerSigner.js +1 -0
  38. package/esm/Avalanche/wallets/ledger/SimpleLedgerSigner.js +1 -0
  39. package/esm/Avalanche/wallets/ledger/ZondaxProvider.js +1 -0
  40. package/esm/Avalanche/wallets/ledger/constants.js +1 -0
  41. package/esm/Avalanche/wallets/ledger/getLedgerProvider.d.ts +10 -0
  42. package/esm/Avalanche/wallets/ledger/getLedgerProvider.js +1 -0
  43. package/esm/Avalanche/wallets/ledger/isObsidianApp.d.ts +5 -0
  44. package/esm/Avalanche/wallets/ledger/isObsidianApp.js +1 -0
  45. package/esm/Avalanche/wallets/ledger/models.d.ts +37 -0
  46. package/esm/Avalanche/wallets/legacy/LedgerWallet.d.ts +41 -0
  47. package/esm/Avalanche/wallets/legacy/LedgerWallet.js +1 -0
  48. package/esm/Avalanche/wallets/legacy/MnemonicWallet.js +1 -0
  49. package/esm/Avalanche/wallets/legacy/MnemonicWalletVoid.d.ts +3 -3
  50. package/esm/Avalanche/wallets/legacy/MnemonicWalletVoid.js +1 -0
  51. package/esm/Avalanche/wallets/models.d.ts +4 -7
  52. package/esm/BitcoinVM/index.js +1 -0
  53. package/esm/BitcoinVM/models.d.ts +12 -1
  54. package/esm/BitcoinVM/utils/createPSBTV2.d.ts +10 -0
  55. package/esm/BitcoinVM/utils/createPSBTV2.js +1 -0
  56. package/esm/BitcoinVM/utils/createPsbt.d.ts +12 -0
  57. package/esm/BitcoinVM/utils/createPsbt.js +1 -0
  58. package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/createTransferTx.js +1 -1
  59. package/esm/BitcoinVM/utils/createWalletPolicy.d.ts +1 -1
  60. package/esm/BitcoinVM/utils/createWalletPolicy.js +1 -0
  61. package/esm/BitcoinVM/utils/getBech32AddressFromXPub.js +1 -0
  62. package/esm/BitcoinVM/utils/psbt2ToPsbt0.d.ts +15 -0
  63. package/esm/BitcoinVM/utils/psbt2ToPsbt0.js +1 -0
  64. package/esm/BitcoinVM/wallets/BitcoinWallet.d.ts +1 -2
  65. package/esm/BitcoinVM/wallets/BitcoinWallet.js +1 -0
  66. package/esm/BitcoinVM/wallets/BitcoinWalletAbstract.d.ts +5 -6
  67. package/esm/BitcoinVM/wallets/BitcoinWalletAbstract.js +1 -0
  68. package/esm/BitcoinVM/wallets/BitcoinWalletLedger.d.ts +4 -5
  69. package/esm/BitcoinVM/wallets/BitcoinWalletLedger.js +1 -0
  70. package/esm/BitcoinVM/wallets/models.d.ts +1 -1
  71. package/esm/EVM/LedgerSigner.d.ts +10 -10
  72. package/esm/EVM/LedgerSigner.js +1 -0
  73. package/esm/EVM/constants.d.ts +1 -1
  74. package/esm/EVM/utils/blockPolling.d.ts +1 -1
  75. package/esm/EVM/utils/getAddressPrivateKeyFromXPriv.d.ts +1 -1
  76. package/esm/EVM/utils/getAddressPublicKeyFromXPub.d.ts +1 -1
  77. package/esm/EVM/utils/getAppEth.d.ts +10 -0
  78. package/esm/EVM/utils/getAppEth.js +1 -0
  79. package/esm/SolanaVM/utils/compileSolanaTx.d.ts +4 -4
  80. package/esm/SolanaVM/utils/deserializeSolanaTx.d.ts +2 -2
  81. package/esm/SolanaVM/utils/getSolanaPublicKeyFromLedger.d.ts +2 -3
  82. package/esm/SolanaVM/utils/getSolanaPublicKeyFromLedger.js +1 -0
  83. package/esm/SolanaVM/utils/maybeGetAssociatedTokenAccount.d.ts +6 -6
  84. package/esm/SolanaVM/utils/serializeSolanaTx.d.ts +2 -2
  85. package/esm/SolanaVM/utils/solanaProvider.d.ts +3 -4
  86. package/esm/SolanaVM/utils/transferSol.d.ts +3 -4
  87. package/esm/SolanaVM/utils/transferToken.d.ts +3 -4
  88. package/esm/SolanaVM/wallets/SolanaLedgerSigner.d.ts +4 -3
  89. package/esm/SolanaVM/wallets/SolanaLedgerSigner.js +1 -0
  90. package/esm/index.d.ts +5 -2
  91. package/esm/index.js +1 -0
  92. package/esm/utils/getAddressDerivationPath.js +1 -0
  93. package/esm/utils/getLedgerAppInfo.d.ts +2 -2
  94. package/esm/utils/getLedgerAppInfo.js +1 -0
  95. package/esm/utils/getLedgerExtendedPublicKey.d.ts +2 -2
  96. package/esm/utils/getLedgerExtendedPublicKey.js +1 -0
  97. package/esm/utils/getPubKeyFromTransport.d.ts +2 -2
  98. package/esm/utils/getPubKeyFromTransport.js +1 -0
  99. package/esm/utils/getPublicKeyFromPrivateKey.d.ts +1 -1
  100. package/esm/utils/openLedgerApp.d.ts +2 -2
  101. package/esm/utils/openLedgerApp.js +1 -0
  102. package/esm/utils/quitLedgerApp.d.ts +2 -3
  103. package/esm/utils/quitLedgerApp.js +1 -0
  104. package/package.json +13 -17
  105. package/esm/BitcoinVM/utils/createPSBT.d.ts +0 -9
  106. package/esm/packages/wallets-sdk/src/Avalanche/index.js +0 -1
  107. package/esm/packages/wallets-sdk/src/Avalanche/utils/parseAvalancheTx.js +0 -1
  108. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseAddAutoRenewedValidatorTx.js +0 -1
  109. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseAddPermissionlessDelegatorTx.js +0 -1
  110. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseAddPermissionlessValidatorTx.js +0 -1
  111. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseAddSubnetValidorTx.js +0 -1
  112. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseBaseTx.js +0 -1
  113. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseConvertSubnetToL1Tx.js +0 -1
  114. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseCreateChainTx.js +0 -1
  115. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseCreateSubnetTx.js +0 -1
  116. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseDisableL1ValidatorTx.js +0 -1
  117. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseExportTx.js +0 -1
  118. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseImportTx.js +0 -1
  119. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseIncreaseL1ValidatorBalanceTx.js +0 -1
  120. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseRegisterL1ValidatorTx.js +0 -1
  121. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseRemoveSubnetValidatorTx.js +0 -1
  122. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseSetAutoRenewedValidatorConfigTx.js +0 -1
  123. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseSetL1ValidatorWeightTx.js +0 -1
  124. package/esm/packages/wallets-sdk/src/Avalanche/utils/parsers/parseTransferSubnetOwnershipTx.js +0 -1
  125. package/esm/packages/wallets-sdk/src/Avalanche/utils/verifyDerivationPath.js +0 -1
  126. package/esm/packages/wallets-sdk/src/Avalanche/wallets/SimpleSigner.js +0 -1
  127. package/esm/packages/wallets-sdk/src/Avalanche/wallets/ledger/LedgerLiveSigner.js +0 -1
  128. package/esm/packages/wallets-sdk/src/Avalanche/wallets/ledger/LedgerSigner.js +0 -1
  129. package/esm/packages/wallets-sdk/src/Avalanche/wallets/ledger/SimpleLedgerSigner.js +0 -1
  130. package/esm/packages/wallets-sdk/src/Avalanche/wallets/ledger/utils/dmkToLedgerTransport.js +0 -1
  131. package/esm/packages/wallets-sdk/src/Avalanche/wallets/legacy/MnemonicWallet.js +0 -1
  132. package/esm/packages/wallets-sdk/src/Avalanche/wallets/legacy/MnemonicWalletVoid.js +0 -1
  133. package/esm/packages/wallets-sdk/src/BitcoinVM/index.js +0 -1
  134. package/esm/packages/wallets-sdk/src/BitcoinVM/utils/createPSBT.js +0 -1
  135. package/esm/packages/wallets-sdk/src/BitcoinVM/utils/createWalletPolicy.js +0 -1
  136. package/esm/packages/wallets-sdk/src/BitcoinVM/utils/ecPair.js +0 -1
  137. package/esm/packages/wallets-sdk/src/BitcoinVM/utils/getBech32AddressFromXPub.js +0 -1
  138. package/esm/packages/wallets-sdk/src/BitcoinVM/wallets/BitcoinWallet.js +0 -1
  139. package/esm/packages/wallets-sdk/src/BitcoinVM/wallets/BitcoinWalletAbstract.js +0 -1
  140. package/esm/packages/wallets-sdk/src/BitcoinVM/wallets/BitcoinWalletLedger.js +0 -1
  141. package/esm/packages/wallets-sdk/src/EVM/LedgerSigner.js +0 -1
  142. package/esm/packages/wallets-sdk/src/SolanaVM/utils/getSolanaPublicKeyFromLedger.js +0 -1
  143. package/esm/packages/wallets-sdk/src/SolanaVM/wallets/SolanaLedgerSigner.js +0 -1
  144. package/esm/packages/wallets-sdk/src/index.js +0 -1
  145. package/esm/packages/wallets-sdk/src/utils/getAddressDerivationPath.js +0 -1
  146. package/esm/packages/wallets-sdk/src/utils/getLedgerAppInfo.js +0 -1
  147. package/esm/packages/wallets-sdk/src/utils/getLedgerExtendedPublicKey.js +0 -1
  148. package/esm/packages/wallets-sdk/src/utils/getPubKeyFromTransport.js +0 -1
  149. package/esm/packages/wallets-sdk/src/utils/openLedgerApp.js +0 -1
  150. package/esm/packages/wallets-sdk/src/utils/quitLedgerApp.js +0 -1
  151. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/models.js +0 -0
  152. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/providers/AbstractProvider.js +0 -0
  153. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/providers/JsonRpcProvider.js +0 -0
  154. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/providers/constants.js +0 -0
  155. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/providers/platformFeeConfig.js +0 -0
  156. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/addSignaturesToAvalancheTx.js +0 -0
  157. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/appendAutoRenewedValidatorConfigAddressMaps.js +0 -0
  158. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/appendDisableAuthAddressMaps.js +0 -0
  159. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/convertGlacierUtxo.js +0 -0
  160. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/createAvalancheEvmUnsignedTx.js +0 -0
  161. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/createAvalancheUnsignedTx.js +0 -0
  162. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/digestMessage.js +0 -0
  163. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getAddressFromXpub.js +0 -0
  164. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getAddressPublicKeyFromXpub.js +0 -0
  165. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getAllUTXOs.js +0 -0
  166. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getAssetBalance.js +0 -0
  167. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getAvalancheDerivationPath.js +0 -0
  168. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getChainAliasByChainId.js +0 -0
  169. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getPchainUnixNow.js +0 -0
  170. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getStakeForAddresses.js +0 -0
  171. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getStakedAssetBalance.js +0 -0
  172. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getTxOutputAddresses.js +0 -0
  173. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getUnixNow.js +0 -0
  174. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getUtxosByTxFromGlacier.js +0 -0
  175. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getVmByChainAlias.js +0 -0
  176. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/getXpubFromMnemonic.js +0 -0
  177. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/handleSubnetAuth.js +0 -0
  178. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/isBech32Address.js +0 -0
  179. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/orderBy.js +0 -0
  180. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/parsers/index.js +0 -0
  181. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/parsers/utils/chainIdToVm.js +0 -0
  182. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/parsers/utils/getTransferableAmount.js +0 -0
  183. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/populateCredential.js +0 -0
  184. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/signedTxToHex.js +0 -0
  185. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/sortUTXOs.js +0 -0
  186. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/utils/txSizeLimits.js +0 -0
  187. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/wallets/AddressWallet.js +0 -0
  188. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/wallets/StaticSigner.js +0 -0
  189. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/wallets/WalletAbstract.js +0 -0
  190. /package/esm/{packages/wallets-sdk/src/Avalanche → Avalanche}/wallets/WalletVoid.js +0 -0
  191. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/providers/BitcoinProvider.js +0 -0
  192. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/providers/BitcoinProviderAbstract.js +0 -0
  193. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/providers/models.js +0 -0
  194. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/providers/utils/parseAddressFullTx.js +0 -0
  195. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/addEncodedSigToPsbt.js +0 -0
  196. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/filterDuplicateUTXOs.js +0 -0
  197. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/formatAddressForNetworkBech32.js +0 -0
  198. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/getBech32Address.js +0 -0
  199. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/getMaxTransferAmount.js +0 -0
  200. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/getTransferTxDetails.js +0 -0
  201. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/selectUtxos.js +0 -0
  202. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/utils/sumUTXOs.js +0 -0
  203. /package/esm/{packages/wallets-sdk/src/BitcoinVM → BitcoinVM}/wallets/BitcoinWalletVoid.js +0 -0
  204. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/constants.js +0 -0
  205. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/blockPolling.js +0 -0
  206. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getAddressFromXPub.js +0 -0
  207. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getAddressPrivateKeyFromXPriv.js +0 -0
  208. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getAddressPublicKeyFromXPub.js +0 -0
  209. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getBtcAddressFromPubKey.js +0 -0
  210. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getEvmAddressFromPubKey.js +0 -0
  211. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getEvmDerivationPath.js +0 -0
  212. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getVoidSigner.js +0 -0
  213. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getWalletFromMnemonic.js +0 -0
  214. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/getXpubFromMnemonic.js +0 -0
  215. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/jsonRpcBatchProvider.js +0 -0
  216. /package/esm/{packages/wallets-sdk/src/EVM → EVM}/utils/multicallABI.js +0 -0
  217. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/compileSolanaTx.js +0 -0
  218. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/derivationPath.js +0 -0
  219. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/deserializeSolanaTx.js +0 -0
  220. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/maybeGetAssociatedTokenAccount.js +0 -0
  221. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/resolveTokenProgramForMint.js +0 -0
  222. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/serializeSolanaTx.js +0 -0
  223. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/solanaProvider.js +0 -0
  224. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/transferSol.js +0 -0
  225. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/utils/transferToken.js +0 -0
  226. /package/esm/{packages/wallets-sdk/src/SolanaVM → SolanaVM}/wallets/SolanaSigner.js +0 -0
  227. /package/esm/{packages/wallets-sdk/src/abis → abis}/erc20.abi.js +0 -0
  228. /package/esm/{packages/wallets-sdk/src/utils → utils}/assertFeeStateProvided.js +0 -0
  229. /package/esm/{packages/wallets-sdk/src/utils → utils}/binarySearch.js +0 -0
  230. /package/esm/{packages/wallets-sdk/src/utils → utils}/getPublicKeyFromPrivateKey.js +0 -0
  231. /package/esm/{packages/wallets-sdk/src/utils → utils}/omitUndefinedKeys.js +0 -0
package/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [3.1.0-alpha.99](https://github.com/ava-labs/avalanche-sdks/compare/v3.1.0-alpha.98...v3.1.0-alpha.99) (2026-09-28)
7
+
8
+ **Note:** Version bump only for package @avalabs/core-wallets-sdk
9
+
10
+ # [3.1.0-alpha.98](https://github.com/ava-labs/avalanche-sdks/compare/v3.1.0-alpha.97...v3.1.0-alpha.98) (2026-09-17)
11
+
12
+ **Note:** Version bump only for package @avalabs/core-wallets-sdk
13
+
6
14
  # [3.1.0-alpha.97](https://github.com/ava-labs/avalanche-sdks/compare/v3.1.0-alpha.96...v3.1.0-alpha.97) (2026-08-31)
7
15
 
8
16
  ### Bug Fixes
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("ethers"),n=require("bip32"),i=require("bip39"),a=require("@metamask/eth-sig-util"),o=require("@avalabs/hw-app-avalanche"),d=require("@ledgerhq/device-management-kit"),u=require("@ledgerhq/device-signer-kit-ethereum"),c=require("@ledgerhq/device-signer-kit-bitcoin"),l=require("@bitcoinerlab/secp256k1"),p=require("ecpair"),h=require("@avalabs/avalanchejs"),g=require("@noble/hashes/sha256"),m=require("@avalabs/glacier-sdk"),f=require("@avalabs/core-chains-sdk"),x=require("create-hash"),v=require("xss"),y=require("bip32-path"),w=require("@solana/kit"),A=require("@solana-program/system"),b=require("@solana-program/token"),T=require("@solana-program/token-2022"),S=require("@ledgerhq/device-signer-kit-solana"),I=require("@scure/base"),P=require("@noble/curves/ed25519"),B=require("micro-key-producer/slip10.js"),k=require("hdkey"),C=require("buffer");function E(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var D=E(l);function M(e){return e.reduce(((e,t)=>e+t.value),0)}class V{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:M(r.confirmed),balanceUnconfirmed:M(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function O(t,r,s,n,i,a){const o=new e.Psbt({network:s});return o.version=2,t.forEach((e=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.addInput({hash:Buffer.from(e.txHash,"hex").reverse(),index:e.index,nonWitnessUtxo:Buffer.from(e.txHex,"hex"),witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value},...n&&i&&a?{bip32Derivation:[{pubkey:i,masterFingerprint:n,path:a}]}:{}})})),r.forEach((e=>{o.addOutput({address:e.address,value:e.value})})),o}function _(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 U(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function K(e,t,r,s,n,i){const a=_(e,t,r,s,U(n));return a.inputs?{...a,psbt:O(a.inputs,a.outputs,i)}:(console.log("Unable to construct transaction, fee needed: ",a.fee),a)}function N(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}const R="m/44'/60'",L=`${R}/0'`;var F=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(F||{});const X=(e,t,r=!0)=>{switch(t){case F.BIP44:return`${r?"m/":""}44'/60'/0'/0/${e}`;case F.LedgerLive:return`${r?"m/":""}44'/60'/${e}'/0/0`;default:throw new Error("Invalid path spec")}};var H=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];const $=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),q=(e,t)=>{const r=new s.Interface(H).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 j=[{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 W extends s.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#e="string"==typeof t?new s.FetchRequest(t):void 0===t?new s.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 s.JsonRpcProvider(this.#e,r,{staticNetwork:r}),this._multicallContract=new s.Contract(e.multiContractAddress,j,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 z(e,t){return n.fromBase58(e).derivePath(`0/${t}`).publicKey}function J(e,t){return{async send(r,s,n,i,a=Buffer.alloc(0),o=[36864]){const d=new Uint8Array(5+a.length);d.set([r,s,n,i,a.length]),d.set(a,5);const u=await e.sendApdu({sessionId:t,apdu:d}),c=u.statusCode[0]<<8|u.statusCode[1];if(!o.includes(c))throw Object.assign(new Error(`Ledger device: status 0x${c.toString(16)}`),{name:"TransportStatusError",statusCode:c});return Buffer.concat([u.data,u.statusCode])}}}var Y=function(e,t){return Y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Y(e,t)};function G(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Y(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Q(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],s=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Z(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var s,n,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=i.next()).done;)a.push(s.value)}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a}function ee(e,t,r){if(2===arguments.length)for(var s,n=0,i=t.length;n<i;n++)!s&&n in t||(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))}function te(e){return"function"==typeof e}function re(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var se=re((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function ne(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var ie=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,s,n;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=Q(i),o=a.next();!o.done;o=a.next()){o.value.remove(this)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var d=this.initialTeardown;if(te(d))try{d()}catch(e){n=e instanceof se?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var c=Q(u),l=c.next();!l.done;l=c.next()){var p=l.value;try{ae(p)}catch(e){n=null!=n?n:[],e instanceof se?n=ee(ee([],Z(n)),Z(e.errors)):n.push(e)}}}catch(e){r={error:e}}finally{try{l&&!l.done&&(s=c.return)&&s.call(c)}finally{if(r)throw r.error}}}if(n)throw new se(n)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)ae(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ne(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&ne(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function ae(e){te(e)?e():e.unsubscribe()}ie.EMPTY;var oe={setTimeout:function(e,t){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];return setTimeout.apply(void 0,ee([e,t],Z(r)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function de(){}var ue=function(e){function t(t){var r,s=e.call(this)||this;return s.isStopped=!1,t?(s.destination=t,((r=t)instanceof ie||r&&"closed"in r&&te(r.remove)&&te(r.add)&&te(r.unsubscribe))&&t.add(s)):s.destination=he,s}return G(t,e),t.create=function(e,t,r){return new le(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(ie),ce=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){pe(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){pe(e)}else pe(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){pe(e)}},e}(),le=function(e){function t(t,r,s){var n,i=e.call(this)||this;return n=te(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=s?s:void 0}:t,i.destination=new ce(n),i}return G(t,e),t}(ue);function pe(e){var t;t=e,oe.setTimeout((function(){throw t}))}var he={closed:!0,next:de,error:function(e){throw e},complete:de},ge=re((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function me(e,t){return new Promise((function(t,r){var s=new le({next:function(e){t(e),s.unsubscribe()},error:r,complete:function(){r(new ge)}});e.subscribe(s)}))}let fe=class e extends s.AbstractSigner{constructor(e=0,t,r,n,i){super(),this.accountIndex=e,this.dmk=t,this.sessionId=r,this.derivationSpec=n,this.provider=i,this.path=X(this.accountIndex,this.derivationSpec),this.accountIndex=e,this.app=new o(J(this.dmk,this.sessionId),{dmk:this.dmk,sessionId:this.sessionId}),s.defineProperties(this,{path:this.path,type:"default",provider:i||null})}type="default";path;app;async getAddress(){const e=await this.app.getETHAddress(this.path);return s.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=s.toUtf8Bytes(e));const t=new u.SignerEthBuilder({dmk:this.dmk,sessionId:this.sessionId}).build(),{observable:r}=t.signMessage(this.path,s.hexlify(e)),n=await me(r);if(n.status!==d.DeviceActionStatus.Completed)throw new Error("Failed to sign message");return s.Signature.from(n.output).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=s.Transaction.from(t),n=r.unsignedSerialized,i=await this.app.signEVMTransaction(this.path,n.slice(2));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.dmk,this.sessionId,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:n,...i}=t,d=s.TypedDataEncoder.getPrimaryType(i);try{const n=await this.app.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:d,message:r});return n.r="0x"+n.r,n.s="0x"+n.s,s.Signature.from(n).serialized}catch(n){if(n instanceof o.DeviceActionError&&n.statusCode===o.LedgerError.InstructionNotSupported){const n=a.TypedDataUtils.hashStruct(d,r,t,a.SignTypedDataVersion.V4),i=a.TypedDataUtils.hashStruct("EIP712Domain",e,t,a.SignTypedDataVersion.V4),o=await this.app.signEIP712HashedMessage(this.path,i.toString("hex"),n.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,s.Signature.from(o).serialized}throw n}}};const xe=p.ECPairFactory(D);function ve(e,t,r){return xe.fromPublicKey(e).verify(t,r)}class ye{constructor(e,t){this.pubkey=e,this.provider=t;try{this.ecPair=xe.fromPublicKey(e)}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 N(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 K(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}var we=(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.AddAutoRenewedValidator="add_auto_renewed_validator",e.SetAutoRenewedValidatorConfig="set_auto_renewed_validator_config",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))(we||{});const Ae=e=>{switch(e){case"C":return h.EVM;case"X":return h.AVM;case"P":return h.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:be,AddressMaps:Te}=h.utils,Se=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const i=be(e);let a=Te.fromTransferableInputs(i,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>h.pvmSerial.isCreateChainTx(e)||h.pvmSerial.isAddSubnetValidatorTx(e)||h.pvmSerial.isRemoveSubnetValidatorTx(e)||h.pvmSerial.isTransformSubnetTx(e)||h.pvmSerial.isTransferSubnetOwnershipTx(e)||h.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=h.OutputOwners.fromNative(n.controlKeys.map((e=>h.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 h.utils.AddressMap(i)),r})({tx:e,provider:r,addressMaps:a});return new h.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else h.pvmSerial.isDisableL1ValidatorTx(e)?a=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),i=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new h.utils.AddressMap(i)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(a,e,r):h.pvmSerial.isSetAutoRenewedValidatorConfigTx(e)&&(a=await async function(e,t,r){try{const s=(await r.getApiP().getTx({txID:t.txId.value()})).unsignedTx;if(!h.pvmSerial.isAddAutoRenewedValidatorTx(s))throw new Error("Referenced validator transaction is not an AddAutoRenewedValidatorTx");const n=s.getValidatorAuthority().addrs,i=t.getAuth().values(),a=n.reduce(((e,t,r)=>(i.includes(r)&&e.push([t,r]),e)),[]);return e.push(new h.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing auto-renewed validator config auth data: ${e.message}`)}}(a,e,r));return new h.UnsignedTx(e,n,a,s)},{bufferToHex:Ie,packTx:Pe}=h.utils,{publicKeyBytesToAddress:Be,recoverPublicKey:ke}=h.secp256k1,Ce=new h.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(Ce);if(!t)return s;const{unsignedTx:n,credentialIndex:i}=t,a=n.getCredentials()[i];if(!a)return s;const o=Pe(n.getTx()),d=g.sha256(o),u=Ce.toString();for(const e of a.toJSON()){if(e.toString()===u)continue;const t=ke(d,e.toBytes()),r={toHex:()=>Ie(Be(t))},a=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of a)t[0]===i&&(s[t[1]]=e)}return s};function De(e){return h.utils.bufferToHex(h.utils.addChecksum(e.toBytes()))}const{getManagerForVM:Me,hexToBuffer:Ve,unpackWithManager:Oe}=h.utils,_e=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=Ae(t);if(n===h.EVM)throw new Error("EVM transactions are not supported");const i=Ve(e),a=Oe(n,i),o=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const i=Me(s).unpack(t,h.avaxSerial.SignedTx),a=await Se({tx:e,utxos:n,provider:r,credentials:i.getCredentials()});return e.getSigIndices().map(((e,t)=>new h.Credential(Ee(e,{unsignedTx:a,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new h.Credential(Ee(e))))}})({tx:a,txBytes:i,provider:r,vm:n,utxos:s});return Se({tx:a,provider:r,credentials:o,utxos:s})},{parseBech32:Ue,format:Ke}=h.utils,{publicKeyBytesToAddress:Ne}=h.secp256k1;class Re{constructor(e,t,r){this.baseUrl=e,this.context=t,this.fetchOptions=r}getContext(){return this.context}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 h.networkIDs.getHRP(this.getNetworkID())}getApiX(){const e=new h.avm.AVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiP(){const e=new h.pvm.PVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiC(){const e=new h.evm.EVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getInfo(){const e=new h.info.InfoApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}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 n=t.strip0x(s.SigningKey.computePublicKey(e,!0)),i=Buffer.from(n,"hex"),a=Ne(i);return Ke(r,this.getHrp(),a)}getAddressFromBuffer(e,t){return Ke(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=Ue(e);return Ke(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=De(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 a=async()=>{let o;switch(r&&n+r<Date.now()&&i(new Error("Timeout")),o=s instanceof h.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),o.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{a()}),1e3)}};a()}))}}const Le={weights:h.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)},Fe={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:Le},Xe={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:Le},He={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:Le};class $e extends Re{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await h.Context.getContextFromURI(e);try{return new $e(e,t)}catch{return new $e(e,t)}}static getDefaultMainnetProvider(e){return new $e(f.AVALANCHE_XP_NETWORK.rpcUrl,Fe,e)}static getDefaultFujiProvider(e){return new $e(f.AVALANCHE_XP_TEST_NETWORK.rpcUrl,Xe,e)}static getDefaultDevnetProvider(e){return new $e(f.AVALANCHE_XP_DEVNET_NETWORK.rpcUrl,He,e)}}const{bytesCompare:qe,parseBech32:je}=h.utils,We=(e,t)=>"P"===t,ze=(e,t,r)=>{const s=We(0,t)?e.amount:e.asset?.amount;return new h.TransferOutput(new h.BigIntPr(BigInt(s)),h.OutputOwners.fromNative(e.addresses.map((e=>je(e)[1])).sort(qe),BigInt(r??0),e.threshold))},Je=(e,t)=>{const r=((e,t)=>{const r=t===m.Network.FUJI,{cBlockchainID:s,xBlockchainID:n,pBlockchainID:i}=r?Xe:Fe;if(s===e)return"C";if(n===e)return"X";if(i===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=We(0,r)?e.txHash:e.creationTxHash,n=We(0,r)?e.assetId:e.asset?.assetId;return new h.Utxo(h.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),h.Id.fromString(n),((e,t)=>We(0,t)?e.stakeableLocktime?new h.pvmSerial.StakeableLockOut(new h.BigIntPr(BigInt(e.stakeableLocktime??0)),ze(e,t,e.platformLocktime??0)):ze(e,t,e.platformLocktime):ze(e,t,e.locktime))(e,r))},{unpackWithManager:Ye,parse:Ge,bufferToHex:Qe,AddressMaps:Ze,AddressMap:et}=h.utils;function tt(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 x("sha256").update(s).digest()}const rt=1024,st=1024;async function nt(e,t,r){const s=e.slice(0,rt),n=e.slice(rt),i=await it(t,{...r,addresses:s});if(n.length){const s=await nt(n,t,{...r,addresses:e});return i.merge(s)}return i}async function it(e,t){if(t.addresses.length>rt)throw new Error(`Can not get UTXOs for more than ${rt} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new h.utils.UtxoSet(s);if(s.length>=st){const s=await it(e,{...t,startIndex:r});return n.merge(s)}return n}function at(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:ot}=h.utils;async function dt(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await dt(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:ut,hexToBuffer:ct,unpackWithManager:lt}=h.utils;function pt(e,t=!0){try{if(t){const[t]=h.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else h.utils.parseBech32(e);return!0}catch(e){return!1}}const ht=e=>{if([Fe.xBlockchainID,Xe.xBlockchainID,He.xBlockchainID].includes(e))return"AVM";if([Fe.pBlockchainID,Xe.pBlockchainID,He.pBlockchainID].includes(e))return"PVM";if([Fe.cBlockchainID,Xe.cBlockchainID,He.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},gt=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),mt=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0));var ft={parseCreateSubnetTx:e=>h.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:we.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>h.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:we.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=>h.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:we.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=>h.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:we.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>h.pvmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.evmSerial.isImportTx(e)?h.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:we.Import,chain:e.getVM(),source:ht(e.sourceChain.value()),amount:mt(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:we.Import,chain:e.getVM(),source:ht(e.sourceChain.value()),amount:mt(e.ins,r),...t}):null,parseExportTx:e=>h.pvmSerial.isExportTx(e)||h.avmSerial.isExportTx(e)||h.evmSerial.isExportTx(e)?h.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:we.Export,chain:e.getVM(),destination:ht(e.destinationChain.toString()),amount:gt(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:we.Export,chain:e.getVM(),destination:ht(e.destination.value()),amount:gt(e.outs,r),...t}):null,parseBaseTx:e=>h.avmSerial.isAvmBaseTx(e)||h.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())})),h.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 h.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 h.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),a=at(),o=i.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=a)));return{type:we.Base,chain:e.getVM(),outputs:o,memo:v(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!h.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return h.pvmSerial.isSigner(e.signer)&&(r=h.utils.bufferToHex(e.signer.proof.publicKey),t=h.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:we.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=>h.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:we.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,parseTransferSubnetOwnershipTx:e=>h.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:we.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=>h.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:we.ConvertSubnetToL1,chain:e.getVM(),managerAddress:`0x${e.address.toString("hex")}`,validators:e.validators.map((e=>({nodeId:h.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=>h.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:we.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>h.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:we.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>h.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:we.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>h.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:we.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null,parseAddAutoRenewedValidatorTx:e=>{if(!h.pvmSerial.isAddAutoRenewedValidatorTx(e))return null;let t,r;h.pvmSerial.isSigner(e.signer)&&(r=h.utils.bufferToHex(e.signer.proof.publicKey),t=h.utils.bufferToHex(e.signer.proof.signature));const s=e.stake.reduce(((e,t)=>e+t.amount()),0n);return({feeData:n})=>({type:we.AddAutoRenewedValidator,chain:e.getVM(),nodeID:e.nodeId.value(),stake:s,stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),owner:e.getValidatorAuthority(),delegationFee:e.delegationShares.value(),autoCompoundRewardShares:e.autoCompoundRewardShares.value(),period:e.period.value(),signer:e.signer,publicKey:r,signature:t,...n})},parseSetAutoRenewedValidatorConfigTx:e=>h.pvmSerial.isSetAutoRenewedValidatorConfigTx(e)?({feeData:t})=>({type:we.SetAutoRenewedValidatorConfig,chain:e.getVM(),txId:e.txId.value(),autoCompoundRewardShares:e.autoCompoundRewardShares.value(),period:e.period.value(),...t}):null};const{getBurnedAmountByTx:xt,getOutputAmounts:vt,getInputAmounts:yt,validateBurnedAmount:wt}=h.utils;function At(e,t,r){return[...e].sort(((e,s)=>{for(let n=0;n<t.length;n++){const i=t[n];if(e[i]>s[i])return"asc"===r?1:-1;if(e[i]<s[i])return"asc"===r?-1:1}return 0}))}function bt(e){const t=at(),r=e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),i=At(s,["amount"],"desc"),a=At(n,["stakeableLocktime","amount"],"desc"),[o,...d]=i;return[...o?[o]:[],...a,...d].map((e=>e.utxo))}function Tt(e,t){return At(e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const St=e=>Tt(e,!0),It=e=>Tt(e,!1);const{getUtxoInfo:Pt}=h.utils;var Bt=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Bt||{});const kt="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",Ct="11111111111111111111111111111111LpoYY",Et=(e,t)=>e.reduce(((e,t)=>e+Pt(t).amount),BigInt(0))-t,Dt={BaseP:{sortFunction:St,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new h.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:Et(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:It,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new h.utils.UtxoSet(t),amount:Et(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:bt,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new h.utils.UtxoSet(t),nodeId:kt,start:at(),end:at()+BigInt(1e3),weight:Et(t,e.getProvider().getContext().baseTxFee),subnetId:Ct,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(h.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(h.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:bt,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new h.utils.UtxoSet(t),nodeId:kt,start:at(),end:at()+BigInt(1e3),weight:Et(t,e.getProvider().getContext().baseTxFee),subnetId:Ct,feeState:r})},ExportP:{sortFunction:St,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext(),n=function({numberIns:e=1},t){const r=h.Common.createDimensions({bandwidth:161*e+254,dbRead:e,dbWrite:2+e,compute:200*e});return h.Common.dimensionsToGas(r,t)}({numberIns:t.length},s.platformFeeConfig.weights),i=r?n*r.price:s.baseTxFee;return e.exportP({amount:Et(t,i),utxoSet:new h.utils.UtxoSet(t),destination:"X",feeState:r})}},ImportP:{sortFunction:St,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new h.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function Mt(e){return y.validateString(e,!0)&&6===e.split("/").length}const Vt=(e,t=!0)=>`${t?"m/":""}44'/9000'/${e}'/0/0`;function Ot(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:_t,hexToBuffer:Ut}=h.utils;class Kt{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return nt(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return dt(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 nt(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=_t(s)[2],i=this.provider.getAvaxID(),a=h.TransferableOutput.fromNative(i,e,[n]),o=Tt(t.getUTXOs(),!0),d=this.provider.getChainID(r),u=this.getAddresses("X").map((e=>_t(e)[2])),c=_t(this.getChangeAddress("X"))[2];return h.avm.newExportTx(this.provider.getContext(),d,u,o,[a],{threshold:1,changeAddresses:[c]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:i}){const a=this.provider.getChainID(t),o=this.getAddresses("P").map((e=>_t(e)[2]));_t(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const d=_t(r)[2],u=e.getUTXOs();return Ot(n),h.pvm.newImportTx({fromAddressesBytes:o,utxos:u,toAddressesBytes:[d],sourceChainId:a,threshold:s,feeState:n,locktime:i},this.provider.getContext())}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>_t(e)[2])),i=_t(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const a=_t(r)[2];return h.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[a],n,{changeAddresses:[i]})}importC(e,r,s,n,i){const a=this.provider.getChainID(r),o=this.getAddresses("C").map((e=>_t(e)[2]));i=i||this.getAddressEVM();const d=Buffer.from(t.strip0x(i),"hex");return h.evm.newImportTxFromBaseFee(this.provider.getContext(),d,o,e.getUTXOs(),a,s,n)}exportC(e,t,r,s,n){const i=Ut(this.getAddressEVM()),a=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=_t(n)[2],d=s/BigInt(1e9);return h.evm.newExportTxFromBaseFee(this.provider.getContext(),d,e,a,i,[o],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const i=_t(n)[2],a=this.provider.getAvaxID(),o=h.TransferableOutput.fromNative(a,e,[i]),d=Tt(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>_t(e)[2])),l=_t(this.getChangeAddress("P"))[2];return Ot(s),h.pvm.newExportTx({changeAddressesBytes:[l],fromAddressesBytes:c,utxos:d,outputs:[o],destinationChainId:u,feeState:s},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const i=It(e.getUTXOs());s=s??this.getCurrentAddress("P");const a=_t(s)[2],o=this.provider.getContext(),d=[h.TransferableOutput.fromNative(o.avaxAssetID,t,[a])],u=this.getAddresses("P").map((e=>_t(e)[2])),c=_t(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c];return Ot(r),h.pvm.newBaseTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:i,outputs:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},o)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:i,fromAddresses:a}){const[o,d,u]=_t(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>h.TransferableOutput.fromNative(e,t,[u]))),l=Tt(e.getUTXOs(),!0),p=(a??this.getAddresses(t)).map((e=>_t(e)[2])),g=_t(this.getChangeAddress("P"))[2],m=i?.changeAddresses??[g];return"X"===t?h.avm.newBaseTx(this.provider.getContext(),p,l,c,i):(Ot(n),h.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:p,utxos:l,outputs:c,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:i,validators:a,options:o,fromAddresses:d}){const u=(d??this.getAddresses("P")).map((e=>_t(e)[2])),c=_t(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c],p=a.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:i,remainingBalanceOwner:a})=>{const o=new h.pvmSerial.ProofOfPossession(Uint8Array.from(h.utils.hexToBuffer(t)),Uint8Array.from(h.utils.hexToBuffer(r))),d=h.PChainOwner.fromNative(a.addresses.map((e=>_t(e)[2])),a.threshold??1),u=h.PChainOwner.fromNative(i.addresses.map((e=>_t(e)[2])),i.threshold??1);return h.L1Validator.fromNative(e,n,s,o,d,u)}));return h.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:p,fromAddressesBytes:u,address:_t(i)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:Tt(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:i,options:a}){const o=(i??this.getAddresses("P")).map((e=>_t(e)[2])),d=_t(this.getChangeAddress("P"))[2],u=a?.changeAddresses??[d];return h.pvm.newRegisterL1ValidatorTx({utxos:Tt(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(h.utils.hexToBuffer(r)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:a?.memo,message:Uint8Array.from(h.utils.hexToBuffer(s)),minIssuanceTime:a?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){const i=(n??this.getAddresses("P")).map((e=>_t(e)[2])),a=_t(this.getChangeAddress("P"))[2],o=s?.changeAddresses??[a];return h.pvm.newSetL1ValidatorWeightTx({utxos:Tt(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:i,memo:s?.memo,message:Uint8Array.from(h.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:i}){const a=(s??this.getAddresses("P")).map((e=>_t(e)[2])),o=_t(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return h.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:i,utxos:Tt(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:a,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:i}){const a=(s??this.getAddresses("P")).map((e=>_t(e)[2])),o=_t(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return h.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:i,utxos:Tt(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:a,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}addAutoRenewedValidator({utxoSet:e,nodeId:t,weight:r,shares:s,feeState:n,fromAddresses:i,rewardAddresses:a,delegatorRewardAddresses:o,ownerAddresses:d,publicKey:u,signature:c,autoCompoundRewardShares:l,period:p,options:g,locktime:m,threshold:f}){const x=bt(e.getUTXOs()),v=(i??this.getAddresses("P")).map((e=>_t(e)[2])),y=(a??[this.getCurrentAddress("P")]).map((e=>_t(e)[2])),w=(o??[this.getCurrentAddress("P")]).map((e=>_t(e)[2])),A=(d??[this.getCurrentAddress("P")]).map((e=>_t(e)[2])),b=_t(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[b];return h.pvm.newAddAutoRenewedValidatorTx({fromAddressesBytes:v,delegatorRewardsOwner:w,utxos:x,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,weight:r,shares:s,feeState:n,publicKey:u,rewardAddresses:y,signature:c,locktime:m,threshold:f,ownerAddresses:A,autoCompoundRewardShares:l,period:p},this.provider.getContext())}setAutoRenewedValidatorConfig({utxoSet:e,feeState:t,validatorTxId:r,auth:s,autoCompoundRewardShares:n,period:i,fromAddresses:a,options:o}){const d=(a??this.getAddresses("P")).map((e=>_t(e)[2])),u=_t(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[u];return h.pvm.newSetAutoRenewedValidatorConfigTx({utxos:Tt(e.getUTXOs(),!0),changeAddressesBytes:c,feeState:t,fromAddressesBytes:d,memo:o?.memo,minIssuanceTime:o?.minIssuanceTime,validatorTxId:r,auth:s,autoCompoundRewardShares:n,period:i},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:i,subnetAuth:a,feeState:o,options:d,fromAddresses:u}){const c=Tt(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>_t(e)[2])),p=_t(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[p];return Ot(o),h.pvm.newCreateChainTx({chainName:r,feeState:o,fromAddressesBytes:l,fxIds:n,genesisData:i,subnetAuth:a,subnetId:t,utxos:c,vmId:s,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:i,locktime:a}){const o=Tt(e.getUTXOs(),!0),d=(s??this.getAddresses("P")).map((e=>_t(e)[2])),u=_t(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],l=t.map((e=>_t(e)[2]));return Ot(r),h.pvm.newCreateSubnetTx({fromAddressesBytes:d,changeAddressesBytes:c,utxos:o,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:i,locktime:a,subnetOwners:l},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:a,feeState:o,fromAddresses:d,options:u}){const c=Tt(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>_t(e)[2])),p=_t(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[p];return Ot(o),h.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:l,utxos:c,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:a,feeState:o},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:a,feeState:o,fromAddresses:d,rewardAddresses:u,delegatorRewardAddresses:c,publicKey:l,signature:p,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=bt(e.getUTXOs()),y=(d??this.getAddresses("P")).map((e=>_t(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>_t(e)[2])),A=(c??[this.getCurrentAddress("P")]).map((e=>_t(e)[2]));if(!(i!==h.networkIDs.PrimaryNetworkID.toString()||l&&p))throw new Error("Must provide public key and signature for primary subnet.");const b=_t(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[b];return Ot(o),h.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:y,delegatorRewardsOwner:A,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:a,feeState:o,publicKey:l,rewardAddresses:w,signature:p,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,fromAddresses:a,rewardAddresses:o,options:d,locktime:u,feeState:c,threshold:l,stakingAssetId:p,additionalOutputs:g}){const m=bt(e.getUTXOs()),f=(a??this.getAddresses("P")).map((e=>_t(e)[2])),x=(o??[this.getCurrentAddress("P")]).map((e=>_t(e)[2])),v=_t(this.getChangeAddress("P"))[2],y=d?.changeAddresses??[v],w=this.provider.getContext();return Ot(c),h.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:f,utxos:m,minIssuanceTime:d?.minIssuanceTime,memo:d?.memo,changeAddressesBytes:y,nodeId:t,start:r,end:s,weight:n,subnetId:i,rewardAddresses:x,locktime:u,stakingAssetId:p,threshold:l,feeState:c,additionalOutputs:g?.map((e=>h.TransferableOutput.fromNative(e.assetId??w.avaxAssetID,e.amount,e.addresses.map((e=>_t(e)[2])),e.locktime,e.threshold)))},w)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:i,options:a}){const o=Tt(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>_t(e)[2])),u=_t(this.getChangeAddress("P"))[2],c=a?.changeAddresses??[u];return Ot(i),h.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:c,fromAddressesBytes:d,utxos:o,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:i},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:i,options:a,threshold:o,locktime:d}){const u=Tt(e.getUTXOs(),!0),c=(i??this.getAddresses("P")).map((e=>_t(e)[2])),l=_t(this.getChangeAddress("P"))[2],p=a?.changeAddresses??[l],g=s.map((e=>_t(e)[2]));return Ot(n),h.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:p,fromAddressesBytes:c,utxos:u,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:o,locktime:d},this.provider.getContext())}}class Nt extends Kt{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,n){const i=t.strip0x(s.SigningKey.computePublicKey(e,!0)),a=t.strip0x(s.SigningKey.computePublicKey(r,!0)),o=Buffer.from(i,"hex"),d=Buffer.from(a,"hex");return new Nt(o,d,n)}static fromMnemonic(e,t,r,s){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!Mt(r)||!Mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const a=i.mnemonicToSeedSync(e),o=n.fromSeed(a),d=o.derivePath(r),u=o.derivePath(t);return Nt.fromPublicKey(u.publicKey,d.publicKey,s)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return s.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{parse:Rt}=h.utils;class Lt extends Kt{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=n.fromBase58(e),this.evmWallet=new Nt(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=i.mnemonicToSeedSync(e),s=n.fromSeed(r),a=s.derivePath("m/44'/9000'/0'").neutered(),o=s.derivePath(X(0,F.BIP44)).neutered();return new Lt(a.toBase58(),o.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(Rt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(Rt(e)[2])))}getRawAddressC(){return Buffer.from(Rt(this.getCurrentAddress("C"))[2])}}const{strip0x:Ft}=h.utils;class Xt extends Lt{constructor(e,t,r){const i=n.fromBase58(e).neutered(),a=new s.SigningKey(t),o=Buffer.from(Ft(a.compressedPublicKey),"hex");super(i.toBase58(),o,r),this.evmPrivKey=t,this.accountNode=n.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=i.mnemonicToSeedSync(e),s=n.fromSeed(r),a=s.derivePath("m/44'/9000'/0'"),o=s.derivePath(ur(0,"EVM",{pathSpec:F.BIP44}));if(!o.privateKey)throw new Error("Unable to derive EVM private key.");return new Xt(a.toBase58(),o.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await h.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;return"EVM"===t.getVM()?[this.evmPrivKey]:[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Ht,sign:$t,signHash:qt}=h.secp256k1,{addChecksum:jt}=h.utils;class Wt extends Nt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(Ht(e)),Buffer.from(Ht(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!Mt(r)||!Mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const a=i.mnemonicToSeedSync(e),o=n.fromSeed(a),d=o.derivePath(t),u=o.derivePath(r);if(!d.privateKey||!u.privateKey)throw new Error("Failed to generate private keys.");return new Wt(d.privateKey,u.privateKey,s)}async signMessage(e){const t=tt(e.message),r=this.getSigningKey(e.chain);return Buffer.from(jt(await qt(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await $t(e.buffer,t))]}}const{isTransferOut:zt,isStakeableLockOut:Jt}=h.utils;function Yt(e){const t=e.output;return zt(t)||Jt(t)?t.getOwners():[]}function Gt(e){const t=e.getTx();return h.avmSerial.isExportTx(t)||h.pvmSerial.isExportTx(t)?new Set(t.outs.map(Yt).flat()):h.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(Yt).flat()):new Set((t.baseTx?.outputs??[]).map(Yt).flat())}const{parse:Qt}=h.utils;const Zt={C:60,X:9e3,P:9e3};var er=Object.freeze({__proto__:null,AbstractProvider:Re,AddressWallet:class extends Kt{constructor(e,t,r,n,i){if(super(i),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=r,this.xpChangeAddress=n,r.length<1)throw new Error("Must have at least 1 xp address.");if(!s.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(r.some((e=>!pt(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!pt(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(n)}setChangeAddress(e){if(!pt(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:Xe,JsonRpcProvider:$e,LedgerLiveSigner:class{constructor(e){this.accountIndices=e}#r(e){return`m/44'/${Zt[e]}'`}#s(e,t){return`${this.#r(e)}/${t}'`}async signMessage(e){if(!e.dmk||!e.sessionId||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a message.");const t=y.fromString(this.#s(e.chain,this.accountIndices[0])),r=y.fromString("0/0"),s=tt(e.message),n=new o(J(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId}),i=await n.signHash(t.toString(),[r].map((e=>e.toString(!0))),s),a=i.signatures?.get(r.toString(!0));if(!a)throw new Error("Failed to sign message.");return a}async signTx(e){if(!e.dmk||!e.sessionId)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"AVM"===r?"X":"P",i=new Set(e.externalIndices??this.accountIndices);for(const r of i){const i=y.fromString(this.#s(n,r));(await this.#n(i,{buffer:s,chain:n,dmk:e.dmk,sessionId:e.sessionId})).forEach((e=>{t.addSignature(new Uint8Array(e))}))}return t}async#n(e,t){if(!t.dmk||!t.sessionId)throw new Error("Ledger transport not provided");const r=new o(J(t.dmk,t.sessionId),{dmk:t.dmk,sessionId:t.sessionId});return[...((await r.sign(e.toString(),(t.signers??[y.fromString("0/0")]).map((e=>e.toString(!0))),t.buffer,(t.change??[y.fromString("0/0")]).map((e=>e.toString(!0))))).signatures??new Map).values()]}async signTxBuffer(e){if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a tx buffer.");const t=y.fromString(this.#s(e.chain,this.accountIndices[0]));return this.#n(t,e)}},LedgerSigner:class extends Nt{constructor(e,t,r,n,i){const a=h.utils.strip0x(s.SigningKey.computePublicKey(new Uint8Array(e),!0)),o=h.utils.strip0x(s.SigningKey.computePublicKey(new Uint8Array(r),!0));if(super(Buffer.from(a,"hex"),Buffer.from(o,"hex"),i),this.pathXP=t,this.pathC=n,!Mt(t)||!Mt(n))throw new Error("Invalid path configuration.")}async signMessage(e){if(!e.dmk||!e.sessionId||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=y.fromString(this.getAccountPath(e.chain)),r=y.fromString(this.getPartialSignerPath(e.chain)),s=tt(e.message),n=new o(J(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId}),i=await n.signHash(t.toString(),[r].map((e=>e.toString(!0))),s),a=i.signatures?.get(r.toString(!0));if(!a)throw new Error("Failed to sign message.");return a}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.dmk||!e.sessionId)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,dmk:e.dmk,sessionId:e.sessionId})).forEach((e=>{t.addSignature(new Uint8Array(e))})),t}async signTxBuffer(e){if(!e.dmk||!e.sessionId)throw new Error("Ledger transport not provided");const t=y.fromString(this.getAccountPath(e.chain)),r=y.fromString(this.getPartialSignerPath(e.chain)),s=new o(J(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId});return[...((await s.sign(t.toString(),[r].map((e=>e.toString(!0))),e.buffer,[r].map((e=>e.toString(!0))))).signatures??new Map).values()]}},MainnetContext:Fe,MnemonicWallet:Xt,MnemonicWalletVoid:Lt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r,s=F.BIP44){this.activeAccountIndex=e,this.provider=t,this.pathSpec=s,r&&(this.accountNode=n.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof h.EVMUnsignedTx||"C"===t?h.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):h.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'/${this.activeAccountIndex}'`;case"C":return`m/44'/60'/${this.pathSpec===F.LedgerLive?this.activeAccountIndex: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(Qt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),i="EVM"===e.tx.getVM()?`0/${this.pathSpec===F.LedgerLive?0:this.activeAccountIndex}`:"0/0",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,r){return 0===t.size?[y.fromString("C"===r?`0/${this.pathSpec===F.LedgerLive?0:this.activeAccountIndex}`:"0/0")]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(y.fromString(s)),e}),[])}async signTx(e){if(!e.dmk||!e.sessionId)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,t),a=this.getAddressBipPaths([...Gt(r)],n,t);return(await this.signTxBuffer({buffer:s,chain:t,dmk:e.dmk,sessionId:e.sessionId,signers:i,change:a})).forEach((e=>{r.addSignature(new Uint8Array(e))})),r}async signTxBuffer(e){if(!e.dmk||!e.sessionId)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=y.fromString(this.getAccountPath(e.chain)),s=new o(J(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId});return[...((await s.sign(r.toString(),e.signers.map((e=>e.toString(!0))),e.buffer,t.map((e=>e.toString(!0))))).signatures??new Map).values()]}async signMessage(e){if(!e.dmk||!e.sessionId||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t="C"===e.chain?this.activeAccountIndex:0,r=e.signer||y.fromString(`0/${t}`);if(2!=r.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const s=tt(e.message),n=new o(J(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId}),i=await n.signHash(this.getAccountPath(e.chain),[r].map((e=>e.toString(!0))),s),a=i.signatures?.get(r.toString(!0));if(!a)throw new Error("Failed to sign message.");return a}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=i.mnemonicToSeedSync(e),s=n.fromSeed(r);this.accountNodeXP=s.derivePath(`m/44'/9000'/${t}'`);const a=s.derivePath(ur(t,"EVM",{pathSpec:F.BIP44}));this.signerNodeEVM=a,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/0");if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1),i=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...i]}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 h.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/0");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=tt(e.message),s=await h.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Bt,StaticSigner:Wt,TxType:we,WalletAbstract:Kt,WalletVoid:Nt,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 _e({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>i.addSignature(e))));const a=i.getCredentials(),o=i.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=a[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new h.Credential(s)),e}),[]),d=new h.UnsignedTx(i.getTx(),i.getInputUtxos(),i.addressMaps,o);return{signedTxHex:De(new h.avaxSerial.SignedTx(i.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:Je,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,credentials:s,utxos:n})=>{const i=Ye(r,e),a=Ge(t)[2],o=Qe(a);if(h.evmSerial.isExportTx(i))return new h.EVMUnsignedTx(i,[],new Ze([et.fromJSON([[o,0]])]),s);if(h.evmSerial.isImportTx(i)){const e=Ze.fromTransferableInputs(i.importedInputs,n,BigInt(Math.floor((new Date).getTime()/1e3)),[a]);return new h.UnsignedTx(i,n,e,s)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:Se,digestMessage:tt,emptySignature:Ce,getAddressFromXpub:function(e,t,r,s,i=!1){if(t<0)throw new Error("Account index must be >= 0");const a=i?"1":"0",o=n.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(o,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return n.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=at();return n.forEach((e=>{const t=ot(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},getAvalancheDerivationPath:Vt,getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:i,unsignedTxBuilder:a}=Dt[r],o=at(),d=i(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=Pt(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*Pt(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(Pt)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:it,getPchainUnixNow:async function(e){const t=await e.getApiP().getTimestamp(),r=new Date(t.timestamp),s=Math.floor(r.getTime()/1e3);return BigInt(s)},getStakeForAddresses:dt,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[h.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:nt,getUnixNow:at,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:i})=>{const a=Ae(t),o=ct(e),d=lt(a,o);if(h.evmSerial.isExportTx(d))return[];const u=(e=>{if(h.evmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case h.EVM:return m.BlockchainId.C_CHAIN;case h.AVM:return m.BlockchainId.X_CHAIN;case h.PVM:return m.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=ut(d),l=new m.Glacier({BASE:s,TOKEN:n,HEADERS:i}),p=[...new Set(c.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(p.map((e=>l.primaryNetworkTransactions.getTxByHash({blockchainId:u,network:r,txHash:e}))));return c.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=Je(n,r);return e.push(i),e}),[])},getVmByChainAlias:Ae,getXpubFromMnemonic:function(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=i.mnemonicToSeedSync(e);return n.fromSeed(r).derivePath(`44'/9000'/${t}'`).neutered().toBase58()},isAddAutoRenewedValidatorTx:function(e){return"add_auto_renewed_validator"===e.type},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:pt,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},isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetAutoRenewedValidatorConfigTx:function(e){return"set_auto_renewed_validator_config"===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,baseFee:n}={}){const i=t.getContext(),a=e.getTx(),o=(e=>{for(const t of Object.values(ft)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(a),d=xt(a,i),u=vt(a),c=yt(a).get(i.avaxAssetID)??BigInt(0),l=d.get(i.avaxAssetID)??BigInt(0),p=u.get(i.avaxAssetID)??BigInt(0);let g=n;void 0===g&&(g=0n,h.evmSerial.isImportExportTx(a)?(g=await t.getApiC().getBaseFee()/BigInt(1e9),0n===g&&(g=1n)):"PVM"===a.vm&&(g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0)))));const{isValid:m,txFee:f}=wt({unsignedTx:e,context:i,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f,baseFee:g},assetId:i.avaxAssetID,provider:t,currentAddress:r})},populateCredential:Ee,signedTxToHex:De,sortUTXOsByAmount:Tt,sortUTXOsByAmountAscending:It,sortUTXOsByAmountDescending:St,sortUTXOsStaking:bt,verifyDerivationPath:Mt});const tr=(e,t)=>{const r=w.getTransactionDecoder().decode(w.getBase64Encoder().encode(e)),s=w.getCompiledTransactionMessageDecoder().decode(r.messageBytes);return w.decompileTransactionMessageFetchingLookupTables(s,t)},rr=Symbol(),sr=({isTestnet:e,rpcUrl:t})=>{const r=w.createSolanaRpc(e?w.devnet(t):w.mainnet(t));return new Proxy(r,{get:(e,t,r)=>t===rr||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,r))})},nr=(e,t)=>String(e)===String(t),ir=async({mint:e,provider:t})=>{const r=w.address(e),{value:s}=await t.getAccountInfo(r,{encoding:"base64"}).send();if(!s)throw new Error(`Mint account not found: ${e}`);const n=s.owner;if(nr(n,b.TOKEN_PROGRAM_ADDRESS))return b.TOKEN_PROGRAM_ADDRESS;if(nr(n,T.TOKEN_2022_PROGRAM_ADDRESS))return T.TOKEN_2022_PROGRAM_ADDRESS;throw new Error(`Unsupported token program for mint ${e}: ${String(n)}`)},ar=async({mint:e,owner:t,provider:r,tokenProgram:s})=>{const n=s??await ir({mint:e,provider:r}),[i]=await b.findAssociatedTokenPda({mint:w.address(e),owner:w.address(t),tokenProgram:n}),a=await r.getAccountInfo(i,{encoding:"base64"}).send();return{address:i,exists:Boolean(a.value),info:a}},or=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class dr{#i;#a;constructor(e){this.#i=Uint8Array.from(e),this.#a=w.address(I.base58.encode(P.ed25519.getPublicKey(this.#i)))}static fromMnemonic(e,t){const r=i.mnemonicToSeedSync(e),s=B.fromMasterSeed(Uint8Array.from(r)).derive(`m/44'/501'/${t}'/0'`);return new dr(Buffer.from(s.privateKey))}#o(e){try{return w.getCompiledTransactionMessageDecoder().decode(e),!0}catch{return!1}}async signMessage(e){const t=I.base64.decode(e);if(this.#o(t))throw new Error("Cannot use signMessage() to sign transactions!");return I.base64.encode(P.ed25519.sign(t,this.#i))}async signTx(e,t){const r=await tr(e,t),{signatures:s,messageBytes:n,...i}=w.compileTransaction(r);if(!this.#d(s))return e;const a=I.base58.encode(P.ed25519.sign(Uint8Array.from(n),this.#i));return w.assertIsSignature(a),w.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...s,[this.#a]:I.base58.decode(a)}})}#d(e){return this.#a in e&&!e[this.#a]}}function ur(e,t,r={withRoot:!0}){if(e<0)throw new Error("Account index can not be less than 0.");switch(t){case"EVM":if(!r.pathSpec)throw new Error("Path spec is required for EVM: either BIP44 or Ledger Live");return X(e,r.pathSpec,r.withRoot);case"AVM":case"PVM":return Vt(e,r.withRoot);case"SVM":return or(e,r.withRoot);default:throw new Error(`Unknown derivation path for VM: ${t}`)}}class cr extends ye{keypair;constructor(e,t){const r=xe.fromPrivateKey(e);super(r.publicKey,t),this.keypair=r}static async fromMnemonic(e,t,r,s=F.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const a=await i.mnemonicToSeed(e),o=n.fromSeed(a),d=ur(t,"EVM",{pathSpec:s}),u=o.derivePath(d);if(!u.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new cr(u.privateKey,r)}signTx(e,t){const r=O(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 cr(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(ve),e.finalizeAllInputs(),e.extractTransaction()}}const lr=e.networks;exports.Avalanche=er,exports.BitcoinLedgerWallet=class extends ye{constructor(e,t,r,s,n,i){super(e,r),this.derivationPath=t,this.dmk=s,this.sessionId=n,this.walletPolicyDetails=i}setTransport(e,t){this.dmk=e,this.sessionId=t}async signTx(e,t){const r=(s=this.dmk,n=this.sessionId,new c.SignerBtcBuilder({dmk:s,sessionId:n}).build());var s,n;const i=this.ecPair.publicKey,a=this.provider.getNetwork(),o=await r.getMasterFingerprint(),u=await me(o.observable);if(u.status!==d.DeviceActionStatus.Completed)throw new Error("Failed to get master fingerprint");const l=O(e,t,a,Buffer.from(u.output.masterFingerprint),i,this.derivationPath),p=await r.signPsbt(new c.RegisteredWallet(this.walletPolicyDetails.policy.name,this.walletPolicyDetails.policy.descriptorTemplate,[...this.walletPolicyDetails.policy.keys],this.walletPolicyDetails.hmac),l),h=await me(p.observable);if(h.status!==d.DeviceActionStatus.Completed)throw new Error("Failed to get signatures");if(h.output.forEach((e=>{"signature"in e&&l.updateInput(e.inputIndex,{partialSig:[{signature:Buffer.from(e.signature),pubkey:Buffer.from(e.pubkey)}]})})),!l.validateSignaturesOfAllInputs(ve))throw new Error("Failed to validate signatures");return l.finalizeAllInputs(),l.extractTransaction()}},exports.BitcoinProvider=class extends V{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.#u=new t.HttpClient(s||o,a);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#c=new t.HttpClient(n||d,a)}#u;#c;async#l(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#c.post("",e,{},this.extraParams))))).flat():this.#c.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#u.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,r){const s=await this.#u.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!s?.length)return{confirmed:[],unconfirmed:[]};const n=s.map(this._parseUtxo),i=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return i(n);return i(await this.getScriptsForUtxos(n,r))}async getAddressFromScript(e){const t=await this.#c.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,t){const[r,s]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),n=s.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),i=n.length?(await this.#l(n,t)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...r,...s.map(((e,t)=>({...e,script:i[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.#u.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.#c.post("",{jsonrpc:"2.0",id:"nownodes",method:"getblockcount",params:[]},{},this.extraParams)).result}async getFeeRates(e){const t={jsonrpc:"2.0",method:"estimatesmartfee"},r=await this.#l([{...t,id:"1",params:[1]},{...t,id:"2",params:[3]},{...t,id:"3",params:[6]}],e).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(r[0]/1024)||1,medium:Math.ceil(r[1]/1024)||1,low:Math.ceil(r[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#c.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#u.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.#u.post(`/api/v2/address/${e}`,{},{},this.extraParams),r=t.txids?.slice(0,25)??[];return await Promise.allSettled(r.map((async t=>{try{const r=await this.#u.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=V,exports.BitcoinWallet=cr,exports.BitcoinWalletAbstract=ye,exports.BitcoinWalletVoid=class extends ye{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=lr,exports.DerivationPath=F,exports.ETH_ACCOUNT_PATH=L,exports.ETH_COIN_PATH=R,exports.JsonRpcBatchInternal=W,exports.LedgerSigner=fe,exports.SolanaLedgerSigner=class{#p;#h;#g;constructor(e,t,r){this.#p=or(e,!1),this.#h=t,this.#g=r}async signTx(e,t,r){const s=await tr(e,sr({rpcUrl:t,isTestnet:r})),{signatures:n,messageBytes:i,...a}=w.compileTransaction(s),o=new S.SignerSolanaBuilder({dmk:this.#h,sessionId:this.#g,solanaRPCURL:t}).build(),{observable:u}=await o.getAddress(this.#p),c=await me(u);if(c.status!==d.DeviceActionStatus.Completed)throw new Error("Failed to get address");const l=w.address(I.base58.encode(Uint8Array.from(c.output)));if(!this.#d(l,n))return e;const p=await o.signTransaction(this.#p,Buffer.from(i)),h=await me(p.observable);if(h.status!==d.DeviceActionStatus.Completed)throw new Error("Failed to sign transaction");const g=I.base58.encode(Uint8Array.from(h.output));return w.assertIsSignature(g),w.getBase64EncodedWireTransaction({...a,messageBytes:i,signatures:{...n,[l]:I.base58.decode(g)}})}#d(e,t){return e in t&&!t[e]}},exports.SolanaSigner=dr,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.compileSolanaTx=e=>w.compileTransaction(e),exports.createPSBT=O,exports.createTransferTx=K,exports.createWalletPolicy=function(e,t,r,s){return new c.WalletPolicy(s,"wpkh(@0/**)",[`[${e}/44'/60'/${t}']${r}`])},exports.deserializeTransactionMessage=tr,exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=ur,exports.getAddressFromXPub=function(e,t){const r=z(e,t);return s.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=n.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=z,exports.getBech32Address=N,exports.getBech32AddressFromXPub=function(e,t,r){return N(z(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const n=t.strip0x(s.SigningKey.computePublicKey(e,!0));return N(Buffer.from(n,"hex"),r)},exports.getEVMDerivationPath=X,exports.getEvmAddressFromPubKey=function(e){return s.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e,t){const r=await e.sendApdu({sessionId:t,apdu:new Uint8Array([176,1,0,0])}),s=Buffer.from(r.data),n=s.readUInt8(1),i=s.readUInt8(2+n),a=s.subarray(2,2+n),o=s.subarray(2+n+1,2+n+1+i);return{applicationName:a.toString("ascii"),version:o.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t,r=!1,s){const n=new o(J(e,t),{dmk:e,sessionId:t}),i=await n.getETHAddress(s??L,r,!0),a=new k;return a.publicKey=C.Buffer.from(i.publicKey,"hex"),a.chainCode=C.Buffer.from(i.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=M(e);if(!n)return 0;const{fee:i}=_(t,r,n,s,e);return n-i},exports.getPubKeyFromTransport=async function(e,t,r,s,n="EVM"){const i=new o(J(e,t),{dmk:e,sessionId:t}),a="EVM"===n?ur(r,n,{pathSpec:s}):ur(r,n),d=await i.getETHAddress(a,!1,!1);return Buffer.from(d.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(h.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaDerivationPath=or,exports.getSolanaProvider=sr,exports.getSolanaPublicKeyFromLedger=async(e,t,r,s)=>{const n=new S.SignerSolanaBuilder({dmk:t,sessionId:r,solanaRPCURL:s}).build(),{observable:i}=await n.getAddress(or(e,!1)),a=await me(i);if(a.status!==d.DeviceActionStatus.Completed)throw new Error("Failed to get address");return w.address(I.base58.encode(Uint8Array.from(a.output)))},exports.getTransferTxDetails=function(e,t,r,s,n){const i=_(e,t,r,s,U(n));return i.inputs||console.log("Unable to construct transaction, fee needed: ",i.fee),i},exports.getVoidSigner=function(e,t){return new s.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 s.HDNodeWallet.fromMnemonic(s.Mnemonic.fromPhrase(e),X(t,r))},exports.getXpubFromMnemonic=async function(e){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await i.mnemonicToSeed(e);return n.fromSeed(t).derivePath(L).neutered().toBase58()},exports.isERC20Transfer=q,exports.isNativeTxn=$,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[rr],exports.maybeGetAssociatedTokenAccount=ar,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())&&q(e,n)?s(e,{type:"erc20",contractAddress:e.to}):$(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",a);return{unsubscribe:()=>o.off("block",a)}},exports.openLedgerApp=async function(e,t,r){try{const s=await e.sendApdu({sessionId:t,apdu:new Uint8Array([224,216,0,0,...Buffer.from(r,"ascii")])});return Buffer.from(s.data).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.quitLedgerApp=async function(e,t){return e.sendApdu({sessionId:t,apdu:new Uint8Array([176,167,0,0])})},exports.resolveTokenProgramForMint=ir,exports.selectUtxos=_,exports.serializeSolanaTx=e=>w.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:r,provider:s})=>{const{value:n}=await s.getLatestBlockhash().send(),i=[A.getTransferSolInstruction({source:w.createNoopSigner(w.address(e)),destination:w.address(t),amount:r})];return w.pipe(w.createTransactionMessage({version:0}),(e=>w.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>w.setTransactionMessageFeePayer(w.address(e),t)),(e=>w.appendTransactionMessageInstructions(i,e)))},exports.transferToken=async({from:e,to:t,mint:r,amount:s,decimals:n,provider:i})=>{const a=await ir({mint:r,provider:i}),o=String(a)===String(T.TOKEN_2022_PROGRAM_ADDRESS);const{address:d}=await ar({mint:r,owner:e,provider:i,tokenProgram:a}),{address:u,exists:c}=await ar({mint:r,owner:t,provider:i,tokenProgram:a}),l=[];c||l.push(o?T.getCreateAssociatedTokenIdempotentInstruction({payer:w.createNoopSigner(w.address(e)),mint:w.address(r),owner:w.address(t),ata:u,tokenProgram:T.TOKEN_2022_PROGRAM_ADDRESS}):b.getCreateAssociatedTokenIdempotentInstruction({payer:w.createNoopSigner(w.address(e)),mint:w.address(r),owner:w.address(t),ata:u})),l.push(o?T.getTransferCheckedInstruction({amount:s,authority:w.createNoopSigner(w.address(e)),decimals:n,mint:w.address(r),destination:u,source:d}):b.getTransferCheckedInstruction({amount:s,authority:w.createNoopSigner(w.address(e)),decimals:n,mint:w.address(r),destination:u,source:d}));const{value:p}=await i.getLatestBlockhash().send();return w.pipe(w.createTransactionMessage({version:0}),(e=>w.setTransactionMessageLifetimeUsingBlockhash(p,e)),(t=>w.setTransactionMessageFeePayer(w.address(e),t)),(e=>w.appendTransactionMessageInstructions(l,e)))};
1
+ "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),s=require("coinselect"),r=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("bip32"),i=require("bip39"),o=require("@ledgerhq/hw-transport"),d=require("@metamask/eth-sig-util"),u=require("ledger-bitcoin"),c=require("@ledgerhq/hw-app-btc/lib/bip32"),l=require("@avalabs/avalanchejs"),p=require("@noble/hashes/sha256"),h=require("@avalabs/glacier-sdk"),g=require("@avalabs/core-chains-sdk"),m=require("create-hash"),f=require("xss"),x=require("bip32-path"),v=require("@avalabs/hw-app-avalanche"),w=require("hdkey"),y=require("@solana/kit"),A=require("@solana-program/system"),b=require("@solana-program/token"),T=require("@solana-program/token-2022"),S=require("@ledgerhq/hw-app-solana"),I=require("@noble/curves/ed25519"),P=require("@scure/base"),B=require("micro-key-producer/slip10.js"),C=require("buffer");function k(e){return e.reduce(((e,t)=>e+t.value),0)}class E{async getUtxoBalance(e,t=!0){const s=await this.getUTXOs(e,t);return{balance:k(s.confirmed),balanceUnconfirmed:k(s.unconfirmed),utxos:s.confirmed,utxosUnconfirmed:s.unconfirmed}}}function V(t,s,r){const n=new e.Psbt({network:r});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),s.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function M(e,t,r,n,a){const i=[{address:e,value:r}],{inputs:o,outputs:d,fee:u}=s(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 D(e){const t=[];return e.filter((e=>{const s=e.txHash+e.index.toString();return!t.includes(s)&&(t.push(s),!0)}))}function O(e,t,s,r,n,a){const i=M(e,t,s,r,D(n));return i.inputs?{...i,psbt:V(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function K(t,s){return e.payments.p2wpkh({pubkey:t,network:s}).address}function U(e){return new r(e,"w0w")}const _="m/44'/60'",N=`${_}/0'`;var L=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(L||{});const R=(e,t,s=!0)=>{switch(t){case L.BIP44:return`${s?"m/":""}44'/60'/0'/0/${e}`;case L.LedgerLive:return`${s?"m/":""}44'/60'/${e}'/0/0`;default:throw new Error("Invalid path spec")}};var X=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];const F=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),H=(e,t)=>{const s=new n.Interface(X).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===s?.name)return t.has(s.args[0]?.toLowerCase());if("transferFrom"===s?.name){const e=t.has(s.args[0]?.toLowerCase()),r=t.has(s.args[1]?.toLowerCase());return e||r}return!1};var $=[{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 q extends n.JsonRpcProvider{url;constructor(e,t,s){super(t,s,{staticNetwork:s}),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,s,{staticNetwork:s}),this._multicallContract=new n.Contract(e.multiContractAddress,$,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 s={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const r={request:s,resolve:null,reject:null},n=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return this._pendingBatch.push(r),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,s)=>{const r=t[s];if(r.error){const t=new Error(r.error.message);t.code=r.error.code,t.data=r.error.data,e.reject(t)}else e.resolve(r.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 s=this.#e.clone();s.body=t;return(await s.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 W(e,t){return a.fromBase58(e).derivePath(`0/${t}`).publicKey}let j=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,s,r){super(),this.path=R(e,s),this.accountIndex=e,this.transport=t,this.derivationSpec=s,this._eth=U(t),n.defineProperties(this,{path:this.path,type:"default",provider:r??null})}setTransport(e){this._eth=U(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),s=await this._eth.signPersonalMessage(this.path,t);return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const s=n.Transaction.from(t),r=s.unsignedSerialized,a=await this._eth.signTransaction(this.path,r.slice(2),null);return s.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},s.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,s){const{EIP712Domain:r,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const r=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:s});return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}catch(r){if(r instanceof o.TransportStatusError&&r.statusCode===o.StatusCodes.INS_NOT_SUPPORTED){const r=d.TypedDataUtils.hashStruct(i,s,t,d.SignTypedDataVersion.V4),a=d.TypedDataUtils.hashStruct("EIP712Domain",e,t,d.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),r.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw r}}};function G(t,s,r,n,a,i){const o=new u.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(s.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,c.pathStringToArray(i))})),s.forEach(((t,s)=>{const n=e.address.toOutputScript(t.address,r);o.setOutputAmount(s,t.value),o.setOutputScript(s,n)})),o}function J(t,s,r,n){const a=new e.Psbt({network:s}),i=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<i;e++){const s=t.getInputWitnessUtxo(e),i=t.getInputBip32Derivation(e,r);a.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:s?{value:s.amount,script:s.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:i?[{path:n,pubkey:r,masterFingerprint:i.masterFingerprint}]:void 0})}for(let r=0;r<o;r++)a.addOutput({value:t.getOutputAmount(r),address:e.address.fromOutputScript(t.getOutputScript(r),s)});return a}class z{constructor(t,s){this.pubkey=t,this.provider=s;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 K(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,s,r){return O(e,this.getAddressBech32(),t,s,r,this.provider.getNetwork())}}var Y=(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.AddAutoRenewedValidator="add_auto_renewed_validator",e.SetAutoRenewedValidatorConfig="set_auto_renewed_validator_config",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))(Y||{});const Q=e=>{switch(e){case"C":return l.EVM;case"X":return l.AVM;case"P":return l.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:Z,AddressMaps:ee}=l.utils,te=async({tx:e,fromAddressBytes:t,provider:s,credentials:r,utxos:n})=>{const a=Z(e);let i=ee.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>l.pvmSerial.isCreateChainTx(e)||l.pvmSerial.isAddSubnetValidatorTx(e)||l.pvmSerial.isRemoveSubnetValidatorTx(e)||l.pvmSerial.isTransformSubnetTx(e)||l.pvmSerial.isTransferSubnetOwnershipTx(e)||l.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:s})=>{const r=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),a=l.OutputOwners.fromNative(n.controlKeys.map((e=>l.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,s)=>(r.includes(s)&&e.push([t,s]),e)),[]);return s.push(new l.utils.AddressMap(a)),s})({tx:e,provider:s,addressMaps:i});return new l.UnsignedTx(e,n,t,r)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else l.pvmSerial.isDisableL1ValidatorTx(e)?i=await async function(e,t,s){try{const{deactivationOwner:r}=await s.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),a=r.addresses.reduce(((e,t,s)=>(n.includes(s)&&e.push([t,s]),e)),[]);return e.push(new l.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(i,e,s):l.pvmSerial.isSetAutoRenewedValidatorConfigTx(e)&&(i=await async function(e,t,s){try{const r=(await s.getApiP().getTx({txID:t.txId.value()})).unsignedTx;if(!l.pvmSerial.isAddAutoRenewedValidatorTx(r))throw new Error("Referenced validator transaction is not an AddAutoRenewedValidatorTx");const n=r.getValidatorAuthority().addrs,a=t.getAuth().values(),i=n.reduce(((e,t,s)=>(a.includes(s)&&e.push([t,s]),e)),[]);return e.push(new l.utils.AddressMap(i)),e}catch(e){throw new Error(`Error while preparing auto-renewed validator config auth data: ${e.message}`)}}(i,e,s));return new l.UnsignedTx(e,n,i,r)},{bufferToHex:se,packTx:re}=l.utils,{publicKeyBytesToAddress:ne,recoverPublicKey:ae}=l.secp256k1,ie=new l.Signature(new Uint8Array(Array(65).fill(0))),oe=(e,t)=>{const s=Math.max(...e);if(!isFinite(s))throw new Error("Error while adding placeholder signatures for the provided indices.");const r=new Array(s+1).fill(ie);if(!t)return r;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return r;const o=re(n.getTx()),d=p.sha256(o),u=ie.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=ae(d,e.toBytes()),s={toHex:()=>se(ne(t))},i=n.addressMaps.getSigIndicesForAddress(s,!1)??[];for(const t of i)t[0]===a&&(r[t[1]]=e)}return r};function de(e){return l.utils.bufferToHex(l.utils.addChecksum(e.toBytes()))}const{getManagerForVM:ue,hexToBuffer:ce,unpackWithManager:le}=l.utils,pe=async({transactionHex:e,chainAlias:t,provider:s,utxos:r})=>{const n=Q(t);if(n===l.EVM)throw new Error("EVM transactions are not supported");const a=ce(e),i=le(n,a),o=await(async({tx:e,txBytes:t,provider:s,vm:r,utxos:n})=>{try{const a=ue(r).unpack(t,l.avaxSerial.SignedTx),i=await te({tx:e,utxos:n,provider:s,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new l.Credential(oe(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new l.Credential(oe(e))))}})({tx:i,txBytes:a,provider:s,vm:n,utxos:r});return te({tx:i,provider:s,credentials:o,utxos:r})},{parseBech32:he,format:ge}=l.utils,{publicKeyBytesToAddress:me}=l.secp256k1;class fe{constructor(e,t,s){this.baseUrl=e,this.context=t,this.fetchOptions=s}getContext(){return this.context}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 l.networkIDs.getHRP(this.getNetworkID())}getApiX(){const e=new l.avm.AVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiP(){const e=new l.pvm.PVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiC(){const e=new l.evm.EVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getInfo(){const e=new l.info.InfoApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}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,s){const r=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(r,"hex"),i=me(a);return ge(s,this.getHrp(),i)}getAddressFromBuffer(e,t){return ge(t,this.getHrp(),e)}formatAddress(e,t){const[,s]=he(e);return ge(t,this.getHrp(),s)}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(),s=de(e);return this.issueTxHex(s,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,s=6e4){const r=this.getApiByVM(t),n=Date.now();return new Promise(((t,a)=>{const i=async()=>{let o;switch(s&&n+s<Date.now()&&a(new Error("Timeout")),o=r instanceof l.evm.EVMApi?await r.getAtomicTxStatus(e):await r.getTxStatus({txID:e,includeReason:!0}),o.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{i()}),1e3)}};i()}))}}const xe={weights:l.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)},ve={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:xe},we={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:xe},ye={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:xe};class Ae extends fe{constructor(e,t,s){super(e,t,s)}static async fromBaseURL(e){const t=await l.Context.getContextFromURI(e);try{return new Ae(e,t)}catch{return new Ae(e,t)}}static getDefaultMainnetProvider(e){return new Ae(g.AVALANCHE_XP_NETWORK.rpcUrl,ve,e)}static getDefaultFujiProvider(e){return new Ae(g.AVALANCHE_XP_TEST_NETWORK.rpcUrl,we,e)}static getDefaultDevnetProvider(e){return new Ae(g.AVALANCHE_XP_DEVNET_NETWORK.rpcUrl,ye,e)}}const{bytesCompare:be,parseBech32:Te}=l.utils,Se=(e,t)=>"P"===t,Ie=(e,t,s)=>{const r=Se(0,t)?e.amount:e.asset?.amount;return new l.TransferOutput(new l.BigIntPr(BigInt(r)),l.OutputOwners.fromNative(e.addresses.map((e=>Te(e)[1])).sort(be),BigInt(s??0),e.threshold))},Pe=(e,t)=>{const s=((e,t)=>{const s=t===h.Network.FUJI,{cBlockchainID:r,xBlockchainID:n,pBlockchainID:a}=s?we:ve;if(r===e)return"C";if(n===e)return"X";if(a===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),r=Se(0,s)?e.txHash:e.creationTxHash,n=Se(0,s)?e.assetId:e.asset?.assetId;return new l.Utxo(l.avaxSerial.UTXOID.fromNative(r,Number(e.outputIndex)),l.Id.fromString(n),((e,t)=>Se(0,t)?e.stakeableLocktime?new l.pvmSerial.StakeableLockOut(new l.BigIntPr(BigInt(e.stakeableLocktime??0)),Ie(e,t,e.platformLocktime??0)):Ie(e,t,e.platformLocktime):Ie(e,t,e.locktime))(e,s))},{unpackWithManager:Be,parse:Ce,bufferToHex:ke,AddressMaps:Ee,AddressMap:Ve}=l.utils;function Me(e){const t=Buffer.from(e,"utf8"),s=Buffer.alloc(4);s.writeUInt32BE(t.length,0);const r=Buffer.from(`Avalanche Signed Message:\n${s}${e}`,"utf8");return m("sha256").update(r).digest()}const De=1024,Oe=1024;async function Ke(e,t,s){const r=e.slice(0,De),n=e.slice(De),a=await Ue(t,{...s,addresses:r});if(n.length){const r=await Ke(n,t,{...s,addresses:e});return a.merge(r)}return a}async function Ue(e,t){if(t.addresses.length>De)throw new Error(`Can not get UTXOs for more than ${De} addresses.`);const{endIndex:s,utxos:r}=await e.getUTXOs(t),n=new l.utils.UtxoSet(r);if(r.length>=Oe){const r=await Ue(e,{...t,startIndex:s});return n.merge(r)}return n}function _e(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:Ne}=l.utils;async function Le(e,t){const s=e.slice(0,256),r=e.slice(256),n=await t.getStake({addresses:s});if(r.length){const e=await Le(r,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Re,hexToBuffer:Xe,unpackWithManager:Fe}=l.utils;function He(e,t=!0){try{if(t){const[t]=l.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else l.utils.parseBech32(e);return!0}catch(e){return!1}}const $e={AVM:"X",PVM:"P",EVM:"C"},qe=e=>l.utils.isStakeableLockOut(e)?e.getStakeableLocktime():0n,We=(e,{vm:t,params:s})=>e.map((e=>{const r=e.getAssetId(),n=(e=>l.utils.isTransferOut(e)||l.utils.isNftTransferOut(e)?e.outputOwners:l.utils.isStakeableLockOut(e)||l.utils.isNftMintOut(e)||l.utils.isSecpMintOut(e)?e.getOutputOwners():void 0)(e.output);return{assetId:r,amount:e.output.amount(),owners:(n?.addrs??[]).map((e=>l.utils.format($e[t],s.provider.getHrp(),e.toBytes()))),locktime:n?.locktime.value()??0n,stakeableLocktime:qe(e.output),threshold:BigInt(n?.threshold.value()??0),isAvax:r===s.assetId}})),je=(e,{params:t})=>e.map((e=>({assetId:e.assetId.toString(),amount:e.amount.value(),owners:[e.address.toHex()],locktime:0n,stakeableLocktime:0n,threshold:1n,isAvax:e.assetId.toString()===t.assetId}))),Ge=e=>{if([ve.xBlockchainID,we.xBlockchainID,ye.xBlockchainID].includes(e))return"AVM";if([ve.pBlockchainID,we.pBlockchainID,ye.pBlockchainID].includes(e))return"PVM";if([ve.cBlockchainID,we.cBlockchainID,ye.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},Je=(e,t)=>e.reduce(((e,s)=>s.assetId.toString()!==t?e:e+s.output.amount()),BigInt(0)),ze=(e,t)=>e.reduce(((e,s)=>s.assetId.toString()!==t?e:e+s.input.amount()),BigInt(0));var Ye={parseCreateSubnetTx:e=>l.pvmSerial.isCreateSubnetTx(e)?({feeData:t,...s})=>({type:Y.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(s.provider.getHrp())}`)),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseCreateChainTx:e=>l.pvmSerial.isCreateChainTx(e)?({feeData:t,...s})=>({type:Y.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,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseAddSubnetValidatorTx:e=>l.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t,...s})=>({type:Y.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,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseRemoveSubnetValidatorTx:e=>l.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t,...s})=>({type:Y.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseImportTx:e=>l.pvmSerial.isImportTx(e)||l.avmSerial.isImportTx(e)||l.evmSerial.isImportTx(e)?l.evmSerial.isImportTx(e)?({feeData:t,...s})=>({type:Y.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:ze(e.importedInputs,s.assetId),...t,outputs:je(e.Outs,{params:s})}):({feeData:t,...s})=>({type:Y.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:ze(e.ins,s.assetId),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseExportTx:e=>l.pvmSerial.isExportTx(e)||l.avmSerial.isExportTx(e)||l.evmSerial.isExportTx(e)?l.evmSerial.isExportTx(e)?({feeData:t,...s})=>({type:Y.Export,chain:e.getVM(),destination:Ge(e.destinationChain.toString()),amount:Je(e.exportedOutputs,s.assetId),...t,outputs:We(e.exportedOutputs,{vm:Ge(e.destinationChain.toString()),params:s})}):({feeData:t,...s})=>({type:Y.Export,chain:e.getVM(),destination:Ge(e.destination.value()),amount:Je(e.outs,s.assetId),...t,outputs:[...We(e.baseTx.outputs,{vm:e.getVM(),params:s}),...We(e.outs,{vm:Ge(e.destination.value()),params:s})]}):null,parseBaseTx:e=>l.avmSerial.isAvmBaseTx(e)||l.pvmSerial.isPvmBaseTx(e)?async({feeData:t,...s})=>{const r=e.getVM();return{type:Y.Base,chain:r,outputs:We(e.baseTx.outputs,{vm:r,params:s}),memo:f(Buffer.from(e.baseTx.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!l.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,s;return l.pvmSerial.isSigner(e.signer)&&(s=l.utils.bufferToHex(e.signer.proof.publicKey),t=l.utils.bufferToHex(e.signer.proof.signature)),({feeData:r,...n})=>({type:Y.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:s,signature:t,...r,outputs:We([...e.baseTx.outputs,...e.stake],{vm:e.getVM(),params:n})})},parseAddPermissionlessDelegatorTx:e=>l.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t,...s})=>({type:Y.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,outputs:We([...e.baseTx.outputs,...e.stake],{vm:e.getVM(),params:s})}):null,parseTransferSubnetOwnershipTx:e=>l.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,...s})=>({type:Y.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(s.provider.getHrp())}`)),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseConvertSubnetTx:e=>l.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,...s})=>{const r=s.provider.getHrp(),n=e=>`P-${e.toString(r)}`;return{type:Y.ConvertSubnetToL1,chain:e.getVM(),managerAddress:`0x${e.address.toString("hex")}`,validators:e.validators.map((e=>({nodeId:l.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,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}}:null,parseRegisterL1ValidatorTx:e=>l.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t,...s})=>({type:Y.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseIncreaseL1ValidatorBalanceTx:e=>l.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t,...s})=>({type:Y.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseSetL1ValidatorWeightTx:e=>l.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t,...s})=>({type:Y.SetL1ValidatorWeight,chain:e.getVM(),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseDisableL1ValidatorTx:e=>l.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t,...s})=>({type:Y.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null,parseAddAutoRenewedValidatorTx:e=>{if(!l.pvmSerial.isAddAutoRenewedValidatorTx(e))return null;let t,s;l.pvmSerial.isSigner(e.signer)&&(s=l.utils.bufferToHex(e.signer.proof.publicKey),t=l.utils.bufferToHex(e.signer.proof.signature));const r=e.stake.reduce(((e,t)=>e+t.amount()),0n);return({feeData:n,...a})=>({type:Y.AddAutoRenewedValidator,chain:e.getVM(),nodeID:e.nodeId.value(),stake:r,stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),owner:e.getValidatorAuthority(),delegationFee:e.delegationShares.value(),autoCompoundRewardShares:e.autoCompoundRewardShares.value(),period:e.period.value(),signer:e.signer,publicKey:s,signature:t,...n,outputs:We([...e.baseTx.outputs,...e.stake],{vm:e.getVM(),params:a})})},parseSetAutoRenewedValidatorConfigTx:e=>l.pvmSerial.isSetAutoRenewedValidatorConfigTx(e)?({feeData:t,...s})=>({type:Y.SetAutoRenewedValidatorConfig,chain:e.getVM(),txId:e.txId.value(),autoCompoundRewardShares:e.autoCompoundRewardShares.value(),period:e.period.value(),...t,outputs:We(e.baseTx.outputs,{vm:e.getVM(),params:s})}):null};const Qe=async(e,t)=>{const s=[...new Set(e.outputs.filter((e=>!e.isAvax)).map((e=>e.assetId)))];if(0===s.length)return e;const r=await Promise.allSettled(s.map((e=>(async(e,t)=>{const s=await t.getApiX().getAssetDescription(e);return{...s,denomination:Number(s.denomination)}})(e,t)))),n=new Map(s.flatMap(((e,t)=>{const s=r[t];return"fulfilled"===s?.status?[[e,s.value]]:[]})));return{...e,outputs:e.outputs.map((e=>{const t=n.get(e.assetId);return t?{...e,assetDescription:t}:e}))}},{getBurnedAmountByTx:Ze,getOutputAmounts:et,getInputAmounts:tt,validateBurnedAmount:st}=l.utils;function rt(e,t,s){return[...e].sort(((e,r)=>{for(let n=0;n<t.length;n++){const a=t[n];if(e[a]>r[a])return"asc"===s?1:-1;if(e[a]<r[a])return"asc"===s?-1:1}return 0}))}function nt(e){const t=_e(),s=e.map((e=>({utxo:e,...l.utils.getUtxoInfo(e)}))),r=s.filter((e=>e.stakeableLocktime<=t)),n=s.filter((e=>e.stakeableLocktime>t)),a=rt(r,["amount"],"desc"),i=rt(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function at(e,t){return rt(e.map((e=>({utxo:e,...l.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const it=e=>at(e,!0),ot=e=>at(e,!1);const{getUtxoInfo:dt}=l.utils;var ut=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(ut||{});const ct="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",lt="11111111111111111111111111111111LpoYY",pt=(e,t)=>e.reduce(((e,t)=>e+dt(t).amount),BigInt(0))-t,ht={BaseP:{sortFunction:it,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext();return e.baseTX({utxoSet:new l.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[r.avaxAssetID]:pt(t,r.baseTxFee)},feeState:s})}},ConsolidateP:{sortFunction:ot,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext();return e.consolidateP({utxoSet:new l.utils.UtxoSet(t),amount:pt(t,r.baseTxFee),feeState:s})}},AddPermissionlessValidator:{sortFunction:nt,unsignedTxBuilder:(e,t,s)=>e.addPermissionlessValidator({utxoSet:new l.utils.UtxoSet(t),nodeId:ct,start:_e(),end:_e()+BigInt(1e3),weight:pt(t,e.getProvider().getContext().baseTxFee),subnetId:lt,shares:5,feeState:s,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(l.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(l.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:nt,unsignedTxBuilder:(e,t,s)=>e.addPermissionlessDelegator({utxoSet:new l.utils.UtxoSet(t),nodeId:ct,start:_e(),end:_e()+BigInt(1e3),weight:pt(t,e.getProvider().getContext().baseTxFee),subnetId:lt,feeState:s})},ExportP:{sortFunction:it,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext(),n=function({numberIns:e=1},t){const s=l.Common.createDimensions({bandwidth:161*e+254,dbRead:e,dbWrite:2+e,compute:200*e});return l.Common.dimensionsToGas(s,t)}({numberIns:t.length},r.platformFeeConfig.weights),a=s?n*s.price:r.baseTxFee;return e.exportP({amount:pt(t,a),utxoSet:new l.utils.UtxoSet(t),destination:"X",feeState:s})}},ImportP:{sortFunction:it,unsignedTxBuilder:(e,t,s)=>e.importP({utxoSet:new l.utils.UtxoSet(t),sourceChain:"X",feeState:s})}};function gt(e){return x.validateString(e,!0)&&6===e.split("/").length}const mt=(e,t=!0)=>`${t?"m/":""}44'/9000'/${e}'/0/0`;function ft(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:xt,hexToBuffer:vt}=l.utils;class wt{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Ke(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Le(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 Ke(this.getAddresses(e),s,{sourceChain:r,addresses:[]})}exportX(e,t,s,r){r=r||this.getCurrentAddress(s);const n=xt(r)[2],a=this.provider.getAvaxID(),i=l.TransferableOutput.fromNative(a,e,[n]),o=at(t.getUTXOs(),!0),d=this.provider.getChainID(s),u=this.getAddresses("X").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("X"))[2];return l.avm.newExportTx(this.provider.getContext(),d,u,o,[i],{threshold:1,changeAddresses:[c]})}importP({utxoSet:e,sourceChain:t,toAddress:s,threshold:r,feeState:n,locktime:a}){const i=this.provider.getChainID(t),o=this.getAddresses("P").map((e=>xt(e)[2]));xt(this.getChangeAddress("P"))[2],s=s||this.getCurrentAddress("P");const d=xt(s)[2],u=e.getUTXOs();return ft(n),l.pvm.newImportTx({fromAddressesBytes:o,utxos:u,toAddressesBytes:[d],sourceChainId:i,threshold:r,feeState:n,locktime:a},this.provider.getContext())}importX(e,t,s){const r=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>xt(e)[2])),a=xt(this.getChangeAddress("X"))[2];s=s||this.getCurrentAddress("X");const i=xt(s)[2];return l.avm.newImportTx(this.provider.getContext(),r,e.getUTXOs(),[i],n,{changeAddresses:[a]})}importC(e,s,r,n,a){const i=this.provider.getChainID(s),o=this.getAddresses("C").map((e=>xt(e)[2]));a=a||this.getAddressEVM();const d=Buffer.from(t.strip0x(a),"hex");return l.evm.newImportTxFromBaseFee(this.provider.getContext(),d,o,e.getUTXOs(),i,r,n)}exportC(e,t,s,r,n){const a=vt(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=xt(n)[2],d=r/BigInt(1e9);return l.evm.newExportTxFromBaseFee(this.provider.getContext(),d,e,i,a,[o],s)}exportP({amount:e,utxoSet:t,destination:s,feeState:r,toAddress:n}){n=n||this.getCurrentAddress(s);const a=xt(n)[2],i=this.provider.getAvaxID(),o=l.TransferableOutput.fromNative(i,e,[a]),d=at(t.getUTXOs(),!0),u=this.provider.getChainID(s),c=this.getAddresses("P").map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2];return ft(r),l.pvm.newExportTx({changeAddressesBytes:[p],fromAddressesBytes:c,utxos:d,outputs:[o],destinationChainId:u,feeState:r},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:s,toAddress:r,options:n}){const a=ot(e.getUTXOs());r=r??this.getCurrentAddress("P");const i=xt(r)[2],o=this.provider.getContext(),d=[l.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],p=n?.changeAddresses??[c];return ft(s),l.pvm.newBaseTx({changeAddressesBytes:p,fromAddressesBytes:u,utxos:a,outputs:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:s},o)}baseTX({utxoSet:e,chain:t,toAddress:s,amountsPerAsset:r,feeState:n,options:a,fromAddresses:i}){const[o,d,u]=xt(s);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${s}"`);const c=Object.entries(r).map((([e,t])=>l.TransferableOutput.fromNative(e,t,[u]))),p=at(e.getUTXOs(),!0),h=(i??this.getAddresses(t)).map((e=>xt(e)[2])),g=xt(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?l.avm.newBaseTx(this.provider.getContext(),h,p,c,a):(ft(n),l.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:h,utxos:p,outputs:c,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:s,subnetAuth:r,feeState:n,address:a,validators:i,options:o,fromAddresses:d}){const u=(d??this.getAddresses("P")).map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],p=o?.changeAddresses??[c],h=i.map((({nodeId:e,pubKey:t,signature:s,balance:r,weight:n,deactivationOwner:a,remainingBalanceOwner:i})=>{const o=new l.pvmSerial.ProofOfPossession(Uint8Array.from(l.utils.hexToBuffer(t)),Uint8Array.from(l.utils.hexToBuffer(s))),d=l.PChainOwner.fromNative(i.addresses.map((e=>xt(e)[2])),i.threshold??1),u=l.PChainOwner.fromNative(a.addresses.map((e=>xt(e)[2])),a.threshold??1);return l.L1Validator.fromNative(e,n,r,o,d,u)}));return l.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:p,validators:h,fromAddressesBytes:u,address:xt(a)[2],chainId:t,subnetId:s,subnetAuth:r,feeState:n,utxos:at(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:s,message:r,feeState:n,fromAddresses:a,options:i}){const o=(a??this.getAddresses("P")).map((e=>xt(e)[2])),d=xt(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return l.pvm.newRegisterL1ValidatorTx({utxos:at(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(l.utils.hexToBuffer(s)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:i?.memo,message:Uint8Array.from(l.utils.hexToBuffer(r)),minIssuanceTime:i?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:s,options:r,fromAddresses:n}){const a=(n??this.getAddresses("P")).map((e=>xt(e)[2])),i=xt(this.getChangeAddress("P"))[2],o=r?.changeAddresses??[i];return l.pvm.newSetL1ValidatorWeightTx({utxos:at(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:a,memo:r?.memo,message:Uint8Array.from(l.utils.hexToBuffer(s)),minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:s,fromAddresses:r,disableAuth:n,validationId:a}){const i=(r??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return l.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:at(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:s,fromAddresses:r,balance:n,validationId:a}){const i=(r??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return l.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:at(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}addAutoRenewedValidator({utxoSet:e,nodeId:t,weight:s,shares:r,feeState:n,fromAddresses:a,rewardAddresses:i,delegatorRewardAddresses:o,ownerAddresses:d,publicKey:u,signature:c,autoCompoundRewardShares:p,period:h,options:g,locktime:m,threshold:f}){const x=nt(e.getUTXOs()),v=(a??this.getAddresses("P")).map((e=>xt(e)[2])),w=(i??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),y=(o??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),A=(d??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),b=xt(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[b];return l.pvm.newAddAutoRenewedValidatorTx({fromAddressesBytes:v,delegatorRewardsOwner:y,utxos:x,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,weight:s,shares:r,feeState:n,publicKey:u,rewardAddresses:w,signature:c,locktime:m,threshold:f,ownerAddresses:A,autoCompoundRewardShares:p,period:h},this.provider.getContext())}setAutoRenewedValidatorConfig({utxoSet:e,feeState:t,validatorTxId:s,auth:r,autoCompoundRewardShares:n,period:a,fromAddresses:i,options:o}){const d=(i??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[u];return l.pvm.newSetAutoRenewedValidatorConfigTx({utxos:at(e.getUTXOs(),!0),changeAddressesBytes:c,feeState:t,fromAddressesBytes:d,memo:o?.memo,minIssuanceTime:o?.minIssuanceTime,validatorTxId:s,auth:r,autoCompoundRewardShares:n,period:a},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:s,vmID:r,fxIds:n,genesisData:a,subnetAuth:i,feeState:o,options:d,fromAddresses:u}){const c=at(e.getUTXOs(),!0),p=(u??this.getAddresses("P")).map((e=>xt(e)[2])),h=xt(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[h];return ft(o),l.pvm.newCreateChainTx({chainName:s,feeState:o,fromAddressesBytes:p,fxIds:n,genesisData:a,subnetAuth:i,subnetId:t,utxos:c,vmId:r,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:s,fromAddresses:r,options:n,threshold:a,locktime:i}){const o=at(e.getUTXOs(),!0),d=(r??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],p=t.map((e=>xt(e)[2]));return ft(s),l.pvm.newCreateSubnetTx({fromAddressesBytes:d,changeAddressesBytes:c,utxos:o,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:s,threshold:a,locktime:i,subnetOwners:p},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:s,end:r,weight:n,subnetId:a,subnetAuth:i,feeState:o,fromAddresses:d,options:u}){const c=at(e.getUTXOs(),!0),p=(d??this.getAddresses("P")).map((e=>xt(e)[2])),h=xt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[h];return ft(o),l.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:p,utxos:c,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,nodeId:t,start:s,end:r,weight:n,subnetId:a,subnetAuth:i,feeState:o},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:s,end:r,weight:n,subnetId:a,shares:i,feeState:o,fromAddresses:d,rewardAddresses:u,delegatorRewardAddresses:c,publicKey:p,signature:h,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=nt(e.getUTXOs()),w=(d??this.getAddresses("P")).map((e=>xt(e)[2])),y=(u??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),A=(c??[this.getCurrentAddress("P")]).map((e=>xt(e)[2]));if(!(a!==l.networkIDs.PrimaryNetworkID.toString()||p&&h))throw new Error("Must provide public key and signature for primary subnet.");const b=xt(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[b];return ft(o),l.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:A,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,start:s,end:r,weight:n,subnetId:a,shares:i,feeState:o,publicKey:p,rewardAddresses:y,signature:h,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:s,end:r,weight:n,subnetId:a,fromAddresses:i,rewardAddresses:o,options:d,locktime:u,feeState:c,threshold:p,stakingAssetId:h,additionalOutputs:g}){const m=nt(e.getUTXOs()),f=(i??this.getAddresses("P")).map((e=>xt(e)[2])),x=(o??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),v=xt(this.getChangeAddress("P"))[2],w=d?.changeAddresses??[v],y=this.provider.getContext();return ft(c),l.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:f,utxos:m,minIssuanceTime:d?.minIssuanceTime,memo:d?.memo,changeAddressesBytes:w,nodeId:t,start:s,end:r,weight:n,subnetId:a,rewardAddresses:x,locktime:u,stakingAssetId:h,threshold:p,feeState:c,additionalOutputs:g?.map((e=>l.TransferableOutput.fromNative(e.assetId??y.avaxAssetID,e.amount,e.addresses.map((e=>xt(e)[2])),e.locktime,e.threshold)))},y)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:s,subnetAuth:r,fromAddresses:n,feeState:a,options:i}){const o=at(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return ft(a),l.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:c,fromAddressesBytes:d,utxos:o,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:t,subnetId:s,subnetAuth:r,feeState:a},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:s,subnetOwners:r,feeState:n,fromAddresses:a,options:i,threshold:o,locktime:d}){const u=at(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],h=i?.changeAddresses??[p],g=r.map((e=>xt(e)[2]));return ft(n),l.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:h,fromAddressesBytes:c,utxos:u,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:t,subnetAuth:s,subnetOwners:g,feeState:n,threshold:o,locktime:d},this.provider.getContext())}}class yt extends wt{constructor(e,t,s){if(super(s),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,s,r){const a=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=t.strip0x(n.SigningKey.computePublicKey(s,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new yt(o,d,r)}static fromMnemonic(e,t,s,r){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!gt(s)||!gt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=i.mnemonicToSeedSync(e),o=a.fromSeed(n),d=o.derivePath(s),u=o.derivePath(t);return yt.fromPublicKey(u.publicKey,d.publicKey,r)}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 At={type:"zondax",getApp:e=>new v(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,s={show:!1,hrp:"avax"}){const r=this.getApp(e);return{publicKey:(await r.getAddressAndPubKey(t.toString(),s.show,s.hrp)).publicKey}},async getXPUB(e,t){const s=this.getApp(e),r=await s.getExtendedPubKey(t,!1);return{pubKey:r.publicKey,chainCode:r.chain_code}},async signHash(e,t,s,r){const n=this.getApp(e),a=r.map((e=>e.toString(!0))),i=await n.signHash(s.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,s,r,n){const a=this.getApp(e),i=r.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(s.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function bt(e){return!(await At.getVersion(e)>="0.6.0")}const{parse:Tt}=l.utils;class St extends wt{constructor(e,t,s){super(s),this.avmXpub=e,this.accountNode=a.fromBase58(e),this.evmWallet=new yt(t,t,s)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=i.mnemonicToSeedSync(e),r=a.fromSeed(s),n=r.derivePath("m/44'/9000'/0'").neutered(),o=r.derivePath(R(0,L.BIP44)).neutered();return new St(n.toBase58(),o.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 s=`${t?1:0}/${e}`,r=this.pubkeyCache[s];if(r)return r;const{publicKey:n}=this.accountNode.derivePath(s);return this.pubkeyCache[s]=n,n}getAddressAtIndex(e,t=!1,s){const r=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(r,s)}getExternalAddresses(e){const t=[];for(let s=0;s<=this.externalIndex;s++)t.push(this.getAddressAtIndex(s,!1,e));return t}getInternalAddresses(e){const t=[];for(let s=0;s<=this.internalIndex;s++)t.push(this.getAddressAtIndex(s,!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(Tt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getRawAddressC(){return Buffer.from(Tt(this.getCurrentAddress("C"))[2])}}const{isTransferOut:It,isStakeableLockOut:Pt}=l.utils;function Bt(e){const t=e.output;return It(t)||Pt(t)?t.getOwners():[]}function Ct(e){const t=e.getTx();return l.avmSerial.isExportTx(t)||l.pvmSerial.isExportTx(t)?new Set(t.outs.map(Bt).flat()):l.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(Bt).flat()):new Set((t.baseTx?.outputs??[]).map(Bt).flat())}const{parse:kt}=l.utils;class Et extends St{constructor(e,t,s){super(e,t,s)}getAdditionalAddressesByIndices(e,t,s){return"C"===s?[]:e.map((e=>{const r=this.getAddressAtIndex(e,t,s),[,,n]=kt(r);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,s){if(await bt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const r=U(e),i=await At.getXPUB(e,Et.getAccountPath("X")),o=a.fromPublicKey(i.pubKey,i.chainCode),d=zt(0,"EVM",{pathSpec:L.BIP44}),u=await r.getAddress(d,!1),c=n.SigningKey.computePublicKey(Buffer.from(u.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new Et(o.toBase58(),l,s)}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,s){const r=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...r,...s??[]]),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:s,internalIndices:r}=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(s??[],!1,i),u=this.getAdditionalAddressesByIndices(r??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>x.fromString(e))),l=[...Ct(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>x.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||[],s=x.fromString(Et.getAccountPath(e.chain));return[...(await At.signTx(e.transport,e.buffer,s,e.signers,t)).signatures.values()]}}const{strip0x:Vt}=l.utils;class Mt extends St{constructor(e,t,s){const r=a.fromBase58(e).neutered(),i=new n.SigningKey(t),o=Buffer.from(Vt(i.compressedPublicKey),"hex");super(r.toBase58(),o,s),this.evmPrivKey=t,this.accountNode=a.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=i.mnemonicToSeedSync(e),r=a.fromSeed(s),n=r.derivePath("m/44'/9000'/0'"),o=r.derivePath(zt(0,"EVM",{pathSpec:L.BIP44}));if(!o.privateKey)throw new Error("Unable to derive EVM private key.");return new Mt(n.toBase58(),o.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await l.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const s=this.accountNode.derivePath(`0/${e}`);if(!s.privateKey)throw new Error("Unable to get private key.");t.push(s.privateKey)}const s=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const s=this.accountNode.derivePath(`0/${t}`);if(!s.privateKey)throw new Error("Unable to get private key.");e.push(s.privateKey)}return e}),[]);return[...t,...s]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const s=this.accountNode.derivePath(`1/${e}`);if(!s.privateKey)throw new Error("Unable to get private key.");t.push(s.privateKey)}const s=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const s=this.accountNode.derivePath(`1/${t}`);if(!s.privateKey)throw new Error("Unable to get private key.");e.push(s.privateKey)}return e}),[]);return[...t,...s]}getSigningKeys(e){const{tx:t,externalIndices:s,internalIndices:r}=e;return"EVM"===t.getVM()?[this.evmPrivKey]:[...this.getInternalPrivateKeys(r),...this.getExternalPrivateKeys(s)]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Dt,sign:Ot,signHash:Kt}=l.secp256k1,{addChecksum:Ut}=l.utils;class _t extends yt{privKeyXP;privKeyC;constructor(e,t,s){super(Buffer.from(Dt(e)),Buffer.from(Dt(t)),s),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,s,r){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!gt(s)||!gt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=i.mnemonicToSeedSync(e),o=a.fromSeed(n),d=o.derivePath(t),u=o.derivePath(s);if(!d.privateKey||!u.privateKey)throw new Error("Failed to generate private keys.");return new _t(d.privateKey,u.privateKey,r)}async signMessage(e){const t=Me(e.message),s=this.getSigningKey(e.chain);return Buffer.from(Ut(await Kt(t,s)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await l.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Ot(e.buffer,t))]}}const{strip0x:Nt}=l.utils;class Lt extends yt{constructor(e,t,s,r,a){const i=l.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),o=l.utils.strip0x(n.SigningKey.computePublicKey(s,!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=r,!gt(t)||!gt(r))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,s,a){if(await bt(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!gt(t)||!gt(s))throw new Error("Invalid path configuration.");const i=new r(e),o=await i.getAddress(s,!1),d=await i.getAddress(t,!1),u=Buffer.from(Nt(o.publicKey),"hex"),c=Buffer.from(Nt(d.publicKey),"hex"),l=Buffer.from(Nt(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Nt(n.SigningKey.computePublicKey(c,!0)),"hex");return new Lt(p,t,l,s,a)}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=x.fromString(this.getAccountPath(e.chain)),s=x.fromString(this.getPartialSignerPath(e.chain)),r=Me(e.message),n=(await At.signHash(e.transport,r,t,[s])).signatures.get(s.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}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,s=t.getVM(),r=Buffer.from(t.toBytes()),n="EVM"===s?"C":"X";return(await this.signTxBuffer({buffer:r,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=x.fromString(this.getAccountPath(e.chain)),s=x.fromString(this.getPartialSignerPath(e.chain));return[...(await At.signTx(e.transport,e.buffer,t,[s],[s])).signatures.values()]}}const{parse:Rt}=l.utils;const Xt={C:60,X:9e3,P:9e3};var Ft=Object.freeze({__proto__:null,AbstractProvider:fe,AddressWallet:class extends wt{constructor(e,t,s,r,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=s,this.xpChangeAddress=r,s.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(s.some((e=>!He(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!He(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(r)}setChangeAddress(e){if(!He(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:ye,FujiContext:we,JsonRpcProvider:Ae,LedgerLiveSigner:class{constructor(e){this.accountIndices=e}#s(e){return`m/44'/${Xt[e]}'`}#r(e,t){return`${this.#s(e)}/${t}'`}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a message.");const t=x.fromString(this.#r(e.chain,this.accountIndices[0])),s=x.fromString("0/0"),r=Me(e.message),n=(await At.signHash(e.transport,r,t,[s])).signatures.get(s.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,s=t.getVM(),r=Buffer.from(t.toBytes()),n="EVM"===s?"C":"AVM"===s?"X":"P",a=new Set(e.externalIndices??this.accountIndices);for(const s of a){const a=x.fromString(this.#r(n,s));(await this.#n(a,{buffer:r,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)}))}return t}async#n(e,t){if(!t.transport)throw new Error("Ledger transport not provided");return[...(await At.signTx(t.transport,t.buffer,e,t.signers??[x.fromString("0/0")],t.change??[x.fromString("0/0")])).signatures.values()]}async signTxBuffer(e){if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a tx buffer.");const t=x.fromString(this.#r(e.chain,this.accountIndices[0]));return this.#n(t,e)}},LedgerSigner:Lt,LedgerWallet:Et,MainnetContext:ve,MnemonicWallet:Mt,MnemonicWalletVoid:St,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,s,r=L.BIP44){this.activeAccountIndex=e,this.provider=t,this.pathSpec=r,s&&(this.accountNode=a.fromBase58(s))}accountNode;reSerializeTx(e,t){return e instanceof l.EVMUnsignedTx||"C"===t?l.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):l.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'/${this.activeAccountIndex}'`;case"C":return`m/44'/60'/${this.pathSpec===L.LedgerLive?this.activeAccountIndex:0}'`}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:s}=this.accountNode.derivePath(e),r=this.provider.getAddress(s,t);return Buffer.from(Rt(r)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:s,internalIndices:r}=e,n=this.getChainAlias(t),a="EVM"===e.tx.getVM()?`0/${this.pathSpec===L.LedgerLive?0:this.activeAccountIndex}`:"0/0",i=new Map;if("C"===n||!this.accountNode)return i;const o=(s??[]).map((e=>`0/${e}`)),d=(r??[]).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,s){return 0===t.size?[x.fromString("C"===s?`0/${this.pathSpec===L.LedgerLive?0:this.activeAccountIndex}`:"0/0")]:e.reduce(((e,s)=>{const r=t.get(Buffer.from(s).toString("hex"));return r&&e.push(x.fromString(r)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),s=this.reSerializeTx(e.tx,t),r=Buffer.from(s.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(s.getAddresses(),n,t),i=this.getAddressBipPaths([...Ct(s)],n,t);return(await this.signTxBuffer({buffer:r,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{s.addSignature(e)})),s}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||[],s=x.fromString(this.getAccountPath(e.chain));return[...(await At.signTx(e.transport,e.buffer,s,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="C"===e.chain?this.activeAccountIndex:0,s=e.signer||x.fromString(`0/${t}`);if(2!=s.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=Me(e.message),n=(await At.signHash(e.transport,r,x.fromString(this.getAccountPath(e.chain)),[s])).signatures.get(s.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const s=i.mnemonicToSeedSync(e),r=a.fromSeed(s);this.accountNodeXP=r.derivePath(`m/44'/9000'/${t}'`);const n=r.derivePath(zt(t,"EVM",{pathSpec:L.BIP44}));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,s)=>{const r=this.accountNodeXP.derivePath(`${t?1:0}/${s}`);if(!r.privateKey)throw new Error("Unable to get private key.");return e.push(r.privateKey),e}),[])}getSigningKeys(e,t,s){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const r=this.accountNodeXP.derivePath("0/0");if(!r.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1),a=this.getAdditionalKeys(s,!0);return[r.privateKey,...n,...a]}async signTx(e){const{tx:t,externalIndices:s,internalIndices:r}=e,n=t.getVM(),a=this.getSigningKeys(n,s,r);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await l.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/0");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 s=Me(e.message),r=await l.secp256k1.signHash(s,t.privateKey);return Buffer.from(r)}},SizeSupportedTx:ut,StaticSigner:_t,TxType:Y,WalletAbstract:wt,WalletVoid:yt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:s,provider:r,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await pe({transactionHex:e,chainAlias:s,provider:r,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const i=a.getCredentials(),o=a.getSigIndices().reduce(((e,t,s)=>{const r=t.map((e=>{const t=i[s]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${s}, ${e}]`);return t}));return e.push(new l.Credential(r)),e}),[]),d=new l.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,o);return{signedTxHex:de(new l.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:Pe,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:s,credentials:r,utxos:n})=>{const a=Be(s,e),i=Ce(t)[2],o=ke(i);if(l.evmSerial.isExportTx(a))return new l.EVMUnsignedTx(a,[],new Ee([Ve.fromJSON([[o,0]])]),r);if(l.evmSerial.isImportTx(a)){const e=Ee.fromTransferableInputs(a.importedInputs,n,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new l.UnsignedTx(a,n,e,r)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:te,digestMessage:Me,emptySignature:ie,getAddressFromXpub:function(e,t,s,r,n=!1){if(t<0)throw new Error("Account index must be >= 0");const i=n?"1":"0",o=a.fromBase58(e).derivePath(`${i}/${t}`).publicKey;return s.getAddress(o,r)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return a.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const s=e.getAssetDict()[t],r={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!s)return r;const n=s.getUTXOs(),a=_e();return n.forEach((e=>{const t=Ne(e);r[t.threshold>1?"multisig":t.locktime>a?"locked":t.stakeableLocktime>a?"lockedStakeable":"available"]+=t.amount})),r.total=r.locked+r.lockedStakeable+r.multisig+r.available,r},getAvalancheDerivationPath:mt,getLedgerProvider:async function(e){return At},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:s,limit:r=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=ht[s],o=_e(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:r}=dt(e);return t<o&&(r<o||("AddPermissionlessDelegator"===s||"AddPermissionlessValidator"===s))}))),u=function(e,t,s){let r=0,n=e.length-1;if(t(e)<=s)return n;let a=-1;for(;r<=n;){const i=Math.floor((r+n)/2);t(e.slice(0,i+1))<=s?(a=i,r=i+1):n=i-1}return a}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*dt(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(dt)}),r+1}}),r);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:Ue,getPchainUnixNow:async function(e){const t=await e.getApiP().getTimestamp(),s=new Date(t.timestamp),r=Math.floor(s.getTime()/1e3);return BigInt(r)},getStakeForAddresses:Le,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,s={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{s[l.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),s.total=s.lockedStaked+s.unlockedStaked,s},getUTXOsForAddresses:Ke,getUnixNow:_e,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:s,url:r,token:n,headers:a})=>{const i=Q(t),o=Xe(e),d=Fe(i,o);if(l.evmSerial.isExportTx(d))return[];const u=(e=>{if(l.evmSerial.isImportTx(e)||l.avmSerial.isImportTx(e)||l.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case l.EVM:return h.BlockchainId.C_CHAIN;case l.AVM:return h.BlockchainId.X_CHAIN;case l.PVM:return h.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=Re(d),p=new h.Glacier({BASE:r,TOKEN:n,HEADERS:a}),g=[...new Set(c.map((e=>e.utxoID.txID.toString())))],m=await Promise.all(g.map((e=>p.primaryNetworkTransactions.getTxByHash({blockchainId:u,network:s,txHash:e}))));return c.reduce(((e,t)=>{const r=m.find((e=>e.txHash===t.utxoID.txID.toString()));if(!r)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=r.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=Pe(n,s);return e.push(a),e}),[])},getVmByChainAlias:Q,getXpubFromMnemonic:function(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=i.mnemonicToSeedSync(e);return a.fromSeed(s).derivePath(`44'/9000'/${t}'`).neutered().toBase58()},isAddAutoRenewedValidatorTx:function(e){return"add_auto_renewed_validator"===e.type},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:He,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:bt,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetAutoRenewedValidatorConfigTx:function(e){return"set_auto_renewed_validator_config"===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,s,{feeTolerance:r=50,baseFee:n}={}){const a=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(Ye)){const s=t(e);if(null!==s)return s}throw new Error("no parser found for tx")})(i),d=Ze(i,a),u=et(i),c=tt(i),p=c.get(a.avaxAssetID)??BigInt(0),h=d.get(a.avaxAssetID)??BigInt(0),g=u.get(a.avaxAssetID)??BigInt(0);let m=n;void 0===m&&(m=0n,l.evmSerial.isImportExportTx(i)?(m=await t.getApiC().getBaseFee()/BigInt(1e9),0n===m&&(m=1n)):"PVM"===i.vm&&(m=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0)))));const{isValid:f,txFee:x}=st({unsignedTx:e,context:a,burnedAmount:h,baseFee:m,feeTolerance:r}),v=await o({feeData:{totalAvaxBurned:h,totalAvaxOutput:g,totalAvaxInput:p,inputAmounts:Object.fromEntries(c),outputAmounts:Object.fromEntries(u),isValidAvaxBurnedAmount:f,txFee:x,baseFee:m},assetId:a.avaxAssetID,provider:t,currentAddress:s,utxos:e.getInputUtxos()});return Qe(v,t)},populateCredential:oe,signedTxToHex:de,sortUTXOsByAmount:at,sortUTXOsByAmountAscending:ot,sortUTXOsByAmountDescending:it,sortUTXOsStaking:nt,verifyDerivationPath:gt});const Ht=(e,t)=>{const s=y.getTransactionDecoder().decode(y.getBase64Encoder().encode(e)),r=y.getCompiledTransactionMessageDecoder().decode(s.messageBytes);return y.decompileTransactionMessageFetchingLookupTables(r,t)},$t=Symbol(),qt=(e,t)=>String(e)===String(t),Wt=async({mint:e,provider:t})=>{const s=y.address(e),{value:r}=await t.getAccountInfo(s,{encoding:"base64"}).send();if(!r)throw new Error(`Mint account not found: ${e}`);const n=r.owner;if(qt(n,b.TOKEN_PROGRAM_ADDRESS))return b.TOKEN_PROGRAM_ADDRESS;if(qt(n,T.TOKEN_2022_PROGRAM_ADDRESS))return T.TOKEN_2022_PROGRAM_ADDRESS;throw new Error(`Unsupported token program for mint ${e}: ${String(n)}`)},jt=async({mint:e,owner:t,provider:s,tokenProgram:r})=>{const n=r??await Wt({mint:e,provider:s}),[a]=await b.findAssociatedTokenPda({mint:y.address(e),owner:y.address(t),tokenProgram:n}),i=await s.getAccountInfo(a,{encoding:"base64"}).send();return{address:a,exists:Boolean(i.value),info:i}},Gt=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class Jt{#a;#i;constructor(e){this.#a=Uint8Array.from(e),this.#i=y.address(P.base58.encode(I.ed25519.getPublicKey(this.#a)))}static fromMnemonic(e,t){const s=i.mnemonicToSeedSync(e),r=B.fromMasterSeed(Uint8Array.from(s)).derive(`m/44'/501'/${t}'/0'`);return new Jt(Buffer.from(r.privateKey))}#o(e){try{return y.getCompiledTransactionMessageDecoder().decode(e),!0}catch{return!1}}async signMessage(e){const t=P.base64.decode(e);if(this.#o(t))throw new Error("Cannot use signMessage() to sign transactions!");return P.base64.encode(I.ed25519.sign(t,this.#a))}async signTx(e,t){const s=await Ht(e,t),{signatures:r,messageBytes:n,...a}=y.compileTransaction(s);if(!this.#d(r))return e;const i=P.base58.encode(I.ed25519.sign(Uint8Array.from(n),this.#a));return y.assertIsSignature(i),y.getBase64EncodedWireTransaction({...a,messageBytes:n,signatures:{...r,[this.#i]:P.base58.decode(i)}})}#d(e){return this.#i in e&&!e[this.#i]}}function zt(e,t,s={withRoot:!0}){if(e<0)throw new Error("Account index can not be less than 0.");switch(t){case"EVM":if(!s.pathSpec)throw new Error("Path spec is required for EVM: either BIP44 or Ledger Live");return R(e,s.pathSpec,s.withRoot);case"AVM":case"PVM":return mt(e,s.withRoot);case"SVM":return Gt(e,s.withRoot);default:throw new Error(`Unknown derivation path for VM: ${t}`)}}class Yt extends z{keypair;constructor(t,s){const r=e.ECPair.fromPrivateKey(t);super(r.publicKey,s),this.keypair=r}static async fromMnemonic(e,t,s,r=L.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await i.mnemonicToSeed(e),o=a.fromSeed(n),d=zt(t,"EVM",{pathSpec:r}),u=o.derivePath(d);if(!u.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new Yt(u.privateKey,s)}signTx(e,t){const s=V(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(s))}static fromEthersWallet(e,t){const s=e.privateKey;if(!s)throw new Error("Unable to get private key from ethers wallet.");const r=Buffer.from(s.substring(2),"hex");return new Yt(r,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}const Qt=e.networks;exports.Avalanche=Ft,exports.BitcoinLedgerWallet=class extends z{constructor(e,t,s,r,n){super(e,s),this.derivationPath=t,this.transport=r,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const s=function(e){return new u.AppClient(e)}(this.transport),r=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await s.getMasterFingerprint(),i=G(e,t,n,Buffer.from(a,"hex"),r,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,c=await s.signPsbt(i,o,d),l=J(i,n,r,this.derivationPath);if(c.forEach((e=>{const[t,s]=e;l.updateInput(t,{partialSig:[{signature:s.signature,pubkey:s.pubkey}]})})),!l.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return l.finalizeAllInputs(),l.extractTransaction()}},exports.BitcoinProvider=class extends E{constructor(e=!0,s,r,n,a){super(),this.isMainnet=e,this.extraParams=a;const i=s?{headers:{"api-key":s}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#u=new t.HttpClient(r||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#c=new t.HttpClient(n||d,i)}#u;#c;async#l(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#c.post("",e,{},this.extraParams))))).flat():this.#c.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#u.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,s){const r=await this.#u.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!r?.length)return{confirmed:[],unconfirmed:[]};const n=r.map(this._parseUtxo),a=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return a(n);return a(await this.getScriptsForUtxos(n,s))}async getAddressFromScript(e){const t=await this.#c.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,t){const[s,r]=e.reduce((([e,t],s)=>s.script?[[...e,s],t]:[e,[...t,s]]),[[],[]]),n=r.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),a=n.length?(await this.#l(n,t)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...s,...r.map(((e,t)=>({...e,script:a[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.#u.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.#c.post("",{jsonrpc:"2.0",id:"nownodes",method:"getblockcount",params:[]},{},this.extraParams)).result}async getFeeRates(e){const t={jsonrpc:"2.0",method:"estimatesmartfee"},s=await this.#l([{...t,id:"1",params:[1]},{...t,id:"2",params:[3]},{...t,id:"3",params:[6]}],e).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(s[0]/1024)||1,medium:Math.ceil(s[1]/1024)||1,low:Math.ceil(s[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#c.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#u.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.#u.post(`/api/v2/address/${e}`,{},{},this.extraParams),s=t.txids?.slice(0,25)??[];return await Promise.allSettled(s.map((async t=>{try{const s=await this.#u.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const s=t.vin.filter((t=>t.addresses?.includes(e))),r=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=s.reduce(((e,t)=>e+BigInt(t.value)),0n),o=r.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=r.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,s)}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:s=1,pollInterval:r=500}={}){try{return await this.getTransaction(e)}catch(n){if(s>=t)throw n;return await new Promise((e=>setTimeout(e,r))),this.waitForTx(e,{maxAttempts:t,attempt:s+1,pollInterval:r})}}},exports.BitcoinProviderAbstract=E,exports.BitcoinWallet=Yt,exports.BitcoinWalletAbstract=z,exports.BitcoinWalletVoid=class extends z{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=Qt,exports.DerivationPath=L,exports.ETH_ACCOUNT_PATH=N,exports.ETH_COIN_PATH=_,exports.JsonRpcBatchInternal=q,exports.LedgerSigner=j,exports.SolanaLedgerSigner=class{#p;#h;constructor(e,t){this.#p=Gt(e,!1),this.#h=t}async signTx(e,t){const s=await Ht(e,t),{signatures:r,messageBytes:n,...a}=y.compileTransaction(s),i=new S(this.#h),{address:o}=await i.getAddress(this.#p),d=y.address(P.base58.encode(Uint8Array.from(o)));if(!this.#d(d,r))return e;const{signature:u}=await i.signTransaction(this.#p,Buffer.from(n)),c=P.base58.encode(Uint8Array.from(u));return y.assertIsSignature(c),y.getBase64EncodedWireTransaction({...a,messageBytes:n,signatures:{...r,[d]:P.base58.decode(c)}})}#d(e,t){return e in t&&!t[e]}},exports.SolanaSigner=Jt,exports.addEncodedSigToPsbt=function(e,t,s,r){const n=[{pubkey:t,signature:e}];s.updateInput(r,{partialSig:n})},exports.compileSolanaTx=e=>y.compileTransaction(e),exports.createPSBTV2=G,exports.createPsbt=V,exports.createTransferTx=O,exports.createWalletPolicy=function(e,t,s,r){const n=new u.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${s}`);return new u.WalletPolicy(r,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=Ht,exports.formatAddressForNetworkBech32=function(t,s){const r=e.address.fromBech32(t);return e.address.toBech32(r.data,r.version,s.bech32)},exports.getAddressDerivationPath=zt,exports.getAddressFromXPub=function(e,t){const s=W(e,t);return n.computeAddress(`0x${s.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const s=a.fromBase58(e).derivePath(`0/${t}`);if(!s.privateKey)throw new Error("Unable to derive private key.");return s.privateKey},exports.getAddressPublicKeyFromXPub=W,exports.getAppEth=U,exports.getBech32Address=K,exports.getBech32AddressFromXPub=function(e,t,s){return K(W(e,t),s)},exports.getBtcAddressFromPubKey=function(e,s){const r=t.strip0x(n.SigningKey.computePublicKey(e,!0));return K(Buffer.from(r,"hex"),s)},exports.getEVMDerivationPath=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),s=t.readUInt8(1),r=t.readUInt8(2+s),n=t.subarray(2,2+s),a=t.subarray(2+s+1,2+s+1+r);return{applicationName:n.toString("ascii"),version:a.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,s){const r=U(e),n=await r.getAddress(s??N,t,!0),a=new w;return a.publicKey=C.Buffer.from(n.publicKey,"hex"),a.chainCode=C.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,s,r){const n=k(e);if(!n)return 0;const{fee:a}=M(t,s,n,r,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,s,r="EVM"){const n=U(e),a="EVM"===r?zt(t,r,{pathSpec:s}):zt(t,r),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(l.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaDerivationPath=Gt,exports.getSolanaProvider=({isTestnet:e,rpcUrl:t})=>{const s=y.createSolanaRpc(e?y.devnet(t):y.mainnet(t));return new Proxy(s,{get:(e,t,s)=>t===$t||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,s))})},exports.getSolanaPublicKeyFromLedger=async(e,t)=>{const s=new S(t),{address:r}=await s.getAddress(Gt(e,!1));return r},exports.getTransferTxDetails=function(e,t,s,r,n){const a=M(e,t,s,r,D(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,s){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),R(t,s))},exports.getXpubFromMnemonic=async function(e){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await i.mnemonicToSeed(e);return a.fromSeed(t).derivePath(N).neutered().toBase58()},exports.isERC20Transfer=H,exports.isNativeTxn=F,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[$t],exports.maybeGetAssociatedTokenAccount=jt,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t)),{})},exports.onBalanceChange=async(e,t,s,r)=>{const n=new Set(e.map((e=>e.toLowerCase()))),a=new Set(t.map((e=>e.toLowerCase()))),i=async e=>{const t=await s.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&a.has(e.to.toLowerCase())&&H(e,n)?r(e,{type:"erc20",contractAddress:e.to}):F(e,n)&&r(e,{type:"native"})}))},o=await s.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=J,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.resolveTokenProgramForMint=Wt,exports.selectUtxos=M,exports.serializeSolanaTx=e=>y.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:s,provider:r})=>{const{value:n}=await r.getLatestBlockhash().send(),a=[A.getTransferSolInstruction({source:y.createNoopSigner(y.address(e)),destination:y.address(t),amount:s})];return y.pipe(y.createTransactionMessage({version:0}),(e=>y.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>y.setTransactionMessageFeePayer(y.address(e),t)),(e=>y.appendTransactionMessageInstructions(a,e)))},exports.transferToken=async({from:e,to:t,mint:s,amount:r,decimals:n,provider:a})=>{const i=await Wt({mint:s,provider:a}),o=String(i)===String(T.TOKEN_2022_PROGRAM_ADDRESS);const{address:d}=await jt({mint:s,owner:e,provider:a,tokenProgram:i}),{address:u,exists:c}=await jt({mint:s,owner:t,provider:a,tokenProgram:i}),l=[];c||l.push(o?T.getCreateAssociatedTokenIdempotentInstruction({payer:y.createNoopSigner(y.address(e)),mint:y.address(s),owner:y.address(t),ata:u,tokenProgram:T.TOKEN_2022_PROGRAM_ADDRESS}):b.getCreateAssociatedTokenIdempotentInstruction({payer:y.createNoopSigner(y.address(e)),mint:y.address(s),owner:y.address(t),ata:u})),l.push(o?T.getTransferCheckedInstruction({amount:r,authority:y.createNoopSigner(y.address(e)),decimals:n,mint:y.address(s),destination:u,source:d}):b.getTransferCheckedInstruction({amount:r,authority:y.createNoopSigner(y.address(e)),decimals:n,mint:y.address(s),destination:u,source:d}));const{value:p}=await a.getLatestBlockhash().send();return y.pipe(y.createTransactionMessage({version:0}),(e=>y.setTransactionMessageLifetimeUsingBlockhash(p,e)),(t=>y.setTransactionMessageFeePayer(y.address(e),t)),(e=>y.appendTransactionMessageInstructions(l,e)))};