@avalabs/core-wallets-sdk 3.1.0-canary.bc3ae2e.0 → 3.1.0-canary.bc8cd2b0

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 (180) hide show
  1. package/CHANGELOG.md +2406 -0
  2. package/dist/index.cjs +1 -0
  3. package/dist/index.d.ts +464 -355
  4. package/esm/Avalanche/index.d.ts +4 -6
  5. package/esm/Avalanche/index.js +1 -1
  6. package/esm/Avalanche/models.d.ts +69 -3
  7. package/esm/Avalanche/models.js +1 -1
  8. package/esm/Avalanche/providers/AbstractProvider.d.ts +5 -15
  9. package/esm/Avalanche/providers/AbstractProvider.js +1 -1
  10. package/esm/Avalanche/providers/JsonRpcProvider.d.ts +4 -5
  11. package/esm/Avalanche/providers/JsonRpcProvider.js +1 -1
  12. package/esm/Avalanche/providers/constants.d.ts +1 -19
  13. package/esm/Avalanche/providers/constants.js +1 -1
  14. package/esm/Avalanche/utils/addSignaturesToAvalancheTx.js +1 -1
  15. package/esm/Avalanche/utils/appendAutoRenewedValidatorConfigAddressMaps.js +1 -0
  16. package/esm/Avalanche/utils/appendDisableAuthAddressMaps.js +1 -0
  17. package/esm/Avalanche/utils/convertGlacierUtxo.d.ts +2 -1
  18. package/esm/Avalanche/utils/convertGlacierUtxo.js +1 -1
  19. package/esm/Avalanche/utils/createAvalancheEvmUnsignedTx.d.ts +3 -2
  20. package/esm/Avalanche/utils/createAvalancheEvmUnsignedTx.js +1 -1
  21. package/esm/Avalanche/utils/createAvalancheUnsignedTx.d.ts +1 -1
  22. package/esm/Avalanche/utils/createAvalancheUnsignedTx.js +1 -1
  23. package/esm/Avalanche/utils/digestMessage.d.ts +1 -1
  24. package/esm/Avalanche/utils/getAddressPublicKeyFromXpub.d.ts +1 -1
  25. package/esm/Avalanche/utils/getAssetBalance.d.ts +2 -1
  26. package/esm/Avalanche/utils/getAssetBalance.js +1 -1
  27. package/esm/Avalanche/utils/getAvalancheDerivationPath.d.ts +3 -0
  28. package/esm/Avalanche/utils/getAvalancheDerivationPath.js +1 -0
  29. package/esm/Avalanche/utils/getChainAliasByChainId.js +1 -1
  30. package/esm/Avalanche/utils/getPchainUnixNow.d.ts +3 -1
  31. package/esm/Avalanche/utils/getPchainUnixNow.js +1 -1
  32. package/esm/Avalanche/utils/getStakedAssetBalance.d.ts +2 -1
  33. package/esm/Avalanche/utils/getTxOutputAddresses.js +1 -1
  34. package/esm/Avalanche/utils/getUtxosByTxFromGlacier.d.ts +1 -2
  35. package/esm/Avalanche/utils/getUtxosByTxFromGlacier.js +1 -1
  36. package/esm/Avalanche/utils/getVmByChainAlias.d.ts +1 -1
  37. package/esm/Avalanche/utils/getXpubFromMnemonic.d.ts +1 -1
  38. package/esm/Avalanche/utils/getXpubFromMnemonic.js +1 -1
  39. package/esm/Avalanche/utils/handleSubnetAuth.js +1 -1
  40. package/esm/Avalanche/utils/orderBy.js +1 -0
  41. package/esm/Avalanche/utils/parseAvalancheTx.d.ts +6 -1
  42. package/esm/Avalanche/utils/parseAvalancheTx.js +1 -1
  43. package/esm/Avalanche/utils/parsers/index.js +1 -1
  44. package/esm/Avalanche/utils/parsers/parseAddAutoRenewedValidatorTx.js +1 -0
  45. package/esm/Avalanche/utils/parsers/parseAddPermissionlessDelegatorTx.js +1 -1
  46. package/esm/Avalanche/utils/parsers/parseAddPermissionlessValidatorTx.js +1 -1
  47. package/esm/Avalanche/utils/parsers/parseAddSubnetValidorTx.js +1 -1
  48. package/esm/Avalanche/utils/parsers/parseBaseTx.js +1 -1
  49. package/esm/Avalanche/utils/parsers/parseConvertSubnetToL1Tx.js +1 -0
  50. package/esm/Avalanche/utils/parsers/parseCreateChainTx.js +1 -1
  51. package/esm/Avalanche/utils/parsers/parseCreateSubnetTx.js +1 -1
  52. package/esm/Avalanche/utils/parsers/parseDisableL1ValidatorTx.js +1 -0
  53. package/esm/Avalanche/utils/parsers/parseExportTx.js +1 -1
  54. package/esm/Avalanche/utils/parsers/parseImportTx.js +1 -1
  55. package/esm/Avalanche/utils/parsers/parseIncreaseL1ValidatorBalanceTx.js +1 -0
  56. package/esm/Avalanche/utils/parsers/parseRegisterL1ValidatorTx.js +1 -0
  57. package/esm/Avalanche/utils/parsers/parseRemoveSubnetValidatorTx.js +1 -1
  58. package/esm/Avalanche/utils/parsers/parseSetAutoRenewedValidatorConfigTx.js +1 -0
  59. package/esm/Avalanche/utils/parsers/parseSetL1ValidatorWeightTx.js +1 -0
  60. package/esm/Avalanche/utils/parsers/parseTransferSubnetOwnershipTx.js +1 -1
  61. package/esm/Avalanche/utils/parsers/utils/chainIdToVm.js +1 -1
  62. package/esm/Avalanche/utils/populateCredential.js +1 -1
  63. package/esm/Avalanche/utils/sortUTXOs.d.ts +7 -7
  64. package/esm/Avalanche/utils/sortUTXOs.js +1 -1
  65. package/esm/Avalanche/utils/txSizeLimits.d.ts +1 -1
  66. package/esm/Avalanche/utils/txSizeLimits.js +1 -1
  67. package/esm/Avalanche/utils/verifyDerivationPath.js +1 -1
  68. package/esm/Avalanche/wallets/AddressWallet.js +1 -1
  69. package/esm/Avalanche/wallets/SimpleSigner.d.ts +1 -1
  70. package/esm/Avalanche/wallets/SimpleSigner.js +1 -1
  71. package/esm/Avalanche/wallets/StaticSigner.d.ts +2 -2
  72. package/esm/Avalanche/wallets/StaticSigner.js +1 -1
  73. package/esm/Avalanche/wallets/TxBuilderTypes.d.ts +130 -1
  74. package/esm/Avalanche/wallets/WalletAbstract.d.ts +23 -27
  75. package/esm/Avalanche/wallets/WalletAbstract.js +1 -1
  76. package/esm/Avalanche/wallets/WalletVoid.js +1 -1
  77. package/esm/Avalanche/wallets/ledger/LedgerLiveSigner.d.ts +16 -0
  78. package/esm/Avalanche/wallets/ledger/LedgerLiveSigner.js +1 -0
  79. package/esm/Avalanche/wallets/ledger/LedgerSigner.d.ts +0 -9
  80. package/esm/Avalanche/wallets/ledger/LedgerSigner.js +1 -1
  81. package/esm/Avalanche/wallets/ledger/SimpleLedgerSigner.d.ts +4 -2
  82. package/esm/Avalanche/wallets/ledger/SimpleLedgerSigner.js +1 -1
  83. package/esm/Avalanche/wallets/ledger/utils/dmkToLedgerTransport.js +1 -0
  84. package/esm/Avalanche/wallets/legacy/MnemonicWallet.js +1 -1
  85. package/esm/Avalanche/wallets/legacy/MnemonicWalletVoid.d.ts +3 -3
  86. package/esm/Avalanche/wallets/legacy/MnemonicWalletVoid.js +1 -1
  87. package/esm/Avalanche/wallets/models.d.ts +8 -5
  88. package/esm/BitcoinVM/index.d.ts +5 -0
  89. package/esm/BitcoinVM/index.js +1 -0
  90. package/esm/BitcoinVM/models.d.ts +1 -12
  91. package/esm/BitcoinVM/providers/BitcoinProvider.d.ts +3 -3
  92. package/esm/BitcoinVM/providers/BitcoinProvider.js +1 -1
  93. package/esm/BitcoinVM/utils/createPSBT.d.ts +9 -0
  94. package/esm/BitcoinVM/utils/createPSBT.js +1 -0
  95. package/esm/BitcoinVM/utils/createTransferTx.js +1 -1
  96. package/esm/BitcoinVM/utils/createWalletPolicy.d.ts +1 -1
  97. package/esm/BitcoinVM/utils/createWalletPolicy.js +1 -1
  98. package/esm/BitcoinVM/utils/ecPair.js +1 -0
  99. package/esm/BitcoinVM/utils/getBech32AddressFromXPub.js +1 -1
  100. package/esm/BitcoinVM/wallets/BitcoinWallet.d.ts +2 -1
  101. package/esm/BitcoinVM/wallets/BitcoinWallet.js +1 -1
  102. package/esm/BitcoinVM/wallets/BitcoinWalletAbstract.d.ts +6 -5
  103. package/esm/BitcoinVM/wallets/BitcoinWalletAbstract.js +1 -1
  104. package/esm/BitcoinVM/wallets/BitcoinWalletLedger.d.ts +5 -4
  105. package/esm/BitcoinVM/wallets/BitcoinWalletLedger.js +1 -1
  106. package/esm/BitcoinVM/wallets/models.d.ts +2 -2
  107. package/esm/EVM/LedgerSigner.d.ts +9 -10
  108. package/esm/EVM/LedgerSigner.js +1 -1
  109. package/esm/EVM/constants.d.ts +1 -1
  110. package/esm/EVM/utils/blockPolling.d.ts +1 -1
  111. package/esm/EVM/utils/blockPolling.js +1 -1
  112. package/esm/EVM/utils/getAddressPrivateKeyFromXPriv.d.ts +1 -1
  113. package/esm/EVM/utils/getAddressPublicKeyFromXPub.d.ts +1 -1
  114. package/esm/EVM/utils/getEvmDerivationPath.d.ts +5 -0
  115. package/esm/EVM/utils/getEvmDerivationPath.js +1 -0
  116. package/esm/EVM/utils/getWalletFromMnemonic.js +1 -1
  117. package/esm/SolanaVM/utils/compileSolanaTx.d.ts +9 -0
  118. package/esm/SolanaVM/utils/compileSolanaTx.js +1 -0
  119. package/esm/SolanaVM/utils/derivationPath.d.ts +3 -0
  120. package/esm/SolanaVM/utils/derivationPath.js +1 -0
  121. package/esm/SolanaVM/utils/deserializeSolanaTx.d.ts +6 -0
  122. package/esm/SolanaVM/utils/deserializeSolanaTx.js +1 -0
  123. package/esm/SolanaVM/utils/getSolanaPublicKeyFromLedger.d.ts +6 -0
  124. package/esm/SolanaVM/utils/getSolanaPublicKeyFromLedger.js +1 -0
  125. package/esm/SolanaVM/utils/maybeGetAssociatedTokenAccount.d.ts +40 -0
  126. package/esm/SolanaVM/utils/maybeGetAssociatedTokenAccount.js +1 -0
  127. package/esm/SolanaVM/utils/resolveTokenProgramForMint.d.ts +13 -0
  128. package/esm/SolanaVM/utils/resolveTokenProgramForMint.js +1 -0
  129. package/esm/SolanaVM/utils/serializeSolanaTx.d.ts +6 -0
  130. package/esm/SolanaVM/utils/serializeSolanaTx.js +1 -0
  131. package/esm/SolanaVM/utils/solanaProvider.d.ts +12 -0
  132. package/esm/SolanaVM/utils/solanaProvider.js +1 -0
  133. package/esm/SolanaVM/utils/transferSol.d.ts +15 -0
  134. package/esm/SolanaVM/utils/transferSol.js +1 -0
  135. package/esm/SolanaVM/utils/transferToken.d.ts +18 -0
  136. package/esm/SolanaVM/utils/transferToken.js +1 -0
  137. package/esm/SolanaVM/wallets/SolanaLedgerSigner.d.ts +9 -0
  138. package/esm/SolanaVM/wallets/SolanaLedgerSigner.js +1 -0
  139. package/esm/SolanaVM/wallets/SolanaSigner.d.ts +20 -0
  140. package/esm/SolanaVM/wallets/SolanaSigner.js +1 -0
  141. package/esm/abis/erc20.abi.js +1 -0
  142. package/esm/index.d.ts +31 -21
  143. package/esm/index.js +1 -1
  144. package/esm/utils/getAddressDerivationPath.d.ts +8 -2
  145. package/esm/utils/getAddressDerivationPath.js +1 -1
  146. package/esm/utils/getLedgerAppInfo.d.ts +2 -2
  147. package/esm/utils/getLedgerAppInfo.js +1 -1
  148. package/esm/utils/getLedgerExtendedPublicKey.d.ts +2 -2
  149. package/esm/utils/getLedgerExtendedPublicKey.js +1 -1
  150. package/esm/utils/getPubKeyFromTransport.d.ts +2 -2
  151. package/esm/utils/getPubKeyFromTransport.js +1 -1
  152. package/esm/utils/getPublicKeyFromPrivateKey.d.ts +1 -1
  153. package/esm/utils/openLedgerApp.d.ts +2 -2
  154. package/esm/utils/openLedgerApp.js +1 -1
  155. package/esm/utils/quitLedgerApp.d.ts +3 -2
  156. package/esm/utils/quitLedgerApp.js +1 -1
  157. package/package.json +47 -18
  158. package/dist/index.js +0 -1
  159. package/esm/Avalanche/utils/getUtxoInfo.d.ts +0 -13
  160. package/esm/Avalanche/utils/getUtxoInfo.js +0 -1
  161. package/esm/Avalanche/utils/parsers/parseAddDelegatorTx.js +0 -1
  162. package/esm/Avalanche/utils/parsers/parseAddValidatorTx.js +0 -1
  163. package/esm/Avalanche/utils/parsers/parseTransformSubnetTx.js +0 -1
  164. package/esm/Avalanche/wallets/ledger/ZondaxProvider.js +0 -1
  165. package/esm/Avalanche/wallets/ledger/constants.js +0 -1
  166. package/esm/Avalanche/wallets/ledger/getLedgerProvider.d.ts +0 -10
  167. package/esm/Avalanche/wallets/ledger/getLedgerProvider.js +0 -1
  168. package/esm/Avalanche/wallets/ledger/isObsidianApp.d.ts +0 -5
  169. package/esm/Avalanche/wallets/ledger/isObsidianApp.js +0 -1
  170. package/esm/Avalanche/wallets/ledger/models.d.ts +0 -37
  171. package/esm/Avalanche/wallets/legacy/LedgerWallet.d.ts +0 -41
  172. package/esm/Avalanche/wallets/legacy/LedgerWallet.js +0 -1
  173. package/esm/BitcoinVM/utils/createPSBTV2.d.ts +0 -10
  174. package/esm/BitcoinVM/utils/createPSBTV2.js +0 -1
  175. package/esm/BitcoinVM/utils/createPsbt.d.ts +0 -12
  176. package/esm/BitcoinVM/utils/createPsbt.js +0 -1
  177. package/esm/BitcoinVM/utils/psbt2ToPsbt0.d.ts +0 -15
  178. package/esm/BitcoinVM/utils/psbt2ToPsbt0.js +0 -1
  179. package/esm/EVM/utils/getAppEth.d.ts +0 -10
  180. package/esm/EVM/utils/getAppEth.js +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),s=require("coinselect"),r=require("ethers"),n=require("bip32"),a=require("bip39"),i=require("@metamask/eth-sig-util"),o=require("@avalabs/hw-app-avalanche"),d=require("@ledgerhq/device-signer-kit-bitcoin"),u=require("@bitcoinerlab/secp256k1"),c=require("ecpair"),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("@solana/kit"),w=require("@solana-program/system"),y=require("@solana-program/token"),A=require("@solana-program/token-2022"),b=require("@ledgerhq/device-signer-kit-solana"),I=require("@ledgerhq/device-management-kit"),T=require("rxjs"),S=require("@noble/curves/ed25519"),P=require("@scure/base"),B=require("micro-key-producer/slip10.js"),C=require("hdkey"),k=require("buffer");function E(e){return e&&e.__esModule?e:{default:e}}function D(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var V=E(s),M=E(o),O=D(u),U=E(m),K=E(f),_=E(x),N=E(B),R=E(C);function L(e){return e.reduce(((e,t)=>e+t.value),0)}class F{async getUtxoBalance(e,t=!0){const s=await this.getUTXOs(e,t);return{balance:L(s.confirmed),balanceUnconfirmed:L(s.unconfirmed),utxos:s.confirmed,utxosUnconfirmed:s.unconfirmed}}}function X(t,s,r,n,a,i){const o=new e.Psbt({network:r});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&&a&&i?{bip32Derivation:[{pubkey:a,masterFingerprint:n,path:i}]}:{}})})),s.forEach((e=>{o.addOutput({address:e.address,value:e.value})})),o}function H(e,t,s,r,n){const a=[{address:e,value:s}],{inputs:i,outputs:o,fee:d}=V.default(n,a,r);if(!i||!o)return{fee:d};const u=[o[0]],c=o[1];return c&&u.push({address:t,value:c.value}),{inputs:i,outputs:u,fee:d}}function $(e){const t=[];return e.filter((e=>{const s=e.txHash+e.index.toString();return!t.includes(s)&&(t.push(s),!0)}))}function q(e,t,s,r,n,a){const i=H(e,t,s,r,$(n));return i.inputs?{...i,psbt:X(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function W(t,s){return e.payments.p2wpkh({pubkey:t,network:s}).address}const j="m/44'/60'",J=`${j}/0'`;var z=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(z||{});const G=(e,t,s=!0)=>{switch(t){case z.BIP44:return`${s?"m/":""}44'/60'/0'/0/${e}`;case z.LedgerLive:return`${s?"m/":""}44'/60'/${e}'/0/0`;default:throw new Error("Invalid path spec")}};var Y=[{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 Q=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),Z=(e,t)=>{const s=new r.Interface(Y).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 ee=[{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 te extends r.JsonRpcProvider{url;constructor(e,t,s){super(t,s,{staticNetwork:s}),this.#e="string"==typeof t?new r.FetchRequest(t):void 0===t?new r.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 r.JsonRpcProvider(this.#e,s,{staticNetwork:s}),this._multicallContract=new r.Contract(e.multiContractAddress,ee,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 se(e,t){return n.fromBase58(e).derivePath(`0/${t}`).publicKey}function re(e,t){return{async send(s,r,n,a,i=Buffer.alloc(0),o=[36864]){const d=new Uint8Array(5+i.length);d.set([s,r,n,a,i.length]),d.set(i,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])}}}let ne=class e extends r.AbstractSigner{constructor(e=0,t,s,n,a){super(a),this.accountIndex=e,this.dmk=t,this.sessionId=s,this.derivationSpec=n,this.path=G(this.accountIndex,this.derivationSpec),this.accountIndex=e,this.app=new M.default(re(this.dmk,this.sessionId),{dmk:this.dmk,sessionId:this.sessionId}),r.defineProperties(this,{path:this.path,type:"default"})}type="default";path;app;async getAddress(){const e=await this.app.getETHAddress(this.path);return r.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=r.toUtf8Bytes(e));const t=await this.app.signPersonalMessage(this.path,r.hexlify(e));return t.r="0x"+t.r,t.s="0x"+t.s,r.Signature.from(t).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const s=r.Transaction.from(t),n=s.unsignedSerialized,a=await this.app.signEVMTransaction(this.path,n.slice(2));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.dmk,this.sessionId,this.derivationSpec,t)}async signTypedData(e,t,s){const{EIP712Domain:n,...a}=t,d=r.TypedDataEncoder.getPrimaryType(a);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:s});return n.r="0x"+n.r,n.s="0x"+n.s,r.Signature.from(n).serialized}catch(n){if(n instanceof o.DeviceActionError&&n.statusCode===o.LedgerError.InstructionNotSupported){const n=i.TypedDataUtils.hashStruct(d,s,t,i.SignTypedDataVersion.V4),a=i.TypedDataUtils.hashStruct("EIP712Domain",e,t,i.SignTypedDataVersion.V4),o=await this.app.signEIP712HashedMessage(this.path,a.toString("hex"),n.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,r.Signature.from(o).serialized}throw n}}};const ae=c.ECPairFactory(O);function ie(e,t,s){return ae.fromPublicKey(e).verify(t,s)}class oe{constructor(e,t){this.pubkey=e,this.provider=t;try{this.ecPair=ae.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 W(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 q(e,this.getAddressBech32(),t,s,r,this.provider.getNetwork())}}var de=(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))(de||{});const ue=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:ce,AddressMaps:le}=l.utils,pe=async({tx:e,fromAddressBytes:t,provider:s,credentials:r,utxos:n})=>{const a=ce(e);let i=le.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:he,packTx:ge}=l.utils,{publicKeyBytesToAddress:me,recoverPublicKey:fe}=l.secp256k1,xe=new l.Signature(new Uint8Array(Array(65).fill(0))),ve=(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(xe);if(!t)return r;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return r;const o=ge(n.getTx()),d=p.sha256(o),u=xe.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=fe(d,e.toBytes()),s={toHex:()=>he(me(t))},i=n.addressMaps.getSigIndicesForAddress(s,!1)??[];for(const t of i)t[0]===a&&(r[t[1]]=e)}return r};function we(e){return l.utils.bufferToHex(l.utils.addChecksum(e.toBytes()))}const{getManagerForVM:ye,hexToBuffer:Ae,unpackWithManager:be}=l.utils,Ie=async({transactionHex:e,chainAlias:t,provider:s,utxos:r})=>{const n=ue(t);if(n===l.EVM)throw new Error("EVM transactions are not supported");const a=Ae(e),i=be(n,a),o=await(async({tx:e,txBytes:t,provider:s,vm:r,utxos:n})=>{try{const a=ye(r).unpack(t,l.avaxSerial.SignedTx),i=await pe({tx:e,utxos:n,provider:s,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new l.Credential(ve(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new l.Credential(ve(e))))}})({tx:i,txBytes:a,provider:s,vm:n,utxos:r});return pe({tx:i,provider:s,credentials:o,utxos:r})},{parseBech32:Te,format:Se}=l.utils,{publicKeyBytesToAddress:Pe}=l.secp256k1;class Be{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 n=t.strip0x(r.SigningKey.computePublicKey(e,!0)),a=Buffer.from(n,"hex"),i=Pe(a);return Se(s,this.getHrp(),i)}getAddressFromBuffer(e,t){return Se(t,this.getHrp(),e)}formatAddress(e,t){const[,s]=Te(e);return Se(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=we(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 Ce={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)},ke={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:Ce},Ee={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:Ce},De={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:Ce};class Ve extends Be{constructor(e,t,s){super(e,t,s)}static async fromBaseURL(e){const t=await l.Context.getContextFromURI(e);try{return new Ve(e,t)}catch{return new Ve(e,t)}}static getDefaultMainnetProvider(e){return new Ve(g.AVALANCHE_XP_NETWORK.rpcUrl,ke,e)}static getDefaultFujiProvider(e){return new Ve(g.AVALANCHE_XP_TEST_NETWORK.rpcUrl,Ee,e)}static getDefaultDevnetProvider(e){return new Ve(g.AVALANCHE_XP_DEVNET_NETWORK.rpcUrl,De,e)}}const{bytesCompare:Me,parseBech32:Oe}=l.utils,Ue=(e,t)=>"P"===t,Ke=(e,t,s)=>{const r=Ue(0,t)?e.amount:e.asset?.amount;return new l.TransferOutput(new l.BigIntPr(BigInt(r)),l.OutputOwners.fromNative(e.addresses.map((e=>Oe(e)[1])).sort(Me),BigInt(s??0),e.threshold))},_e=(e,t)=>{const s=((e,t)=>{const s=t===h.Network.FUJI,{cBlockchainID:r,xBlockchainID:n,pBlockchainID:a}=s?Ee:ke;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=Ue(0,s)?e.txHash:e.creationTxHash,n=Ue(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)=>Ue(0,t)?e.stakeableLocktime?new l.pvmSerial.StakeableLockOut(new l.BigIntPr(BigInt(e.stakeableLocktime??0)),Ke(e,t,e.platformLocktime??0)):Ke(e,t,e.platformLocktime):Ke(e,t,e.locktime))(e,s))},{unpackWithManager:Ne,parse:Re,bufferToHex:Le,AddressMaps:Fe,AddressMap:Xe}=l.utils;function He(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 U.default("sha256").update(r).digest()}const $e=1024,qe=1024;async function We(e,t,s){const r=e.slice(0,$e),n=e.slice($e),a=await je(t,{...s,addresses:r});if(n.length){const r=await We(n,t,{...s,addresses:e});return a.merge(r)}return a}async function je(e,t){if(t.addresses.length>$e)throw new Error(`Can not get UTXOs for more than ${$e} addresses.`);const{endIndex:s,utxos:r}=await e.getUTXOs(t),n=new l.utils.UtxoSet(r);if(r.length>=qe){const r=await je(e,{...t,startIndex:s});return n.merge(r)}return n}function Je(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:ze}=l.utils;async function Ge(e,t){const s=e.slice(0,256),r=e.slice(256),n=await t.getStake({addresses:s});if(r.length){const e=await Ge(r,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Ye,hexToBuffer:Qe,unpackWithManager:Ze}=l.utils;function et(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 tt=e=>{if([ke.xBlockchainID,Ee.xBlockchainID,De.xBlockchainID].includes(e))return"AVM";if([ke.pBlockchainID,Ee.pBlockchainID,De.pBlockchainID].includes(e))return"PVM";if([ke.cBlockchainID,Ee.cBlockchainID,De.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},st=(e,t)=>e.reduce(((e,s)=>s.assetId.toString()!==t?e:e+s.output.amount()),BigInt(0)),rt=(e,t)=>e.reduce(((e,s)=>s.assetId.toString()!==t?e:e+s.input.amount()),BigInt(0));var nt={parseCreateSubnetTx:e=>l.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:s})=>({type:de.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(s.getHrp())}`)),...t}):null,parseCreateChainTx:e=>l.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:de.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=>l.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:de.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=>l.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:de.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>l.pvmSerial.isImportTx(e)||l.avmSerial.isImportTx(e)||l.evmSerial.isImportTx(e)?l.evmSerial.isImportTx(e)?({feeData:t,assetId:s})=>({type:de.Import,chain:e.getVM(),source:tt(e.sourceChain.value()),amount:rt(e.importedInputs,s),...t}):({feeData:t,assetId:s})=>({type:de.Import,chain:e.getVM(),source:tt(e.sourceChain.value()),amount:rt(e.ins,s),...t}):null,parseExportTx:e=>l.pvmSerial.isExportTx(e)||l.avmSerial.isExportTx(e)||l.evmSerial.isExportTx(e)?l.evmSerial.isExportTx(e)?({feeData:t,assetId:s})=>({type:de.Export,chain:e.getVM(),destination:tt(e.destinationChain.toString()),amount:st(e.exportedOutputs,s),...t}):({feeData:t,assetId:s})=>({type:de.Export,chain:e.getVM(),destination:tt(e.destination.value()),amount:st(e.outs,s),...t}):null,parseBaseTx:e=>l.avmSerial.isAvmBaseTx(e)||l.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:s,provider:r})=>{const n=e.baseTx,a=await(async(e,t)=>{const s=e.baseTx,r=new Set;if(s.outputs.forEach((e=>{r.add(e.assetId.value())})),l.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...r.values()].map((e=>t.getApiX().getAssetDescription(e))));return s.outputs.reduce(((s,n)=>{if(n.output instanceof l.TransferOutput){const a=n.assetId.value(),i=[...r.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...s,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return s}),[])}return s.outputs.reduce(((e,s)=>{if(s.output instanceof l.TransferOutput){const r=s.assetId.value(),n=s.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:r,amount:s.output.amount(),locktime:s.output.getLocktime(),threshold:BigInt(s.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===r}]}return e}),[])})(e,r),i=Je(),o=a.filter((e=>!(1===e.owners.length&&e.owners[0]===s&&e.locktime<=i)));return{type:de.Base,chain:e.getVM(),outputs:o,memo:K.default(Buffer.from(n.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})=>({type:de.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})},parseAddPermissionlessDelegatorTx:e=>l.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:de.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=>l.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:s})=>({type:de.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(s.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>l.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:s})=>{const r=s.getHrp(),n=e=>`P-${e.toString(r)}`;return{type:de.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}}:null,parseRegisterL1ValidatorTx:e=>l.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:de.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>l.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:de.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>l.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:de.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>l.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:de.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):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})=>({type:de.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})},parseSetAutoRenewedValidatorConfigTx:e=>l.pvmSerial.isSetAutoRenewedValidatorConfigTx(e)?({feeData:t})=>({type:de.SetAutoRenewedValidatorConfig,chain:e.getVM(),txId:e.txId.value(),autoCompoundRewardShares:e.autoCompoundRewardShares.value(),period:e.period.value(),...t}):null};const{getBurnedAmountByTx:at,getOutputAmounts:it,getInputAmounts:ot,validateBurnedAmount:dt}=l.utils;function ut(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 ct(e){const t=Je(),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=ut(r,["amount"],"desc"),i=ut(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function lt(e,t){return ut(e.map((e=>({utxo:e,...l.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const pt=e=>lt(e,!0),ht=e=>lt(e,!1);const{getUtxoInfo:gt}=l.utils;var mt=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(mt||{});const ft="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",xt="11111111111111111111111111111111LpoYY",vt=(e,t)=>e.reduce(((e,t)=>e+gt(t).amount),BigInt(0))-t,wt={BaseP:{sortFunction:pt,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]:vt(t,r.baseTxFee)},feeState:s})}},ConsolidateP:{sortFunction:ht,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext();return e.consolidateP({utxoSet:new l.utils.UtxoSet(t),amount:vt(t,r.baseTxFee),feeState:s})}},AddPermissionlessValidator:{sortFunction:ct,unsignedTxBuilder:(e,t,s)=>e.addPermissionlessValidator({utxoSet:new l.utils.UtxoSet(t),nodeId:ft,start:Je(),end:Je()+BigInt(1e3),weight:vt(t,e.getProvider().getContext().baseTxFee),subnetId:xt,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:ct,unsignedTxBuilder:(e,t,s)=>e.addPermissionlessDelegator({utxoSet:new l.utils.UtxoSet(t),nodeId:ft,start:Je(),end:Je()+BigInt(1e3),weight:vt(t,e.getProvider().getContext().baseTxFee),subnetId:xt,feeState:s})},ExportP:{sortFunction:pt,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:vt(t,a),utxoSet:new l.utils.UtxoSet(t),destination:"X",feeState:s})}},ImportP:{sortFunction:pt,unsignedTxBuilder:(e,t,s)=>e.importP({utxoSet:new l.utils.UtxoSet(t),sourceChain:"X",feeState:s})}};function yt(e){return x.validateString(e,!0)&&6===e.split("/").length}const At=(e,t=!0)=>`${t?"m/":""}44'/9000'/${e}'/0/0`;function bt(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:It,hexToBuffer:Tt}=l.utils;class St{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return We(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Ge(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 We(this.getAddresses(e),s,{sourceChain:r,addresses:[]})}exportX(e,t,s,r){r=r||this.getCurrentAddress(s);const n=It(r)[2],a=this.provider.getAvaxID(),i=l.TransferableOutput.fromNative(a,e,[n]),o=lt(t.getUTXOs(),!0),d=this.provider.getChainID(s),u=this.getAddresses("X").map((e=>It(e)[2])),c=It(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=>It(e)[2]));It(this.getChangeAddress("P"))[2],s=s||this.getCurrentAddress("P");const d=It(s)[2],u=e.getUTXOs();return bt(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=>It(e)[2])),a=It(this.getChangeAddress("X"))[2];s=s||this.getCurrentAddress("X");const i=It(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=>It(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=Tt(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=It(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=It(n)[2],i=this.provider.getAvaxID(),o=l.TransferableOutput.fromNative(i,e,[a]),d=lt(t.getUTXOs(),!0),u=this.provider.getChainID(s),c=this.getAddresses("P").map((e=>It(e)[2])),p=It(this.getChangeAddress("P"))[2];return bt(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=ht(e.getUTXOs());r=r??this.getCurrentAddress("P");const i=It(r)[2],o=this.provider.getContext(),d=[l.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>It(e)[2])),c=It(this.getChangeAddress("P"))[2],p=n?.changeAddresses??[c];return bt(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]=It(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=lt(e.getUTXOs(),!0),h=(i??this.getAddresses(t)).map((e=>It(e)[2])),g=It(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?l.avm.newBaseTx(this.provider.getContext(),h,p,c,a):(bt(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=>It(e)[2])),c=It(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=>It(e)[2])),i.threshold??1),u=l.PChainOwner.fromNative(a.addresses.map((e=>It(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:It(a)[2],chainId:t,subnetId:s,subnetAuth:r,feeState:n,utxos:lt(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=>It(e)[2])),d=It(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return l.pvm.newRegisterL1ValidatorTx({utxos:lt(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=>It(e)[2])),i=It(this.getChangeAddress("P"))[2],o=r?.changeAddresses??[i];return l.pvm.newSetL1ValidatorWeightTx({utxos:lt(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=>It(e)[2])),o=It(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return l.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:lt(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=>It(e)[2])),o=It(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return l.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:lt(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=ct(e.getUTXOs()),v=(a??this.getAddresses("P")).map((e=>It(e)[2])),w=(i??[this.getCurrentAddress("P")]).map((e=>It(e)[2])),y=(o??[this.getCurrentAddress("P")]).map((e=>It(e)[2])),A=(d??[this.getCurrentAddress("P")]).map((e=>It(e)[2])),b=It(this.getChangeAddress("P"))[2],I=g?.changeAddresses??[b];return l.pvm.newAddAutoRenewedValidatorTx({fromAddressesBytes:v,delegatorRewardsOwner:y,utxos:x,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:I,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=>It(e)[2])),u=It(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[u];return l.pvm.newSetAutoRenewedValidatorConfigTx({utxos:lt(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=lt(e.getUTXOs(),!0),p=(u??this.getAddresses("P")).map((e=>It(e)[2])),h=It(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[h];return bt(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=lt(e.getUTXOs(),!0),d=(r??this.getAddresses("P")).map((e=>It(e)[2])),u=It(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],p=t.map((e=>It(e)[2]));return bt(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=lt(e.getUTXOs(),!0),p=(d??this.getAddresses("P")).map((e=>It(e)[2])),h=It(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[h];return bt(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=ct(e.getUTXOs()),w=(d??this.getAddresses("P")).map((e=>It(e)[2])),y=(u??[this.getCurrentAddress("P")]).map((e=>It(e)[2])),A=(c??[this.getCurrentAddress("P")]).map((e=>It(e)[2]));if(!(a!==l.networkIDs.PrimaryNetworkID.toString()||p&&h))throw new Error("Must provide public key and signature for primary subnet.");const b=It(this.getChangeAddress("P"))[2],I=g?.changeAddresses??[b];return bt(o),l.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:A,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:I,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=ct(e.getUTXOs()),f=(i??this.getAddresses("P")).map((e=>It(e)[2])),x=(o??[this.getCurrentAddress("P")]).map((e=>It(e)[2])),v=It(this.getChangeAddress("P"))[2],w=d?.changeAddresses??[v],y=this.provider.getContext();return bt(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=>It(e)[2])),e.locktime,e.threshold)))},y)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:s,subnetAuth:r,fromAddresses:n,feeState:a,options:i}){const o=lt(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>It(e)[2])),u=It(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return bt(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=lt(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>It(e)[2])),p=It(this.getChangeAddress("P"))[2],h=i?.changeAddresses??[p],g=r.map((e=>It(e)[2]));return bt(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 Pt extends St{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,n){const a=t.strip0x(r.SigningKey.computePublicKey(e,!0)),i=t.strip0x(r.SigningKey.computePublicKey(s,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new Pt(o,d,n)}static fromMnemonic(e,t,s,r){if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!yt(s)||!yt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const i=a.mnemonicToSeedSync(e),o=n.fromSeed(i),d=o.derivePath(s),u=o.derivePath(t);return Pt.fromPublicKey(u.publicKey,d.publicKey,r)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return r.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:Bt}=l.utils;class Ct extends St{constructor(e,t,s){super(s),this.avmXpub=e,this.accountNode=n.fromBase58(e),this.evmWallet=new Pt(t,t,s)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=a.mnemonicToSeedSync(e),r=n.fromSeed(s),i=r.derivePath("m/44'/9000'/0'").neutered(),o=r.derivePath(G(0,z.BIP44)).neutered();return new Ct(i.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(Bt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(Bt(e)[2])))}getRawAddressC(){return Buffer.from(Bt(this.getCurrentAddress("C"))[2])}}const{strip0x:kt}=l.utils;class Et extends Ct{constructor(e,t,s){const a=n.fromBase58(e).neutered(),i=new r.SigningKey(t),o=Buffer.from(kt(i.compressedPublicKey),"hex");super(a.toBase58(),o,s),this.evmPrivKey=t,this.accountNode=n.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=a.mnemonicToSeedSync(e),r=n.fromSeed(s),i=r.derivePath("m/44'/9000'/0'"),o=r.derivePath(Yt(0,"EVM",{pathSpec:z.BIP44}));if(!o.privateKey)throw new Error("Unable to derive EVM private key.");return new Et(i.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:Vt,signHash:Mt}=l.secp256k1,{addChecksum:Ot}=l.utils;class Ut extends Pt{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(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!yt(s)||!yt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const i=a.mnemonicToSeedSync(e),o=n.fromSeed(i),d=o.derivePath(t),u=o.derivePath(s);if(!d.privateKey||!u.privateKey)throw new Error("Failed to generate private keys.");return new Ut(d.privateKey,u.privateKey,r)}async signMessage(e){const t=He(e.message),s=this.getSigningKey(e.chain);return Buffer.from(Ot(await Mt(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 Vt(e.buffer,t))]}}const{isTransferOut:Kt,isStakeableLockOut:_t}=l.utils;function Nt(e){const t=e.output;return Kt(t)||_t(t)?t.getOwners():[]}function Rt(e){const t=e.getTx();return l.avmSerial.isExportTx(t)||l.pvmSerial.isExportTx(t)?new Set(t.outs.map(Nt).flat()):l.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(Nt).flat()):new Set((t.baseTx?.outputs??[]).map(Nt).flat())}const{parse:Lt}=l.utils;const Ft={C:60,X:9e3,P:9e3};var Xt=Object.freeze({__proto__:null,AbstractProvider:Be,AddressWallet:class extends St{constructor(e,t,s,n,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=s,this.xpChangeAddress=n,s.length<1)throw new Error("Must have at least 1 xp address.");if(!r.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(s.some((e=>!et(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!et(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(!et(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:De,FujiContext:Ee,JsonRpcProvider:Ve,LedgerLiveSigner:class{constructor(e){this.accountIndices=e}#s(e){return`m/44'/${Ft[e]}'`}#r(e,t){return`${this.#s(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=_.default.fromString(this.#r(e.chain,this.accountIndices[0])),s=_.default.fromString("0/0"),r=He(e.message),n=new M.default(re(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId}),a=await n.signHash(t.toString(),[s].map((e=>e.toString(!0))),r),i=a.signatures?.get(s.toString(!0));if(!i)throw new Error("Failed to sign message.");return i}async signTx(e){if(!e.dmk||!e.sessionId)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=_.default.fromString(this.#r(n,s));(await this.#n(a,{buffer:r,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 s=new M.default(re(t.dmk,t.sessionId),{dmk:t.dmk,sessionId:t.sessionId});return[...((await s.sign(e.toString(),(t.signers??[_.default.fromString("0/0")]).map((e=>e.toString(!0))),t.buffer,(t.change??[_.default.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=_.default.fromString(this.#r(e.chain,this.accountIndices[0]));return this.#n(t,e)}},LedgerSigner:class extends Pt{constructor(e,t,s,n,a){const i=l.utils.strip0x(r.SigningKey.computePublicKey(new Uint8Array(e),!0)),o=l.utils.strip0x(r.SigningKey.computePublicKey(new Uint8Array(s),!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=n,!yt(t)||!yt(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=_.default.fromString(this.getAccountPath(e.chain)),s=_.default.fromString(this.getPartialSignerPath(e.chain)),r=He(e.message),n=new M.default(re(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId}),a=await n.signHash(t.toString(),[s].map((e=>e.toString(!0))),r),i=a.signatures?.get(s.toString(!0));if(!i)throw new Error("Failed to sign message.");return i}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,s=t.getVM(),r=Buffer.from(t.toBytes()),n="EVM"===s?"C":"X";return(await this.signTxBuffer({buffer:r,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=_.default.fromString(this.getAccountPath(e.chain)),s=_.default.fromString(this.getPartialSignerPath(e.chain)),r=new M.default(re(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId});return[...((await r.sign(t.toString(),[s].map((e=>e.toString(!0))),e.buffer,[s].map((e=>e.toString(!0))))).signatures??new Map).values()]}},MainnetContext:ke,MnemonicWallet:Et,MnemonicWalletVoid:Ct,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,s,r=z.BIP44){this.activeAccountIndex=e,this.provider=t,this.pathSpec=r,s&&(this.accountNode=n.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===z.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(Lt(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===z.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?[_.default.fromString("C"===s?`0/${this.pathSpec===z.LedgerLive?0:this.activeAccountIndex}`:"0/0")]:e.reduce(((e,s)=>{const r=t.get(Buffer.from(s).toString("hex"));return r&&e.push(_.default.fromString(r)),e}),[])}async signTx(e){if(!e.dmk||!e.sessionId)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([...Rt(s)],n,t);return(await this.signTxBuffer({buffer:r,chain:t,dmk:e.dmk,sessionId:e.sessionId,signers:a,change:i})).forEach((e=>{s.addSignature(new Uint8Array(e))})),s}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||[],s=_.default.fromString(this.getAccountPath(e.chain)),r=new M.default(re(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId});return[...((await r.sign(s.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,s=e.signer||_.default.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=He(e.message),n=new M.default(re(e.dmk,e.sessionId),{dmk:e.dmk,sessionId:e.sessionId}),a=await n.signHash(this.getAccountPath(e.chain),[s].map((e=>e.toString(!0))),r),i=a.signatures?.get(s.toString(!0));if(!i)throw new Error("Failed to sign message.");return i}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const s=a.mnemonicToSeedSync(e),r=n.fromSeed(s);this.accountNodeXP=r.derivePath(`m/44'/9000'/${t}'`);const i=r.derivePath(Yt(t,"EVM",{pathSpec:z.BIP44}));this.signerNodeEVM=i,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=He(e.message),r=await l.secp256k1.signHash(s,t.privateKey);return Buffer.from(r)}},SizeSupportedTx:mt,StaticSigner:Ut,TxType:de,WalletAbstract:St,WalletVoid:Pt,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 Ie({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:we(new l.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:_e,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:s,credentials:r,utxos:n})=>{const a=Ne(s,e),i=Re(t)[2],o=Le(i);if(l.evmSerial.isExportTx(a))return new l.EVMUnsignedTx(a,[],new Fe([Xe.fromJSON([[o,0]])]),r);if(l.evmSerial.isImportTx(a)){const e=Fe.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:pe,digestMessage:He,emptySignature:xe,getAddressFromXpub:function(e,t,s,r,a=!1){if(t<0)throw new Error("Account index must be >= 0");const i=a?"1":"0",o=n.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 n.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=Je();return n.forEach((e=>{const t=ze(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:At,getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:s,limit:r=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=wt[s],o=Je(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:r}=gt(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*gt(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(gt)}),r+1}}),r);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:je,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:Ge,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:We,getUnixNow:Je,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:s,url:r,token:n,headers:a})=>{const i=ue(t),o=Qe(e),d=Ze(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=Ye(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=_e(n,s);return e.push(a),e}),[])},getVmByChainAlias:ue,getXpubFromMnemonic:function(e,t){if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=a.mnemonicToSeedSync(e);return n.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:et,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,s,{feeTolerance:r=50,baseFee:n}={}){const a=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(nt)){const s=t(e);if(null!==s)return s}throw new Error("no parser found for tx")})(i),d=at(i,a),u=it(i),c=ot(i).get(a.avaxAssetID)??BigInt(0),p=d.get(a.avaxAssetID)??BigInt(0),h=u.get(a.avaxAssetID)??BigInt(0);let g=n;void 0===g&&(g=0n,l.evmSerial.isImportExportTx(i)?(g=await t.getApiC().getBaseFee()/BigInt(1e9),0n===g&&(g=1n)):"PVM"===i.vm&&(g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0)))));const{isValid:m,txFee:f}=dt({unsignedTx:e,context:a,burnedAmount:p,baseFee:g,feeTolerance:r});return await o({feeData:{totalAvaxBurned:p,totalAvaxOutput:h,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f,baseFee:g},assetId:a.avaxAssetID,provider:t,currentAddress:s})},populateCredential:ve,signedTxToHex:we,sortUTXOsByAmount:lt,sortUTXOsByAmountAscending:ht,sortUTXOsByAmountDescending:pt,sortUTXOsStaking:ct,verifyDerivationPath:yt});const Ht=(e,t)=>{const s=v.getTransactionDecoder().decode(v.getBase64Encoder().encode(e)),r=v.getCompiledTransactionMessageDecoder().decode(s.messageBytes);return v.decompileTransactionMessageFetchingLookupTables(r,t)},$t=Symbol(),qt=({isTestnet:e,rpcUrl:t})=>{const s=v.createSolanaRpc(e?v.devnet(t):v.mainnet(t));return new Proxy(s,{get:(e,t,s)=>t===$t||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,s))})},Wt=(e,t)=>String(e)===String(t),jt=async({mint:e,provider:t})=>{const s=v.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(Wt(n,y.TOKEN_PROGRAM_ADDRESS))return y.TOKEN_PROGRAM_ADDRESS;if(Wt(n,A.TOKEN_2022_PROGRAM_ADDRESS))return A.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 jt({mint:e,provider:s}),[a]=await y.findAssociatedTokenPda({mint:v.address(e),owner:v.address(t),tokenProgram:n}),i=await s.getAccountInfo(a,{encoding:"base64"}).send();return{address:a,exists:Boolean(i.value),info:i}},zt=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class Gt{#a;#i;constructor(e){this.#a=Uint8Array.from(e),this.#i=v.address(P.base58.encode(S.ed25519.getPublicKey(this.#a)))}static fromMnemonic(e,t){const s=a.mnemonicToSeedSync(e),r=N.default.fromMasterSeed(Uint8Array.from(s)).derive(`m/44'/501'/${t}'/0'`);return new Gt(Buffer.from(r.privateKey))}#o(e){try{return v.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(S.ed25519.sign(t,this.#a))}async signTx(e,t){const s=await Ht(e,t),{signatures:r,messageBytes:n,...a}=v.compileTransaction(s);if(!this.#d(r))return e;const i=P.base58.encode(S.ed25519.sign(Uint8Array.from(n),this.#a));return v.assertIsSignature(i),v.getBase64EncodedWireTransaction({...a,messageBytes:n,signatures:{...r,[this.#i]:P.base58.decode(i)}})}#d(e){return this.#i in e&&!e[this.#i]}}function Yt(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 G(e,s.pathSpec,s.withRoot);case"AVM":case"PVM":return At(e,s.withRoot);case"SVM":return zt(e,s.withRoot);default:throw new Error(`Unknown derivation path for VM: ${t}`)}}class Qt extends oe{keypair;constructor(e,t){const s=ae.fromPrivateKey(e);super(s.publicKey,t),this.keypair=s}static async fromMnemonic(e,t,s,r=z.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const i=await a.mnemonicToSeed(e),o=n.fromSeed(i),d=Yt(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 Qt(u.privateKey,s)}signTx(e,t){const s=X(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 Qt(r,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(ie),e.finalizeAllInputs(),e.extractTransaction()}}const Zt=e.networks;exports.Avalanche=Xt,exports.BitcoinLedgerWallet=class extends oe{constructor(e,t,s,r,n,a){super(e,s),this.derivationPath=t,this.dmk=r,this.sessionId=n,this.walletPolicyDetails=a}setTransport(e,t){this.dmk=e,this.sessionId=t}async signTx(e,t){const s=(r=this.dmk,n=this.sessionId,new d.SignerBtcBuilder({dmk:r,sessionId:n}).build());var r,n;const a=this.ecPair.publicKey,i=this.provider.getNetwork(),o=await s.getMasterFingerprint({skipOpenApp:!0}),u=await T.lastValueFrom(o.observable);if(u.status!==I.DeviceActionStatus.Completed)throw new Error("Failed to get master fingerprint");const c=X(e,t,i,Buffer.from(u.output.masterFingerprint),a,this.derivationPath),l=await s.signPsbt(new d.RegisteredWallet(this.walletPolicyDetails.policy.name,this.walletPolicyDetails.policy.descriptorTemplate,[...this.walletPolicyDetails.policy.keys],this.walletPolicyDetails.hmac),c,{skipOpenApp:!0}),p=await T.lastValueFrom(l.observable);if(p.status!==I.DeviceActionStatus.Completed)throw new Error("Failed to get signatures");if(p.output.forEach((e=>{"signature"in e&&c.updateInput(e.inputIndex,{partialSig:[{signature:Buffer.from(e.signature),pubkey:Buffer.from(e.pubkey)}]})})),!c.validateSignaturesOfAllInputs(ie))throw new Error("Failed to validate signatures");return c.finalizeAllInputs(),c.extractTransaction()}},exports.BitcoinProvider=class extends F{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=F,exports.BitcoinWallet=Qt,exports.BitcoinWalletAbstract=oe,exports.BitcoinWalletVoid=class extends oe{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=Zt,exports.DerivationPath=z,exports.ETH_ACCOUNT_PATH=J,exports.ETH_COIN_PATH=j,exports.JsonRpcBatchInternal=te,exports.LedgerSigner=ne,exports.SolanaLedgerSigner=class{#p;#h;#g;constructor(e,t,s){this.#p=zt(e,!1),this.#h=t,this.#g=s}async signTx(e,t,s){const r=await Ht(e,qt({rpcUrl:t,isTestnet:s})),{signatures:n,messageBytes:a,...i}=v.compileTransaction(r),o=new b.SignerSolanaBuilder({dmk:this.#h,sessionId:this.#g,solanaRPCURL:t}).build(),{observable:d}=await o.getAddress(this.#p),u=await T.lastValueFrom(d);if(u.status!==I.DeviceActionStatus.Completed)throw new Error("Failed to get address");const c=v.address(u.output);if(!this.#d(c,n))return e;const l=await o.signTransaction(this.#p,Buffer.from(a)),p=await T.lastValueFrom(l.observable);if(p.status!==I.DeviceActionStatus.Completed)throw new Error("Failed to sign transaction");const h=P.base58.encode(Uint8Array.from(p.output));return v.assertIsSignature(h),v.getBase64EncodedWireTransaction({...i,messageBytes:a,signatures:{...n,[c]:P.base58.decode(h)}})}#d(e,t){return e in t&&!t[e]}},exports.SolanaSigner=Gt,exports.addEncodedSigToPsbt=function(e,t,s,r){const n=[{pubkey:t,signature:e}];s.updateInput(r,{partialSig:n})},exports.compileSolanaTx=e=>v.compileTransaction(e),exports.createPSBT=X,exports.createTransferTx=q,exports.createWalletPolicy=function(e,t,s,r){return new d.WalletPolicy(r,"wpkh(@0/**)",[`[${e}/44'/60'/${t}']${s}`])},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=Yt,exports.getAddressFromXPub=function(e,t){const s=se(e,t);return r.computeAddress(`0x${s.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const s=n.fromBase58(e).derivePath(`0/${t}`);if(!s.privateKey)throw new Error("Unable to derive private key.");return s.privateKey},exports.getAddressPublicKeyFromXPub=se,exports.getBech32Address=W,exports.getBech32AddressFromXPub=function(e,t,s){return W(se(e,t),s)},exports.getBtcAddressFromPubKey=function(e,s){const n=t.strip0x(r.SigningKey.computePublicKey(e,!0));return W(Buffer.from(n,"hex"),s)},exports.getEVMDerivationPath=G,exports.getEvmAddressFromPubKey=function(e){return r.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e,t){const s=await e.sendApdu({sessionId:t,apdu:new Uint8Array([176,1,0,0])}),r=Buffer.from(s.data),n=r.readUInt8(1),a=r.readUInt8(2+n),i=r.subarray(2,2+n),o=r.subarray(2+n+1,2+n+1+a);return{applicationName:i.toString("ascii"),version:o.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t,s=!1,r){const n=new M.default(re(e,t),{dmk:e,sessionId:t}),a=await n.getETHAddress(r??J,s,!0),i=new R.default;return i.publicKey=k.Buffer.from(a.publicKey,"hex"),i.chainCode=k.Buffer.from(a.chainCode,"hex"),i.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,s,r){const n=L(e);if(!n)return 0;const{fee:a}=H(t,s,n,r,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,s,r,n="EVM"){const a=new M.default(re(e,t),{dmk:e,sessionId:t}),i="EVM"===n?Yt(s,n,{pathSpec:r}):Yt(s,n),o=await a.getETHAddress(i,!1,!1);return Buffer.from(o.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=zt,exports.getSolanaProvider=qt,exports.getSolanaPublicKeyFromLedger=async(e,t,s,r)=>{const n=new b.SignerSolanaBuilder({dmk:t,sessionId:s,solanaRPCURL:r}).build(),{observable:a}=await n.getAddress(zt(e,!1)),i=await T.lastValueFrom(a);if(i.status!==I.DeviceActionStatus.Completed)throw new Error("Failed to get address");return v.address(i.output)},exports.getTransferTxDetails=function(e,t,s,r,n){const a=H(e,t,s,r,$(n));return a.inputs||console.log("Unable to construct transaction, fee needed: ",a.fee),a},exports.getVoidSigner=function(e,t){return new r.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 r.HDNodeWallet.fromMnemonic(r.Mnemonic.fromPhrase(e),G(t,s))},exports.getXpubFromMnemonic=async function(e){if(!a.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await a.mnemonicToSeed(e);return n.fromSeed(t).derivePath(J).neutered().toBase58()},exports.isERC20Transfer=Z,exports.isNativeTxn=Q,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())&&Z(e,n)?r(e,{type:"erc20",contractAddress:e.to}):Q(e,n)&&r(e,{type:"native"})}))},o=await s.on("block",i);return{unsubscribe:()=>o.off("block",i)}},exports.openLedgerApp=async function(e,t,s){try{const r=await e.sendApdu({sessionId:t,apdu:new Uint8Array([224,216,0,0,...Buffer.from(s,"ascii")])});return Buffer.from(r.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=jt,exports.selectUtxos=H,exports.serializeSolanaTx=e=>v.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:s,provider:r})=>{const{value:n}=await r.getLatestBlockhash().send(),a=[w.getTransferSolInstruction({source:v.createNoopSigner(v.address(e)),destination:v.address(t),amount:s})];return v.pipe(v.createTransactionMessage({version:0}),(e=>v.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>v.setTransactionMessageFeePayer(v.address(e),t)),(e=>v.appendTransactionMessageInstructions(a,e)))},exports.transferToken=async({from:e,to:t,mint:s,amount:r,decimals:n,provider:a})=>{const i=await jt({mint:s,provider:a}),o=String(i)===String(A.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?A.getCreateAssociatedTokenIdempotentInstruction({payer:v.createNoopSigner(v.address(e)),mint:v.address(s),owner:v.address(t),ata:u,tokenProgram:A.TOKEN_2022_PROGRAM_ADDRESS}):y.getCreateAssociatedTokenIdempotentInstruction({payer:v.createNoopSigner(v.address(e)),mint:v.address(s),owner:v.address(t),ata:u})),l.push(o?A.getTransferCheckedInstruction({amount:r,authority:v.createNoopSigner(v.address(e)),decimals:n,mint:v.address(s),destination:u,source:d}):y.getTransferCheckedInstruction({amount:r,authority:v.createNoopSigner(v.address(e)),decimals:n,mint:v.address(s),destination:u,source:d}));const{value:p}=await a.getLatestBlockhash().send();return v.pipe(v.createTransactionMessage({version:0}),(e=>v.setTransactionMessageLifetimeUsingBlockhash(p,e)),(t=>v.setTransactionMessageFeePayer(v.address(e),t)),(e=>v.appendTransactionMessageInstructions(l,e)))};