@avalabs/core-wallets-sdk 3.1.0-alpha.68 → 3.1.0-alpha.69

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 (30) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.ts +19 -11
  3. package/esm/Avalanche/index.d.ts +1 -0
  4. package/esm/Avalanche/index.js +1 -1
  5. package/esm/Avalanche/utils/getAvalancheDerivationPath.d.ts +3 -0
  6. package/esm/Avalanche/utils/getAvalancheDerivationPath.js +1 -0
  7. package/esm/Avalanche/utils/getVmByChainAlias.d.ts +1 -1
  8. package/esm/Avalanche/utils/getXpubFromMnemonic.d.ts +1 -1
  9. package/esm/Avalanche/utils/getXpubFromMnemonic.js +1 -1
  10. package/esm/Avalanche/wallets/SimpleSigner.d.ts +1 -1
  11. package/esm/Avalanche/wallets/SimpleSigner.js +1 -1
  12. package/esm/Avalanche/wallets/ledger/SimpleLedgerSigner.d.ts +1 -1
  13. package/esm/Avalanche/wallets/ledger/SimpleLedgerSigner.js +1 -1
  14. package/esm/Avalanche/wallets/legacy/LedgerWallet.js +1 -1
  15. package/esm/Avalanche/wallets/legacy/MnemonicWallet.js +1 -1
  16. package/esm/Avalanche/wallets/legacy/MnemonicWalletVoid.js +1 -1
  17. package/esm/BitcoinVM/index.js +1 -1
  18. package/esm/BitcoinVM/utils/getBech32AddressFromXPub.js +1 -1
  19. package/esm/BitcoinVM/wallets/BitcoinWallet.js +1 -1
  20. package/esm/BitcoinVM/wallets/BitcoinWalletLedger.js +1 -1
  21. package/esm/EVM/LedgerSigner.js +1 -1
  22. package/esm/EVM/utils/getEvmDerivationPath.d.ts +5 -0
  23. package/esm/EVM/utils/getEvmDerivationPath.js +1 -0
  24. package/esm/EVM/utils/getWalletFromMnemonic.js +1 -1
  25. package/esm/index.d.ts +1 -0
  26. package/esm/index.js +1 -1
  27. package/esm/utils/getAddressDerivationPath.d.ts +8 -5
  28. package/esm/utils/getAddressDerivationPath.js +1 -1
  29. package/esm/utils/getPubKeyFromTransport.js +1 -1
  30. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@solana/kit"),i=require("@solana-program/system"),o=require("@solana-program/token"),d=require("@ledgerhq/hw-app-solana"),u=require("bip39"),c=require("@noble/curves/ed25519"),l=require("@scure/base"),p=require("micro-key-producer/slip10.js"),h=require("@avalabs/avalanchejs"),g=require("hdkey"),m=require("bip32"),f=require("@ledgerhq/hw-transport"),x=require("@metamask/eth-sig-util"),v=require("ledger-bitcoin"),y=require("@ledgerhq/hw-app-btc/lib/bip32"),w=require("@noble/hashes/sha256"),b=require("@avalabs/glacier-sdk"),A=require("@avalabs/core-chains-sdk"),T=require("create-hash"),I=require("xss"),S=require("bip32-path"),P=require("@avalabs/hw-app-avalanche"),B=require("buffer");function C(e){return e.reduce(((e,t)=>e+t.value),0)}class k{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:C(r.confirmed),balanceUnconfirmed:C(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function E(t,r,s){const n=new e.Psbt({network:s});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),r.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function M(e,t,s,n,a){const i=[{address:e,value:s}],{inputs:o,outputs:d,fee:u}=r(a,i,n);if(!o||!d)return{fee:u};const c=[d[0]],l=d[1];return l&&c.push({address:t,value:l.value}),{inputs:o,outputs:c,fee:u}}function D(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function V(e,t,r,s,n,a){const i=M(e,t,r,s,D(n));return i.inputs?{...i,psbt:E(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function K(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function O(e){return new s(e,"w0w")}const U=(e,t)=>{const r=a.getTransactionDecoder().decode(a.getBase64Encoder().encode(e)),s=a.getCompiledTransactionMessageDecoder().decode(r.messageBytes);return a.decompileTransactionMessageFetchingLookupTables(s,t)},N=Symbol(),_=async({mint:e,owner:t,provider:r})=>{const[s]=await o.findAssociatedTokenPda({mint:a.address(e),owner:a.address(t),tokenProgram:o.TOKEN_PROGRAM_ADDRESS}),n=await r.getAccountInfo(s,{encoding:"base64"}).send();return{address:s,exists:Boolean(n.value),info:n}},L=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class X{#e;#t;constructor(e){this.#e=Uint8Array.from(e),this.#t=a.address(l.base58.encode(c.ed25519.getPublicKey(this.#e)))}static fromMnemonic(e,t){const r=u.mnemonicToSeedSync(e),s=p.fromMasterSeed(Uint8Array.from(r)).derive(`m/44'/501'/${t}'/0'`);return new X(Buffer.from(s.privateKey))}#r(e){try{return a.getCompiledTransactionMessageDecoder().decode(e),!0}catch{return!1}}async signMessage(e){const t=l.base64.decode(e);if(this.#r(t))throw new Error("Cannot use signMessage() to sign transactions!");return l.base64.encode(c.ed25519.sign(t,this.#e))}async signTx(e,t){const r=await U(e,t),{signatures:s,messageBytes:n,...i}=a.compileTransaction(r);if(!this.#s(s))return e;const o=l.base58.encode(c.ed25519.sign(Uint8Array.from(n),this.#e));return a.assertIsSignature(o),a.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...s,[this.#t]:l.base58.decode(o)}})}#s(e){return this.#t in e&&!e[this.#t]}}const F="m/44'/60'",H=`${F}/0'`;var q=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(q||{});function $(e,t,r,s=!0){if(e<0)throw new Error("Account index can not be less than 0.");if("SVM"===r)return L(e,s);const n="EVM"===r?"60":"9000";return t==q.BIP44?`m/44'/${n}'/0'/0/${e}`:`m/44'/${n}'/${e}'/0/0`}var R=[{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 W=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),j=(e,t)=>{const r=new n.Interface(R).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var J=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"}];class z extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#n="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#n.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#n,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,J,this._parentProvider),this._maxCalls=62)}#n;#a=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#a++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#n.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function G(e,t){return m.fromBase58(e).derivePath(`0/${t}`).publicKey}let Y=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=$(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=O(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=O(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,a=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof f.TransportStatusError&&s.statusCode===f.StatusCodes.INS_NOT_SUPPORTED){const s=x.TypedDataUtils.hashStruct(i,r,t,x.SignTypedDataVersion.V4),a=x.TypedDataUtils.hashStruct("EIP712Domain",e,t,x.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function Q(t,r,s,n,a,i){const o=new v.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,y.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function Z(t,r,s,n){const a=new e.Psbt({network:r}),i=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<i;e++){const r=t.getInputWitnessUtxo(e),i=t.getInputBip32Derivation(e,s);a.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:i?[{path:n,pubkey:s,masterFingerprint:i.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)a.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return a}class ee{constructor(t,r){this.pubkey=t,this.provider=r;try{this.ecPair=e.ECPair.fromPublicKey(t)}catch(e){throw new Error("Not a valid public key.")}}ecPair;getAddressP2PKH(){return e.payments.p2pkh({pubkey:this.ecPair.publicKey,network:this.provider.getNetwork()}).address}getAddressBech32(){return K(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,r,s){return V(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class te extends ee{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=q.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await u.mnemonicToSeed(e),a=m.fromSeed(n),i=$(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new te(o.privateKey,r)}signTx(e,t){const r=E(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(r))}static fromEthersWallet(e,t){const r=e.privateKey;if(!r)throw new Error("Unable to get private key from ethers wallet.");const s=Buffer.from(r.substring(2),"hex");return new te(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}const re=e.networks;var se=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.ConvertSubnetToL1="convert_subnet_to_l1",e.RegisterL1Validator="register_l1_validator",e.SetL1ValidatorWeight="set_l1_validator_weight",e.IncreaseL1ValidatorBalance="increase_l1_validator_balance",e.DisableL1Validator="disable_l1_validator",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))(se||{});const ne=e=>{switch(e){case"C":return h.EVM;case"X":return h.AVM;case"P":return h.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:ae,AddressMaps:ie}=h.utils,oe=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=ae(e);let i=ie.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>h.pvmSerial.isCreateChainTx(e)||h.pvmSerial.isAddSubnetValidatorTx(e)||h.pvmSerial.isRemoveSubnetValidatorTx(e)||h.pvmSerial.isTransformSubnetTx(e)||h.pvmSerial.isTransferSubnetOwnershipTx(e)||h.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),a=h.OutputOwners.fromNative(n.controlKeys.map((e=>h.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new h.utils.AddressMap(a)),r})({tx:e,provider:r,addressMaps:i});return new h.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else h.pvmSerial.isDisableL1ValidatorTx(e)&&(i=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),a=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new h.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(i,e,r));return new h.UnsignedTx(e,n,i,s)},{bufferToHex:de,packTx:ue}=h.utils,{publicKeyBytesToAddress:ce,recoverPublicKey:le}=h.secp256k1,pe=new h.Signature(new Uint8Array(Array(65).fill(0))),he=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(pe);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=ue(n.getTx()),d=w.sha256(o),u=pe.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=le(d,e.toBytes()),r={toHex:()=>de(ce(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function ge(e){return h.utils.bufferToHex(h.utils.addChecksum(e.toBytes()))}const{getManagerForVM:me,hexToBuffer:fe,unpackWithManager:xe}=h.utils,ve=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=ne(t);if(n===h.EVM)throw new Error("EVM transactions are not supported");const a=fe(e),i=xe(n,a),o=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=me(s).unpack(t,h.avaxSerial.SignedTx),i=await oe({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new h.Credential(he(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new h.Credential(he(e))))}})({tx:i,txBytes:a,provider:r,vm:n,utxos:s});return oe({tx:i,provider:r,credentials:o,utxos:s})},{parseBech32:ye,format:we}=h.utils,{publicKeyBytesToAddress:be}=h.secp256k1;class Ae{constructor(e,t,r){this.baseUrl=e,this.context=t,this.fetchOptions=r}getContext(){return this.context}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return h.networkIDs.getHRP(this.getNetworkID())}getApiX(){const e=new h.avm.AVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiP(){const e=new h.pvm.PVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiC(){const e=new h.evm.EVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getInfo(){const e=new h.info.InfoApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=be(a);return we(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return we(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ye(e);return we(t,this.getHrp(),r)}getApiByVM(e){switch(e){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(e){switch(e){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(e){const t=e.unsignedTx.getVM(),r=ge(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,a)=>{const i=async()=>{let o;switch(r&&n+r<Date.now()&&a(new Error("Timeout")),o=s instanceof h.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),o.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{i()}),1e3)}};i()}))}}const Te={weights:h.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},Ie={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:Te},Se={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:Te},Pe={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:Te};class Be extends Ae{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await h.Context.getContextFromURI(e);try{return new Be(e,t)}catch{return new Be(e,t)}}static getDefaultMainnetProvider(){return new Be(A.AVALANCHE_XP_NETWORK.rpcUrl,Ie)}static getDefaultFujiProvider(){return new Be(A.AVALANCHE_XP_TEST_NETWORK.rpcUrl,Se)}static getDefaultDevnetProvider(){return new Be(A.AVALANCHE_P_DEV_NETWORK.rpcUrl,Pe)}}const{bytesCompare:Ce,parseBech32:ke}=h.utils,Ee=(e,t)=>"P"===t,Me=(e,t,r)=>{const s=Ee(0,t)?e.amount:e.asset?.amount;return new h.TransferOutput(new h.BigIntPr(BigInt(s)),h.OutputOwners.fromNative(e.addresses.map((e=>ke(e)[1])).sort(Ce),BigInt(r??0),e.threshold))},De=(e,t)=>{const r=((e,t)=>{const r=t===b.Network.FUJI,{cBlockchainID:s,xBlockchainID:n,pBlockchainID:a}=r?Se:Ie;if(s===e)return"C";if(n===e)return"X";if(a===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=Ee(0,r)?e.txHash:e.creationTxHash,n=Ee(0,r)?e.assetId:e.asset?.assetId;return new h.Utxo(h.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),h.Id.fromString(n),((e,t)=>Ee(0,t)?e.stakeableLocktime?new h.pvmSerial.StakeableLockOut(new h.BigIntPr(BigInt(e.stakeableLocktime??0)),Me(e,t,e.platformLocktime??0)):Me(e,t,e.platformLocktime):Me(e,t,e.locktime))(e,r))},{unpackWithManager:Ve,parse:Ke,bufferToHex:Oe,AddressMaps:Ue,AddressMap:Ne}=h.utils;function _e(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return T("sha256").update(s).digest()}const Le=1024,Xe=1024;async function Fe(e,t,r){const s=e.slice(0,Le),n=e.slice(Le),a=await He(t,{...r,addresses:s});if(n.length){const s=await Fe(n,t,{...r,addresses:e});return a.merge(s)}return a}async function He(e,t){if(t.addresses.length>Le)throw new Error(`Can not get UTXOs for more than ${Le} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new h.utils.UtxoSet(s);if(s.length>=Xe){const s=await He(e,{...t,startIndex:r});return n.merge(s)}return n}function qe(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:$e}=h.utils;async function Re(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await Re(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:We,hexToBuffer:je,unpackWithManager:Je}=h.utils;function ze(e,t=!0){try{if(t){const[t]=h.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else h.utils.parseBech32(e);return!0}catch(e){return!1}}const Ge=e=>{if([Ie.xBlockchainID,Se.xBlockchainID,Pe.xBlockchainID].includes(e))return"AVM";if([Ie.pBlockchainID,Se.pBlockchainID,Pe.pBlockchainID].includes(e))return"PVM";if([Ie.cBlockchainID,Se.cBlockchainID,Pe.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},Ye=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),Qe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0));var Ze={parseCreateSubnetTx:e=>h.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:se.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>h.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:se.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>h.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:se.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>h.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:se.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>h.pvmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.evmSerial.isImportTx(e)?h.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:se.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:Qe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:se.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:Qe(e.ins,r),...t}):null,parseExportTx:e=>h.pvmSerial.isExportTx(e)||h.avmSerial.isExportTx(e)||h.evmSerial.isExportTx(e)?h.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:se.Export,chain:e.getVM(),destination:Ge(e.destinationChain.toString()),amount:Ye(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:se.Export,chain:e.getVM(),destination:Ge(e.destination.value()),amount:Ye(e.outs,r),...t}):null,parseBaseTx:e=>h.avmSerial.isAvmBaseTx(e)||h.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,a=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),h.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof h.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof h.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),i=qe(),o=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=i)));return{type:se.Base,chain:e.getVM(),outputs:o,memo:I(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!h.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return h.pvmSerial.isSigner(e.signer)&&(r=h.utils.bufferToHex(e.signer.proof.publicKey),t=h.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:se.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>h.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:se.AddPermissionlessDelegator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),stakeOuts:e.stake,delegatorRewardsOwner:e.getDelegatorRewardsOwner(),...t}):null,parseTransferSubnetOwnershipTx:e=>h.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:se.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>h.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:se.ConvertSubnetToL1,chain:e.getVM(),managerAddress:`0x${e.address.toString("hex")}`,validators:e.validators.map((e=>({nodeId:h.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>h.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:se.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>h.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:se.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>h.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:se.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>h.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:se.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:et,getOutputAmounts:tt,getInputAmounts:rt,validateBurnedAmount:st}=h.utils;function nt(e,t,r){return[...e].sort(((e,s)=>{for(let n=0;n<t.length;n++){const a=t[n];if(e[a]>s[a])return"asc"===r?1:-1;if(e[a]<s[a])return"asc"===r?-1:1}return 0}))}function at(e){const t=qe(),r=e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),a=nt(s,["amount"],"desc"),i=nt(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function it(e,t){return nt(e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const ot=e=>it(e,!0),dt=e=>it(e,!1);const{getUtxoInfo:ut}=h.utils;var ct=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(ct||{});const lt="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",pt="11111111111111111111111111111111LpoYY",ht=(e,t)=>e.reduce(((e,t)=>e+ut(t).amount),BigInt(0))-t,gt={BaseP:{sortFunction:ot,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new h.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:ht(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:dt,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new h.utils.UtxoSet(t),amount:ht(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new h.utils.UtxoSet(t),nodeId:lt,start:qe(),end:qe()+BigInt(1e3),weight:ht(t,e.getProvider().getContext().baseTxFee),subnetId:pt,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(h.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(h.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new h.utils.UtxoSet(t),nodeId:lt,start:qe(),end:qe()+BigInt(1e3),weight:ht(t,e.getProvider().getContext().baseTxFee),subnetId:pt,feeState:r})},ExportP:{sortFunction:ot,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext(),n=function({numberIns:e=1},t){const r=h.Common.createDimensions({bandwidth:161*e+254,dbRead:e,dbWrite:2+e,compute:200*e});return h.Common.dimensionsToGas(r,t)}({numberIns:t.length},s.platformFeeConfig.weights),a=r?n*r.price:s.baseTxFee;return e.exportP({amount:ht(t,a),utxoSet:new h.utils.UtxoSet(t),destination:"X",feeState:r})}},ImportP:{sortFunction:ot,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new h.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function mt(e){return S.validateString(e,!0)&&6===e.split("/").length}function ft(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:xt,hexToBuffer:vt}=h.utils;class yt{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Fe(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Re(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(e),s=this.provider.getChainID(t);return Fe(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=xt(s)[2],a=this.provider.getAvaxID(),i=h.TransferableOutput.fromNative(a,e,[n]),o=it(t.getUTXOs(),!0),d=this.provider.getChainID(r),u=this.getAddresses("X").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("X"))[2];return h.avm.newExportTx(this.provider.getContext(),d,u,o,[i],{threshold:1,changeAddresses:[c]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:a}){const i=this.provider.getChainID(t),o=this.getAddresses("P").map((e=>xt(e)[2]));xt(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const d=xt(r)[2],u=e.getUTXOs();return ft(n),h.pvm.newImportTx({fromAddressesBytes:o,utxos:u,toAddressesBytes:[d],sourceChainId:i,threshold:s,feeState:n,locktime:a},this.provider.getContext())}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>xt(e)[2])),a=xt(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const i=xt(r)[2];return h.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[i],n,{changeAddresses:[a]})}importC(e,r,s,n,a){const i=this.provider.getChainID(r),o=this.getAddresses("C").map((e=>xt(e)[2]));a=a||this.getAddressEVM();const d=Buffer.from(t.strip0x(a),"hex");return h.evm.newImportTxFromBaseFee(this.provider.getContext(),d,o,e.getUTXOs(),i,s,n)}exportC(e,t,r,s,n){const a=vt(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=xt(n)[2],d=s/BigInt(1e9);return h.evm.newExportTxFromBaseFee(this.provider.getContext(),d,e,i,a,[o],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const a=xt(n)[2],i=this.provider.getAvaxID(),o=h.TransferableOutput.fromNative(i,e,[a]),d=it(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>xt(e)[2])),l=xt(this.getChangeAddress("P"))[2];return ft(s),h.pvm.newExportTx({changeAddressesBytes:[l],fromAddressesBytes:c,utxos:d,outputs:[o],destinationChainId:u,feeState:s},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const a=dt(e.getUTXOs());s=s??this.getCurrentAddress("P");const i=xt(s)[2],o=this.provider.getContext(),d=[h.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c];return ft(r),h.pvm.newBaseTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:a,outputs:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},o)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:a,fromAddresses:i}){const[o,d,u]=xt(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>h.TransferableOutput.fromNative(e,t,[u]))),l=it(e.getUTXOs(),!0),p=(i??this.getAddresses(t)).map((e=>xt(e)[2])),g=xt(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?h.avm.newBaseTx(this.provider.getContext(),p,l,c,a):(ft(n),h.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:p,utxos:l,outputs:c,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:a,validators:i,options:o,fromAddresses:d}){const u=(d??this.getAddresses("P")).map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c],p=i.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:a,remainingBalanceOwner:i})=>{const o=new h.pvmSerial.ProofOfPossession(Uint8Array.from(h.utils.hexToBuffer(t)),Uint8Array.from(h.utils.hexToBuffer(r))),d=h.PChainOwner.fromNative(i.addresses.map((e=>xt(e)[2])),i.threshold??1),u=h.PChainOwner.fromNative(a.addresses.map((e=>xt(e)[2])),a.threshold??1);return h.L1Validator.fromNative(e,n,s,o,d,u)}));return h.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:p,fromAddressesBytes:u,address:xt(a)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:it(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:a,options:i}){const o=(a??this.getAddresses("P")).map((e=>xt(e)[2])),d=xt(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return h.pvm.newRegisterL1ValidatorTx({utxos:it(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(h.utils.hexToBuffer(r)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:i?.memo,message:Uint8Array.from(h.utils.hexToBuffer(s)),minIssuanceTime:i?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){const a=(n??this.getAddresses("P")).map((e=>xt(e)[2])),i=xt(this.getChangeAddress("P"))[2],o=s?.changeAddresses??[i];return h.pvm.newSetL1ValidatorWeightTx({utxos:it(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:a,memo:s?.memo,message:Uint8Array.from(h.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:a}){const i=(s??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return h.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:it(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:a}){const i=(s??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return h.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:it(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:a,subnetAuth:i,feeState:o,options:d,fromAddresses:u}){const c=it(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[p];return ft(o),h.pvm.newCreateChainTx({chainName:r,feeState:o,fromAddressesBytes:l,fxIds:n,genesisData:a,subnetAuth:i,subnetId:t,utxos:c,vmId:s,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:a,locktime:i}){const o=it(e.getUTXOs(),!0),d=(s??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],l=t.map((e=>xt(e)[2]));return ft(r),h.pvm.newCreateSubnetTx({fromAddressesBytes:d,changeAddressesBytes:c,utxos:o,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:a,locktime:i,subnetOwners:l},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:i,feeState:o,fromAddresses:d,options:u}){const c=it(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[p];return ft(o),h.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:l,utxos:c,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:i,feeState:o},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:i,feeState:o,fromAddresses:d,rewardAddresses:u,delegatorRewardAddresses:c,publicKey:l,signature:p,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=at(e.getUTXOs()),y=(d??this.getAddresses("P")).map((e=>xt(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),b=(c??[this.getCurrentAddress("P")]).map((e=>xt(e)[2]));if(!(a!==h.networkIDs.PrimaryNetworkID.toString()||l&&p))throw new Error("Must provide public key and signature for primary subnet.");const A=xt(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[A];return ft(o),h.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:y,delegatorRewardsOwner:b,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:i,feeState:o,publicKey:l,rewardAddresses:w,signature:p,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,fromAddresses:i,rewardAddresses:o,options:d,locktime:u,feeState:c,threshold:l,stakingAssetId:p}){const g=at(e.getUTXOs()),m=(i??this.getAddresses("P")).map((e=>xt(e)[2])),f=(o??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),x=xt(this.getChangeAddress("P"))[2],v=d?.changeAddresses??[x];return ft(c),h.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:d?.minIssuanceTime,memo:d?.memo,changeAddressesBytes:v,nodeId:t,start:r,end:s,weight:n,subnetId:a,rewardAddresses:f,locktime:u,stakingAssetId:p,threshold:l,feeState:c},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:a,options:i}){const o=it(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return ft(a),h.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:c,fromAddressesBytes:d,utxos:o,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:a},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:a,options:i,threshold:o,locktime:d}){const u=it(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>xt(e)[2])),l=xt(this.getChangeAddress("P"))[2],p=i?.changeAddresses??[l],g=s.map((e=>xt(e)[2]));return ft(n),h.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:p,fromAddressesBytes:c,utxos:u,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:o,locktime:d},this.provider.getContext())}}class wt extends yt{constructor(e,t,r){if(super(r),this.pubkeyXP=e,this.pubkeyC=t,33!==t.length||33!==e.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(e,r,s){const a=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new wt(o,d,s)}static fromMnemonic(e,t,r,s){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!mt(r)||!mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=u.mnemonicToSeedSync(e),a=m.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return wt.fromPublicKey(o.publicKey,i.publicKey,s)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return n.computeAddress(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(e){return[this.getAddress(e)]}getChangeAddress(e){return this.getAddress(e)}getCurrentAddress(e){return this.getAddress(e)}}const bt={type:"zondax",getApp:e=>new P(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,r={show:!1,hrp:"avax"}){const s=this.getApp(e);return{publicKey:(await s.getAddressAndPubKey(t.toString(),r.show,r.hrp)).publicKey}},async getXPUB(e,t){const r=this.getApp(e),s=await r.getExtendedPubKey(t,!1);return{pubKey:s.publicKey,chainCode:s.chain_code}},async signHash(e,t,r,s){const n=this.getApp(e),a=s.map((e=>e.toString(!0))),i=await n.signHash(r.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const a=this.getApp(e),i=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(r.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function At(e){return!(await bt.getVersion(e)>="0.6.0")}const{parse:Tt}=h.utils;class It extends yt{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=m.fromBase58(e),this.evmWallet=new wt(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=u.mnemonicToSeedSync(e),s=m.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath($(0,q.BIP44,"EVM")).neutered();return new It(n.toBase58(),a.publicKey,t)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getRawAddressC(){return Buffer.from(Tt(this.getCurrentAddress("C"))[2])}}const{isTransferOut:St,isStakeableLockOut:Pt}=h.utils;function Bt(e){const t=e.output;return St(t)||Pt(t)?t.getOwners():[]}function Ct(e){const t=e.getTx();return h.avmSerial.isExportTx(t)||h.pvmSerial.isExportTx(t)?new Set(t.outs.map(Bt).flat()):h.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(Bt).flat()):new Set((t.baseTx?.outputs??[]).map(Bt).flat())}const{parse:kt}=h.utils;class Et extends It{constructor(e,t,r){super(e,t,r)}getAdditionalAddressesByIndices(e,t,r){return"C"===r?[]:e.map((e=>{const s=this.getAddressAtIndex(e,t,r),[,,n]=kt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await At(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=O(e),a=await bt.getXPUB(e,Et.getAccountPath("X")),i=m.fromPublicKey(a.pubKey,a.chainCode),o=$(0,q.BIP44,"EVM"),d=await s.getAddress(o,!1),u=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),c=Buffer.from(t.strip0x(u),"hex");return new Et(i.toBase58(),c,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>S.fromString(e))),l=[...Ct(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>S.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:p})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=S.fromString(Et.getAccountPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:Mt}=h.utils;class Dt extends It{constructor(e,t,r){const s=m.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(Mt(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=m.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=u.mnemonicToSeedSync(e),s=m.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath($(0,q.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new Dt(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Vt,sign:Kt,signHash:Ot}=h.secp256k1,{addChecksum:Ut}=h.utils;class Nt extends wt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(Vt(e)),Buffer.from(Vt(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!mt(r)||!mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=u.mnemonicToSeedSync(e),a=m.fromSeed(n),i=a.derivePath(t),o=a.derivePath(r);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Nt(i.privateKey,o.privateKey,s)}async signMessage(e){const t=_e(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Ut(await Ot(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Kt(e.buffer,t))]}}const{strip0x:_t}=h.utils;class Lt extends wt{constructor(e,t,r,s,a){const i=h.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),o=h.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=s,!mt(t)||!mt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await At(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!mt(t)||!mt(r))throw new Error("Invalid path configuration.");const i=new s(e),o=await i.getAddress(r,!1),d=await i.getAddress(t,!1),u=Buffer.from(_t(o.publicKey),"hex"),c=Buffer.from(_t(d.publicKey),"hex"),l=Buffer.from(_t(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(_t(n.SigningKey.computePublicKey(c,!0)),"hex");return new Lt(p,t,l,r,a)}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=S.fromString(this.getAccountPath(e.chain)),r=S.fromString(this.getPartialSignerPath(e.chain)),s=_e(e.message),n=(await bt.signHash(e.transport,s,t,[r])).signatures.get(r.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=S.fromString(this.getAccountPath(e.chain)),r=S.fromString(this.getPartialSignerPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Xt}=h.utils;const Ft={C:60,X:9e3,P:9e3};var Ht=Object.freeze({__proto__:null,AbstractProvider:Ae,AddressWallet:class extends yt{constructor(e,t,r,s,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=r,this.xpChangeAddress=s,r.length<1)throw new Error("Must have at least 1 xp address.");if(!n.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(r.some((e=>!ze(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!ze(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(s)}setChangeAddress(e){if(!ze(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:Pe,FujiContext:Se,JsonRpcProvider:Be,LedgerLiveSigner:class{constructor(e){this.accountIndices=e}#i(e){return`m/44'/${Ft[e]}'`}#o(e,t){return`${this.#i(e)}/${t}'`}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a message.");const t=S.fromString(this.#o(e.chain,this.accountIndices[0])),r=S.fromString("0/0"),s=_e(e.message),n=(await bt.signHash(e.transport,s,t,[r])).signatures.get(r.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"AVM"===r?"X":"P",a=new Set(e.externalIndices??this.accountIndices);for(const r of a){const a=S.fromString(this.#o(n,r));(await this.#d(a,{buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)}))}return t}async#d(e,t){if(!t.transport)throw new Error("Ledger transport not provided");return[...(await bt.signTx(t.transport,t.buffer,e,t.signers??[S.fromString("0/0")],t.change??[S.fromString("0/0")])).signatures.values()]}async signTxBuffer(e){if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a tx buffer.");const t=S.fromString(this.#o(e.chain,this.accountIndices[0]));return this.#d(t,e)}},LedgerSigner:Lt,LedgerWallet:Et,MainnetContext:Ie,MnemonicWallet:Dt,MnemonicWalletVoid:It,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=m.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof h.EVMUnsignedTx||"C"===t?h.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):h.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Xt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),a=`0/${this.activeAccountIndex}`,i=new Map;if("C"===n||!this.accountNode)return i;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[a,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&i.set(t,e)}return i}getAddressBipPaths(e,t){return 0===t.size?[S.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(S.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(r.getAddresses(),n),i=this.getAddressBipPaths([...Ct(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=S.fromString(this.getAccountPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||S.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=_e(e.message),s=(await bt.signHash(e.transport,r,S.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=u.mnemonicToSeedSync(e),s=m.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath($(t,q.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=this.getSigningKeys(n,r,s);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await h.addTxSignatures({unsignedTx:t,privateKeys:a}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=_e(e.message),s=await h.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:ct,StaticSigner:Nt,TxType:se,WalletAbstract:yt,WalletVoid:wt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await ve({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const i=a.getCredentials(),o=a.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=i[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new h.Credential(s)),e}),[]),d=new h.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,o);return{signedTxHex:ge(new h.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:De,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,credentials:s,utxos:n})=>{const a=Ve(r,e),i=Ke(t)[2],o=Oe(i);if(h.evmSerial.isExportTx(a))return new h.EVMUnsignedTx(a,[],new Ue([Ne.fromJSON([[o,0]])]),s);if(h.evmSerial.isImportTx(a)){const e=Ue.fromTransferableInputs(a.importedInputs,n,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new h.UnsignedTx(a,n,e,s)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:oe,digestMessage:_e,emptySignature:pe,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=m.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(i,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return m.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=qe();return n.forEach((e=>{const t=$e(e);s[t.threshold>1?"multisig":t.locktime>a?"locked":t.stakeableLocktime>a?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getLedgerProvider:async function(e){return bt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=gt[r],o=qe(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=ut(e);return t<o&&(s<o||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),u=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let a=-1;for(;s<=n;){const i=Math.floor((s+n)/2);t(e.slice(0,i+1))<=r?(a=i,s=i+1):n=i-1}return a}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*ut(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(ut)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:He,getPchainUnixNow:async function(e){const t=await e.getApiP().getTimestamp(),r=new Date(t.timestamp),s=Math.floor(r.getTime()/1e3);return BigInt(s)},getStakeForAddresses:Re,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[h.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Fe,getUnixNow:qe,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:a})=>{const i=ne(t),o=je(e),d=Je(i,o);if(h.evmSerial.isExportTx(d))return[];const u=(e=>{if(h.evmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case h.EVM:return b.BlockchainId.C_CHAIN;case h.AVM:return b.BlockchainId.X_CHAIN;case h.PVM:return b.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=We(d),l=new b.Glacier({BASE:s,TOKEN:n,HEADERS:a}),p=[...new Set(c.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(p.map((e=>l.primaryNetworkTransactions.getTxByHash({blockchainId:u,network:r,txHash:e}))));return c.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=De(n,r);return e.push(a),e}),[])},getVmByChainAlias:ne,getXpubFromMnemonic:function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=u.mnemonicToSeedSync(e);return m.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:ze,isConvertSubnetToL1Tx:function(e){return"convert_subnet_to_l1"===e.type},isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isDisableL1ValidatorTx:function(e){return"disable_l1_validator"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isIncreaseL1ValidatorBalance:function(e){return"increase_l1_validator_balance"===e.type},isObsidianApp:At,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50,baseFee:n}={}){try{const a=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(Ze)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=et(i,a),u=tt(i),c=rt(i).get(a.avaxAssetID)??BigInt(0),l=d.get(a.avaxAssetID)??BigInt(0),p=u.get(a.avaxAssetID)??BigInt(0);let g=n;void 0===g&&(g=0n,h.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}=st({unsignedTx:e,context:a,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f,baseFee:g},assetId:a.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:se.Unknown}}},populateCredential:he,signedTxToHex:ge,sortUTXOsByAmount:it,sortUTXOsByAmountAscending:dt,sortUTXOsByAmountDescending:ot,sortUTXOsStaking:at,verifyDerivationPath:mt});exports.Avalanche=Ht,exports.BitcoinLedgerWallet=class extends ee{constructor(e,t,r,s,n){super(e,r),this.derivationPath=t,this.transport=s,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const r=function(e){return new v.AppClient(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=Q(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=Z(i,n,s,this.derivationPath);if(u.forEach((e=>{const[t,r]=e;c.updateInput(t,{partialSig:[{signature:r.signature,pubkey:r.pubkey}]})})),!c.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return c.finalizeAllInputs(),c.extractTransaction()}},exports.BitcoinProvider=class extends k{constructor(e=!0,r,s,n,a){super(),this.isMainnet=e,this.extraParams=a;const i=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#u=new t.HttpClient(s||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,r){const s=await this.#u.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!s?.length)return{confirmed:[],unconfirmed:[]};const n=s.map(this._parseUtxo),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,r))}async getAddressFromScript(e){const t=await this.#c.post("",{jsonrpc:"2.0",id:`decode-script-${e}`,method:"decodescript",params:[e]},{},this.extraParams);if(t.result)return t.result.address;throw new Error(`Unable to resolve address for script: ${e}. ${t.error.message}`)}async getScriptsForUtxos(e,t){const[r,s]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),n=s.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),a=n.length?(await this.#l(n,t)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...r,...s.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"},r=await this.#l([{...t,id:"1",params:[1]},{...t,id:"2",params:[3]},{...t,id:"3",params:[6]}],e).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(r[0]/1024)||1,medium:Math.ceil(r[1]/1024)||1,low:Math.ceil(r[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#c.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#u.post(`/api/v2/tx/${e}`,{},{},this.extraParams);return{block:t.blockHeight,fees:Number(t.fees),confirmations:t.confirmations,amount:Number(t.value),hash:t.txid,addresses:Array.from(new Set([...t.vin.map((e=>e.addresses||[])).flat(),...t.vout.map((e=>e.addresses||[])).flat()])),blockTime:t.blockTime,inputs:[...t.vin.map((e=>({...e,value:Number(e.value)})))],outputs:[...t.vout.map((e=>({...e,value:Number(e.value)})))]}}async getTxHistory(e){const t=await this.#u.post(`/api/v2/address/${e}`,{},{},this.extraParams),r=t.txids?.slice(0,25)??[];return await Promise.allSettled(r.map((async t=>{try{const r=await this.#u.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const r=t.vin.filter((t=>t.addresses?.includes(e))),s=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),a=t.vout.filter((t=>!t.addresses?.includes(e))),i=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=i>o;let u=o-i;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=a.map((e=>e.addresses||[])).flat(),p=d?l:c,h=p.filter(((e,t)=>p.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:h,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,r)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:r=1,pollInterval:s=500}={}){try{return await this.getTransaction(e)}catch(n){if(r>=t)throw n;return await new Promise((e=>setTimeout(e,s))),this.waitForTx(e,{maxAttempts:t,attempt:r+1,pollInterval:s})}}},exports.BitcoinProviderAbstract=k,exports.BitcoinWallet=te,exports.BitcoinWalletAbstract=ee,exports.BitcoinWalletVoid=class extends ee{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=re,exports.DerivationPath=q,exports.ETH_ACCOUNT_PATH=H,exports.ETH_COIN_PATH=F,exports.JsonRpcBatchInternal=z,exports.LedgerSigner=Y,exports.SolanaLedgerSigner=class{#p;#h;constructor(e,t){this.#p=L(e,!1),this.#h=t}async signTx(e,t){const r=await U(e,t),{signatures:s,messageBytes:n,...i}=a.compileTransaction(r),o=new d(this.#h),{address:u}=await o.getAddress(this.#p),c=a.address(l.base58.encode(Uint8Array.from(u)));if(!this.#s(c,s))return e;const{signature:p}=await o.signTransaction(this.#p,Buffer.from(n)),h=l.base58.encode(Uint8Array.from(p));return a.assertIsSignature(h),a.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...s,[c]:l.base58.decode(h)}})}#s(e,t){return e in t&&!t[e]}},exports.SolanaSigner=X,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.compileSolanaTx=e=>a.compileTransaction(e),exports.createPSBTV2=Q,exports.createPsbt=E,exports.createTransferTx=V,exports.createWalletPolicy=function(e,t,r,s){const n=new v.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new v.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=U,exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=$,exports.getAddressFromXPub=function(e,t){const r=G(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=m.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=G,exports.getAppEth=O,exports.getBech32Address=K,exports.getBech32AddressFromXPub=function(e,t,r){return K(G(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return K(Buffer.from(s,"hex"),r)},exports.getEvmAddressFromPubKey=function(e){return n.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e){const t=await e.send(176,1,0,0),r=t.readUInt8(1),s=t.readUInt8(2+r),n=t.subarray(2,2+r),a=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:a.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=O(e),n=await s.getAddress(r??H,t,!0),a=new g;return a.publicKey=B.Buffer.from(n.publicKey,"hex"),a.chainCode=B.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=C(e);if(!n)return 0;const{fee:a}=M(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=O(e),a=$(t,r,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(h.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaDerivationPath=L,exports.getSolanaProvider=({isTestnet:e,rpcUrl:t})=>{const r=a.createSolanaRpc(e?a.devnet(t):a.mainnet(t));return new Proxy(r,{get:(e,t,r)=>t===N||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,r))})},exports.getSolanaPublicKeyFromLedger=async(e,t)=>{const r=new d(t),{address:s}=await r.getAddress(L(e,!1));return s},exports.getTransferTxDetails=function(e,t,r,s,n){const a=M(e,t,r,s,D(n));return a.inputs||console.log("Unable to construct transaction, fee needed: ",a.fee),a},exports.getVoidSigner=function(e,t){return new n.VoidSigner(e,t)},exports.getWalletFromMnemonic=function(e,t,r){if(!(t>=0&&t%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return n.HDNodeWallet.fromMnemonic(n.Mnemonic.fromPhrase(e),$(t,r,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await u.mnemonicToSeed(e);return m.fromSeed(t).derivePath(H).neutered().toBase58()},exports.isERC20Transfer=j,exports.isNativeTxn=W,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[N],exports.maybeGetAssociatedTokenAccount=_,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),t)),{})},exports.onBalanceChange=async(e,t,r,s)=>{const n=new Set(e.map((e=>e.toLowerCase()))),a=new Set(t.map((e=>e.toLowerCase()))),i=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&a.has(e.to.toLowerCase())&&j(e,n)?s(e,{type:"erc20",contractAddress:e.to}):W(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",i);return{unsubscribe:()=>o.off("block",i)}},exports.openLedgerApp=async function(e,t){try{return(await e.send(224,216,0,0,Buffer.from(t,"ascii"))).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.psbt2ToPsbt0=Z,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=M,exports.serializeSolanaTx=e=>a.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:r,provider:s})=>{const{value:n}=await s.getLatestBlockhash().send(),o=[i.getTransferSolInstruction({source:a.createNoopSigner(a.address(e)),destination:a.address(t),amount:r})];return a.pipe(a.createTransactionMessage({version:0}),(e=>a.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>a.setTransactionMessageFeePayer(a.address(e),t)),(e=>a.appendTransactionMessageInstructions(o,e)))},exports.transferToken=async({from:e,to:t,mint:r,amount:s,decimals:n,provider:i})=>{const{address:d}=await _({mint:a.address(r),owner:a.address(e),provider:i}),{address:u,exists:c}=await _({mint:a.address(r),owner:a.address(t),provider:i}),l=[];c||l.push(o.getCreateAssociatedTokenIdempotentInstruction({payer:a.createNoopSigner(a.address(e)),mint:a.address(r),owner:a.address(t),ata:u})),l.push(o.getTransferCheckedInstruction({amount:s,authority:a.createNoopSigner(a.address(e)),decimals:n,mint:a.address(r),destination:u,source:d}));const{value:p}=await i.getLatestBlockhash().send();return a.pipe(a.createTransactionMessage({version:0}),(e=>a.setTransactionMessageLifetimeUsingBlockhash(p,e)),(t=>a.setTransactionMessageFeePayer(a.address(e),t)),(e=>a.appendTransactionMessageInstructions(l,e)))};
1
+ "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("bip32"),i=require("bip39"),o=require("@ledgerhq/hw-transport"),d=require("@metamask/eth-sig-util"),u=require("ledger-bitcoin"),c=require("@ledgerhq/hw-app-btc/lib/bip32"),l=require("@avalabs/avalanchejs"),p=require("@noble/hashes/sha256"),h=require("@avalabs/glacier-sdk"),g=require("@avalabs/core-chains-sdk"),m=require("create-hash"),f=require("xss"),x=require("bip32-path"),v=require("@avalabs/hw-app-avalanche"),y=require("hdkey"),w=require("@solana/kit"),b=require("@solana-program/system"),A=require("@solana-program/token"),T=require("@ledgerhq/hw-app-solana"),I=require("@noble/curves/ed25519"),S=require("@scure/base"),P=require("micro-key-producer/slip10.js"),B=require("buffer");function C(e){return e.reduce(((e,t)=>e+t.value),0)}class k{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:C(r.confirmed),balanceUnconfirmed:C(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function E(t,r,s){const n=new e.Psbt({network:s});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),r.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function M(e,t,s,n,a){const i=[{address:e,value:s}],{inputs:o,outputs:d,fee:u}=r(a,i,n);if(!o||!d)return{fee:u};const c=[d[0]],l=d[1];return l&&c.push({address:t,value:l.value}),{inputs:o,outputs:c,fee:u}}function V(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function D(e,t,r,s,n,a){const i=M(e,t,r,s,V(n));return i.inputs?{...i,psbt:E(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function K(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function O(e){return new s(e,"w0w")}const U="m/44'/60'",N=`${U}/0'`;var _=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(_||{});const L=(e,t,r=!0)=>{switch(t){case _.BIP44:return`${r?"m/":""}44'/60'/0'/0/${e}`;case _.LedgerLive:return`${r?"m/":""}44'/60'/${e}'/0/0`;default:throw new Error("Invalid path spec")}};var X=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];const F=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),H=(e,t)=>{const r=new n.Interface(X).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var $=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"}];class q extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#e="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#e.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#e,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,$,this._parentProvider),this._maxCalls=62)}#e;#t=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#e.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function R(e,t){return a.fromBase58(e).derivePath(`0/${t}`).publicKey}let W=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=L(e,r),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=O(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=O(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,a=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof o.TransportStatusError&&s.statusCode===o.StatusCodes.INS_NOT_SUPPORTED){const s=d.TypedDataUtils.hashStruct(i,r,t,d.SignTypedDataVersion.V4),a=d.TypedDataUtils.hashStruct("EIP712Domain",e,t,d.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function j(t,r,s,n,a,i){const o=new u.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,c.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function J(t,r,s,n){const a=new e.Psbt({network:r}),i=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<i;e++){const r=t.getInputWitnessUtxo(e),i=t.getInputBip32Derivation(e,s);a.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:i?[{path:n,pubkey:s,masterFingerprint:i.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)a.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return a}class z{constructor(t,r){this.pubkey=t,this.provider=r;try{this.ecPair=e.ECPair.fromPublicKey(t)}catch(e){throw new Error("Not a valid public key.")}}ecPair;getAddressP2PKH(){return e.payments.p2pkh({pubkey:this.ecPair.publicKey,network:this.provider.getNetwork()}).address}getAddressBech32(){return K(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,r,s){return D(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}var G=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.ConvertSubnetToL1="convert_subnet_to_l1",e.RegisterL1Validator="register_l1_validator",e.SetL1ValidatorWeight="set_l1_validator_weight",e.IncreaseL1ValidatorBalance="increase_l1_validator_balance",e.DisableL1Validator="disable_l1_validator",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))(G||{});const Y=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:Q,AddressMaps:Z}=l.utils,ee=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=Q(e);let i=Z.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:r})=>{const s=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,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new l.utils.AddressMap(a)),r})({tx:e,provider:r,addressMaps:i});return new l.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else l.pvmSerial.isDisableL1ValidatorTx(e)&&(i=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),a=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new l.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(i,e,r));return new l.UnsignedTx(e,n,i,s)},{bufferToHex:te,packTx:re}=l.utils,{publicKeyBytesToAddress:se,recoverPublicKey:ne}=l.secp256k1,ae=new l.Signature(new Uint8Array(Array(65).fill(0))),ie=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(ae);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=re(n.getTx()),d=p.sha256(o),u=ae.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=ne(d,e.toBytes()),r={toHex:()=>te(se(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function oe(e){return l.utils.bufferToHex(l.utils.addChecksum(e.toBytes()))}const{getManagerForVM:de,hexToBuffer:ue,unpackWithManager:ce}=l.utils,le=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=Y(t);if(n===l.EVM)throw new Error("EVM transactions are not supported");const a=ue(e),i=ce(n,a),o=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=de(s).unpack(t,l.avaxSerial.SignedTx),i=await ee({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new l.Credential(ie(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new l.Credential(ie(e))))}})({tx:i,txBytes:a,provider:r,vm:n,utxos:s});return ee({tx:i,provider:r,credentials:o,utxos:s})},{parseBech32:pe,format:he}=l.utils,{publicKeyBytesToAddress:ge}=l.secp256k1;class me{constructor(e,t,r){this.baseUrl=e,this.context=t,this.fetchOptions=r}getContext(){return this.context}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return 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,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=ge(a);return he(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return he(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=pe(e);return he(t,this.getHrp(),r)}getApiByVM(e){switch(e){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(e){switch(e){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(e){const t=e.unsignedTx.getVM(),r=oe(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,a)=>{const i=async()=>{let o;switch(r&&n+r<Date.now()&&a(new Error("Timeout")),o=s instanceof l.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),o.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{i()}),1e3)}};i()}))}}const fe={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)},xe={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:fe},ve={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:fe},ye={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:fe};class we extends me{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await l.Context.getContextFromURI(e);try{return new we(e,t)}catch{return new we(e,t)}}static getDefaultMainnetProvider(){return new we(g.AVALANCHE_XP_NETWORK.rpcUrl,xe)}static getDefaultFujiProvider(){return new we(g.AVALANCHE_XP_TEST_NETWORK.rpcUrl,ve)}static getDefaultDevnetProvider(){return new we(g.AVALANCHE_P_DEV_NETWORK.rpcUrl,ye)}}const{bytesCompare:be,parseBech32:Ae}=l.utils,Te=(e,t)=>"P"===t,Ie=(e,t,r)=>{const s=Te(0,t)?e.amount:e.asset?.amount;return new l.TransferOutput(new l.BigIntPr(BigInt(s)),l.OutputOwners.fromNative(e.addresses.map((e=>Ae(e)[1])).sort(be),BigInt(r??0),e.threshold))},Se=(e,t)=>{const r=((e,t)=>{const r=t===h.Network.FUJI,{cBlockchainID:s,xBlockchainID:n,pBlockchainID:a}=r?ve:xe;if(s===e)return"C";if(n===e)return"X";if(a===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=Te(0,r)?e.txHash:e.creationTxHash,n=Te(0,r)?e.assetId:e.asset?.assetId;return new l.Utxo(l.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),l.Id.fromString(n),((e,t)=>Te(0,t)?e.stakeableLocktime?new l.pvmSerial.StakeableLockOut(new l.BigIntPr(BigInt(e.stakeableLocktime??0)),Ie(e,t,e.platformLocktime??0)):Ie(e,t,e.platformLocktime):Ie(e,t,e.locktime))(e,r))},{unpackWithManager:Pe,parse:Be,bufferToHex:Ce,AddressMaps:ke,AddressMap:Ee}=l.utils;function Me(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return m("sha256").update(s).digest()}const Ve=1024,De=1024;async function Ke(e,t,r){const s=e.slice(0,Ve),n=e.slice(Ve),a=await Oe(t,{...r,addresses:s});if(n.length){const s=await Ke(n,t,{...r,addresses:e});return a.merge(s)}return a}async function Oe(e,t){if(t.addresses.length>Ve)throw new Error(`Can not get UTXOs for more than ${Ve} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new l.utils.UtxoSet(s);if(s.length>=De){const s=await Oe(e,{...t,startIndex:r});return n.merge(s)}return n}function Ue(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:Ne}=l.utils;async function _e(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await _e(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Le,hexToBuffer:Xe,unpackWithManager:Fe}=l.utils;function He(e,t=!0){try{if(t){const[t]=l.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else l.utils.parseBech32(e);return!0}catch(e){return!1}}const $e=e=>{if([xe.xBlockchainID,ve.xBlockchainID,ye.xBlockchainID].includes(e))return"AVM";if([xe.pBlockchainID,ve.pBlockchainID,ye.pBlockchainID].includes(e))return"PVM";if([xe.cBlockchainID,ve.cBlockchainID,ye.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},qe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),Re=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0));var We={parseCreateSubnetTx:e=>l.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:G.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>l.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:G.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:G.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:G.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:r})=>({type:G.Import,chain:e.getVM(),source:$e(e.sourceChain.value()),amount:Re(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:G.Import,chain:e.getVM(),source:$e(e.sourceChain.value()),amount:Re(e.ins,r),...t}):null,parseExportTx:e=>l.pvmSerial.isExportTx(e)||l.avmSerial.isExportTx(e)||l.evmSerial.isExportTx(e)?l.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:G.Export,chain:e.getVM(),destination:$e(e.destinationChain.toString()),amount:qe(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:G.Export,chain:e.getVM(),destination:$e(e.destination.value()),amount:qe(e.outs,r),...t}):null,parseBaseTx:e=>l.avmSerial.isAvmBaseTx(e)||l.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,a=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),l.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof l.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof l.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),i=Ue(),o=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=i)));return{type:G.Base,chain:e.getVM(),outputs:o,memo:f(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!l.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return l.pvmSerial.isSigner(e.signer)&&(r=l.utils.bufferToHex(e.signer.proof.publicKey),t=l.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:G.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>l.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:G.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:r})=>({type:G.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>l.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:G.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:G.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>l.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:G.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>l.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:G.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>l.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:G.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:je,getOutputAmounts:Je,getInputAmounts:ze,validateBurnedAmount:Ge}=l.utils;function Ye(e,t,r){return[...e].sort(((e,s)=>{for(let n=0;n<t.length;n++){const a=t[n];if(e[a]>s[a])return"asc"===r?1:-1;if(e[a]<s[a])return"asc"===r?-1:1}return 0}))}function Qe(e){const t=Ue(),r=e.map((e=>({utxo:e,...l.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),a=Ye(s,["amount"],"desc"),i=Ye(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function Ze(e,t){return Ye(e.map((e=>({utxo:e,...l.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const et=e=>Ze(e,!0),tt=e=>Ze(e,!1);const{getUtxoInfo:rt}=l.utils;var st=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(st||{});const nt="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",at="11111111111111111111111111111111LpoYY",it=(e,t)=>e.reduce(((e,t)=>e+rt(t).amount),BigInt(0))-t,ot={BaseP:{sortFunction:et,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new l.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:it(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:tt,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new l.utils.UtxoSet(t),amount:it(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:Qe,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new l.utils.UtxoSet(t),nodeId:nt,start:Ue(),end:Ue()+BigInt(1e3),weight:it(t,e.getProvider().getContext().baseTxFee),subnetId:at,shares:5,feeState:r,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:Qe,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new l.utils.UtxoSet(t),nodeId:nt,start:Ue(),end:Ue()+BigInt(1e3),weight:it(t,e.getProvider().getContext().baseTxFee),subnetId:at,feeState:r})},ExportP:{sortFunction:et,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext(),n=function({numberIns:e=1},t){const r=l.Common.createDimensions({bandwidth:161*e+254,dbRead:e,dbWrite:2+e,compute:200*e});return l.Common.dimensionsToGas(r,t)}({numberIns:t.length},s.platformFeeConfig.weights),a=r?n*r.price:s.baseTxFee;return e.exportP({amount:it(t,a),utxoSet:new l.utils.UtxoSet(t),destination:"X",feeState:r})}},ImportP:{sortFunction:et,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new l.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function dt(e){return x.validateString(e,!0)&&6===e.split("/").length}const ut=(e,t=!0)=>`${t?"m/":""}44'/9000'/${e}'/0/0`;function ct(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:lt,hexToBuffer:pt}=l.utils;class ht{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Ke(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return _e(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(e),s=this.provider.getChainID(t);return Ke(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=lt(s)[2],a=this.provider.getAvaxID(),i=l.TransferableOutput.fromNative(a,e,[n]),o=Ze(t.getUTXOs(),!0),d=this.provider.getChainID(r),u=this.getAddresses("X").map((e=>lt(e)[2])),c=lt(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:r,threshold:s,feeState:n,locktime:a}){const i=this.provider.getChainID(t),o=this.getAddresses("P").map((e=>lt(e)[2]));lt(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const d=lt(r)[2],u=e.getUTXOs();return ct(n),l.pvm.newImportTx({fromAddressesBytes:o,utxos:u,toAddressesBytes:[d],sourceChainId:i,threshold:s,feeState:n,locktime:a},this.provider.getContext())}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>lt(e)[2])),a=lt(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const i=lt(r)[2];return l.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[i],n,{changeAddresses:[a]})}importC(e,r,s,n,a){const i=this.provider.getChainID(r),o=this.getAddresses("C").map((e=>lt(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,s,n)}exportC(e,t,r,s,n){const a=pt(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=lt(n)[2],d=s/BigInt(1e9);return l.evm.newExportTxFromBaseFee(this.provider.getContext(),d,e,i,a,[o],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const a=lt(n)[2],i=this.provider.getAvaxID(),o=l.TransferableOutput.fromNative(i,e,[a]),d=Ze(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>lt(e)[2])),p=lt(this.getChangeAddress("P"))[2];return ct(s),l.pvm.newExportTx({changeAddressesBytes:[p],fromAddressesBytes:c,utxos:d,outputs:[o],destinationChainId:u,feeState:s},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const a=tt(e.getUTXOs());s=s??this.getCurrentAddress("P");const i=lt(s)[2],o=this.provider.getContext(),d=[l.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>lt(e)[2])),c=lt(this.getChangeAddress("P"))[2],p=n?.changeAddresses??[c];return ct(r),l.pvm.newBaseTx({changeAddressesBytes:p,fromAddressesBytes:u,utxos:a,outputs:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},o)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:a,fromAddresses:i}){const[o,d,u]=lt(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>l.TransferableOutput.fromNative(e,t,[u]))),p=Ze(e.getUTXOs(),!0),h=(i??this.getAddresses(t)).map((e=>lt(e)[2])),g=lt(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?l.avm.newBaseTx(this.provider.getContext(),h,p,c,a):(ct(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:r,subnetAuth:s,feeState:n,address:a,validators:i,options:o,fromAddresses:d}){const u=(d??this.getAddresses("P")).map((e=>lt(e)[2])),c=lt(this.getChangeAddress("P"))[2],p=o?.changeAddresses??[c],h=i.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:a,remainingBalanceOwner:i})=>{const o=new l.pvmSerial.ProofOfPossession(Uint8Array.from(l.utils.hexToBuffer(t)),Uint8Array.from(l.utils.hexToBuffer(r))),d=l.PChainOwner.fromNative(i.addresses.map((e=>lt(e)[2])),i.threshold??1),u=l.PChainOwner.fromNative(a.addresses.map((e=>lt(e)[2])),a.threshold??1);return l.L1Validator.fromNative(e,n,s,o,d,u)}));return l.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:p,validators:h,fromAddressesBytes:u,address:lt(a)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:Ze(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:a,options:i}){const o=(a??this.getAddresses("P")).map((e=>lt(e)[2])),d=lt(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return l.pvm.newRegisterL1ValidatorTx({utxos:Ze(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(l.utils.hexToBuffer(r)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:i?.memo,message:Uint8Array.from(l.utils.hexToBuffer(s)),minIssuanceTime:i?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){const a=(n??this.getAddresses("P")).map((e=>lt(e)[2])),i=lt(this.getChangeAddress("P"))[2],o=s?.changeAddresses??[i];return l.pvm.newSetL1ValidatorWeightTx({utxos:Ze(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:a,memo:s?.memo,message:Uint8Array.from(l.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:a}){const i=(s??this.getAddresses("P")).map((e=>lt(e)[2])),o=lt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return l.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:Ze(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:a}){const i=(s??this.getAddresses("P")).map((e=>lt(e)[2])),o=lt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return l.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:Ze(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:a,subnetAuth:i,feeState:o,options:d,fromAddresses:u}){const c=Ze(e.getUTXOs(),!0),p=(u??this.getAddresses("P")).map((e=>lt(e)[2])),h=lt(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[h];return ct(o),l.pvm.newCreateChainTx({chainName:r,feeState:o,fromAddressesBytes:p,fxIds:n,genesisData:a,subnetAuth:i,subnetId:t,utxos:c,vmId:s,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:a,locktime:i}){const o=Ze(e.getUTXOs(),!0),d=(s??this.getAddresses("P")).map((e=>lt(e)[2])),u=lt(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],p=t.map((e=>lt(e)[2]));return ct(r),l.pvm.newCreateSubnetTx({fromAddressesBytes:d,changeAddressesBytes:c,utxos:o,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:a,locktime:i,subnetOwners:p},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:i,feeState:o,fromAddresses:d,options:u}){const c=Ze(e.getUTXOs(),!0),p=(d??this.getAddresses("P")).map((e=>lt(e)[2])),h=lt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[h];return ct(o),l.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:p,utxos:c,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:i,feeState:o},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,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=Qe(e.getUTXOs()),y=(d??this.getAddresses("P")).map((e=>lt(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>lt(e)[2])),b=(c??[this.getCurrentAddress("P")]).map((e=>lt(e)[2]));if(!(a!==l.networkIDs.PrimaryNetworkID.toString()||p&&h))throw new Error("Must provide public key and signature for primary subnet.");const A=lt(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[A];return ct(o),l.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:y,delegatorRewardsOwner:b,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:i,feeState:o,publicKey:p,rewardAddresses:w,signature:h,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,fromAddresses:i,rewardAddresses:o,options:d,locktime:u,feeState:c,threshold:p,stakingAssetId:h}){const g=Qe(e.getUTXOs()),m=(i??this.getAddresses("P")).map((e=>lt(e)[2])),f=(o??[this.getCurrentAddress("P")]).map((e=>lt(e)[2])),x=lt(this.getChangeAddress("P"))[2],v=d?.changeAddresses??[x];return ct(c),l.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:d?.minIssuanceTime,memo:d?.memo,changeAddressesBytes:v,nodeId:t,start:r,end:s,weight:n,subnetId:a,rewardAddresses:f,locktime:u,stakingAssetId:h,threshold:p,feeState:c},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:a,options:i}){const o=Ze(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>lt(e)[2])),u=lt(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return ct(a),l.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:c,fromAddressesBytes:d,utxos:o,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:a},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:a,options:i,threshold:o,locktime:d}){const u=Ze(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>lt(e)[2])),p=lt(this.getChangeAddress("P"))[2],h=i?.changeAddresses??[p],g=s.map((e=>lt(e)[2]));return ct(n),l.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:h,fromAddressesBytes:c,utxos:u,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:o,locktime:d},this.provider.getContext())}}class gt extends ht{constructor(e,t,r){if(super(r),this.pubkeyXP=e,this.pubkeyC=t,33!==t.length||33!==e.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(e,r,s){const a=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new gt(o,d,s)}static fromMnemonic(e,t,r,s){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!dt(r)||!dt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=i.mnemonicToSeedSync(e),o=a.fromSeed(n),d=o.derivePath(r),u=o.derivePath(t);return gt.fromPublicKey(u.publicKey,d.publicKey,s)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return n.computeAddress(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(e){return[this.getAddress(e)]}getChangeAddress(e){return this.getAddress(e)}getCurrentAddress(e){return this.getAddress(e)}}const mt={type:"zondax",getApp:e=>new v(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,r={show:!1,hrp:"avax"}){const s=this.getApp(e);return{publicKey:(await s.getAddressAndPubKey(t.toString(),r.show,r.hrp)).publicKey}},async getXPUB(e,t){const r=this.getApp(e),s=await r.getExtendedPubKey(t,!1);return{pubKey:s.publicKey,chainCode:s.chain_code}},async signHash(e,t,r,s){const n=this.getApp(e),a=s.map((e=>e.toString(!0))),i=await n.signHash(r.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const a=this.getApp(e),i=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(r.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function ft(e){return!(await mt.getVersion(e)>="0.6.0")}const{parse:xt}=l.utils;class vt extends ht{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=a.fromBase58(e),this.evmWallet=new gt(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=i.mnemonicToSeedSync(e),s=a.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),o=s.derivePath(L(0,_.BIP44)).neutered();return new vt(n.toBase58(),o.publicKey,t)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(xt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(xt(e)[2])))}getRawAddressC(){return Buffer.from(xt(this.getCurrentAddress("C"))[2])}}const{isTransferOut:yt,isStakeableLockOut:wt}=l.utils;function bt(e){const t=e.output;return yt(t)||wt(t)?t.getOwners():[]}function At(e){const t=e.getTx();return l.avmSerial.isExportTx(t)||l.pvmSerial.isExportTx(t)?new Set(t.outs.map(bt).flat()):l.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(bt).flat()):new Set((t.baseTx?.outputs??[]).map(bt).flat())}const{parse:Tt}=l.utils;class It extends vt{constructor(e,t,r){super(e,t,r)}getAdditionalAddressesByIndices(e,t,r){return"C"===r?[]:e.map((e=>{const s=this.getAddressAtIndex(e,t,r),[,,n]=Tt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await ft(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=O(e),i=await mt.getXPUB(e,It.getAccountPath("X")),o=a.fromPublicKey(i.pubKey,i.chainCode),d=Ht(0,"EVM",{pathSpec:_.BIP44}),u=await s.getAddress(d,!1),c=n.SigningKey.computePublicKey(Buffer.from(u.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new It(o.toBase58(),l,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>x.fromString(e))),l=[...At(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>x.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:p})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=x.fromString(It.getAccountPath(e.chain));return[...(await mt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:St}=l.utils;class Pt extends vt{constructor(e,t,r){const s=a.fromBase58(e).neutered(),i=new n.SigningKey(t),o=Buffer.from(St(i.compressedPublicKey),"hex");super(s.toBase58(),o,r),this.evmPrivKey=t,this.accountNode=a.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=i.mnemonicToSeedSync(e),s=a.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),o=s.derivePath(Ht(0,"EVM",{pathSpec:_.BIP44}));if(!o.privateKey)throw new Error("Unable to derive EVM private key.");return new Pt(n.toBase58(),o.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await l.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Bt,sign:Ct,signHash:kt}=l.secp256k1,{addChecksum:Et}=l.utils;class Mt extends gt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(Bt(e)),Buffer.from(Bt(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!dt(r)||!dt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=i.mnemonicToSeedSync(e),o=a.fromSeed(n),d=o.derivePath(t),u=o.derivePath(r);if(!d.privateKey||!u.privateKey)throw new Error("Failed to generate private keys.");return new Mt(d.privateKey,u.privateKey,s)}async signMessage(e){const t=Me(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Et(await kt(t,r)))}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 Ct(e.buffer,t))]}}const{strip0x:Vt}=l.utils;class Dt extends gt{constructor(e,t,r,s,a){const i=l.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),o=l.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=s,!dt(t)||!dt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await ft(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!dt(t)||!dt(r))throw new Error("Invalid path configuration.");const i=new s(e),o=await i.getAddress(r,!1),d=await i.getAddress(t,!1),u=Buffer.from(Vt(o.publicKey),"hex"),c=Buffer.from(Vt(d.publicKey),"hex"),l=Buffer.from(Vt(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Vt(n.SigningKey.computePublicKey(c,!0)),"hex");return new Dt(p,t,l,r,a)}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=x.fromString(this.getAccountPath(e.chain)),r=x.fromString(this.getPartialSignerPath(e.chain)),s=Me(e.message),n=(await mt.signHash(e.transport,s,t,[r])).signatures.get(r.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=x.fromString(this.getAccountPath(e.chain)),r=x.fromString(this.getPartialSignerPath(e.chain));return[...(await mt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Kt}=l.utils;const Ot={C:60,X:9e3,P:9e3};var Ut=Object.freeze({__proto__:null,AbstractProvider:me,AddressWallet:class extends ht{constructor(e,t,r,s,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=r,this.xpChangeAddress=s,r.length<1)throw new Error("Must have at least 1 xp address.");if(!n.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(r.some((e=>!He(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!He(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(s)}setChangeAddress(e){if(!He(e,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=e}getAddressEVM(){return this.addressC}getAddresses(e){return("C"===e?[this.addressCoreEth]:this.xpAddresses).map((t=>this.provider.formatAddress(t,e)))}getChangeAddress(e){const t="C"===e?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(t,e)}getCurrentAddress(e){const t="C"===e?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(t,e)}},DevnetContext:ye,FujiContext:ve,JsonRpcProvider:we,LedgerLiveSigner:class{constructor(e){this.accountIndices=e}#r(e){return`m/44'/${Ot[e]}'`}#s(e,t){return`${this.#r(e)}/${t}'`}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a message.");const t=x.fromString(this.#s(e.chain,this.accountIndices[0])),r=x.fromString("0/0"),s=Me(e.message),n=(await mt.signHash(e.transport,s,t,[r])).signatures.get(r.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"AVM"===r?"X":"P",a=new Set(e.externalIndices??this.accountIndices);for(const r of a){const a=x.fromString(this.#s(n,r));(await this.#n(a,{buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)}))}return t}async#n(e,t){if(!t.transport)throw new Error("Ledger transport not provided");return[...(await mt.signTx(t.transport,t.buffer,e,t.signers??[x.fromString("0/0")],t.change??[x.fromString("0/0")])).signatures.values()]}async signTxBuffer(e){if(!this.accountIndices.length)throw new Error("No account indices provided. At least one account index is required to sign a tx buffer.");const t=x.fromString(this.#s(e.chain,this.accountIndices[0]));return this.#n(t,e)}},LedgerSigner:Dt,LedgerWallet:It,MainnetContext:xe,MnemonicWallet:Pt,MnemonicWalletVoid:vt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=a.fromBase58(r))}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'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Kt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),a="EVM"===e.tx.getVM()?`0/${this.activeAccountIndex}`:"0/0",i=new Map;if("C"===n||!this.accountNode)return i;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[a,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&i.set(t,e)}return i}getAddressBipPaths(e,t,r){return 0===t.size?[x.fromString("C"===r?`0/${this.activeAccountIndex}`:"0/0")]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(x.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(r.getAddresses(),n,t),i=this.getAddressBipPaths([...At(r)],n,t);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=x.fromString(this.getAccountPath(e.chain));return[...(await mt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t="C"===e.chain?this.activeAccountIndex:0,r=e.signer||x.fromString(`0/${t}`);if(2!=r.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const s=Me(e.message),n=(await mt.signHash(e.transport,s,x.fromString(this.getAccountPath(e.chain)),[r])).signatures.get(r.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=i.mnemonicToSeedSync(e),s=a.fromSeed(r);this.accountNodeXP=s.derivePath(`m/44'/9000'/${t}'`);const n=s.derivePath(Ht(t,"EVM",{pathSpec:_.BIP44}));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath("0/0");if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=this.getSigningKeys(n,r,s);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await 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 r=Me(e.message),s=await l.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:st,StaticSigner:Mt,TxType:G,WalletAbstract:ht,WalletVoid:gt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await le({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const i=a.getCredentials(),o=a.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=i[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new l.Credential(s)),e}),[]),d=new l.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,o);return{signedTxHex:oe(new l.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:Se,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,credentials:s,utxos:n})=>{const a=Pe(r,e),i=Be(t)[2],o=Ce(i);if(l.evmSerial.isExportTx(a))return new l.EVMUnsignedTx(a,[],new ke([Ee.fromJSON([[o,0]])]),s);if(l.evmSerial.isImportTx(a)){const e=ke.fromTransferableInputs(a.importedInputs,n,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new l.UnsignedTx(a,n,e,s)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:ee,digestMessage:Me,emptySignature:ae,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const i=n?"1":"0",o=a.fromBase58(e).derivePath(`${i}/${t}`).publicKey;return r.getAddress(o,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return a.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=Ue();return n.forEach((e=>{const t=Ne(e);s[t.threshold>1?"multisig":t.locktime>a?"locked":t.stakeableLocktime>a?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getAvalancheDerivationPath:ut,getLedgerProvider:async function(e){return mt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=ot[r],o=Ue(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=rt(e);return t<o&&(s<o||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),u=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let a=-1;for(;s<=n;){const i=Math.floor((s+n)/2);t(e.slice(0,i+1))<=r?(a=i,s=i+1):n=i-1}return a}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*rt(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(rt)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:Oe,getPchainUnixNow:async function(e){const t=await e.getApiP().getTimestamp(),r=new Date(t.timestamp),s=Math.floor(r.getTime()/1e3);return BigInt(s)},getStakeForAddresses:_e,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[l.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Ke,getUnixNow:Ue,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:a})=>{const i=Y(t),o=Xe(e),d=Fe(i,o);if(l.evmSerial.isExportTx(d))return[];const u=(e=>{if(l.evmSerial.isImportTx(e)||l.avmSerial.isImportTx(e)||l.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case l.EVM:return h.BlockchainId.C_CHAIN;case l.AVM:return h.BlockchainId.X_CHAIN;case l.PVM:return h.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=Le(d),p=new h.Glacier({BASE:s,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:r,txHash:e}))));return c.reduce(((e,t)=>{const s=m.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=Se(n,r);return e.push(a),e}),[])},getVmByChainAlias:Y,getXpubFromMnemonic:function(e,t){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=i.mnemonicToSeedSync(e);return a.fromSeed(r).derivePath(`44'/9000'/${t}'`).neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:He,isConvertSubnetToL1Tx:function(e){return"convert_subnet_to_l1"===e.type},isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isDisableL1ValidatorTx:function(e){return"disable_l1_validator"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isIncreaseL1ValidatorBalance:function(e){return"increase_l1_validator_balance"===e.type},isObsidianApp:ft,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50,baseFee:n}={}){try{const a=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(We)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=je(i,a),u=Je(i),c=ze(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}=Ge({unsignedTx:e,context:a,burnedAmount:p,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:p,totalAvaxOutput:h,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f,baseFee:g},assetId:a.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:G.Unknown}}},populateCredential:ie,signedTxToHex:oe,sortUTXOsByAmount:Ze,sortUTXOsByAmountAscending:tt,sortUTXOsByAmountDescending:et,sortUTXOsStaking:Qe,verifyDerivationPath:dt});const Nt=(e,t)=>{const r=w.getTransactionDecoder().decode(w.getBase64Encoder().encode(e)),s=w.getCompiledTransactionMessageDecoder().decode(r.messageBytes);return w.decompileTransactionMessageFetchingLookupTables(s,t)},_t=Symbol(),Lt=async({mint:e,owner:t,provider:r})=>{const[s]=await A.findAssociatedTokenPda({mint:w.address(e),owner:w.address(t),tokenProgram:A.TOKEN_PROGRAM_ADDRESS}),n=await r.getAccountInfo(s,{encoding:"base64"}).send();return{address:s,exists:Boolean(n.value),info:n}},Xt=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class Ft{#a;#i;constructor(e){this.#a=Uint8Array.from(e),this.#i=w.address(S.base58.encode(I.ed25519.getPublicKey(this.#a)))}static fromMnemonic(e,t){const r=i.mnemonicToSeedSync(e),s=P.fromMasterSeed(Uint8Array.from(r)).derive(`m/44'/501'/${t}'/0'`);return new Ft(Buffer.from(s.privateKey))}#o(e){try{return w.getCompiledTransactionMessageDecoder().decode(e),!0}catch{return!1}}async signMessage(e){const t=S.base64.decode(e);if(this.#o(t))throw new Error("Cannot use signMessage() to sign transactions!");return S.base64.encode(I.ed25519.sign(t,this.#a))}async signTx(e,t){const r=await Nt(e,t),{signatures:s,messageBytes:n,...a}=w.compileTransaction(r);if(!this.#d(s))return e;const i=S.base58.encode(I.ed25519.sign(Uint8Array.from(n),this.#a));return w.assertIsSignature(i),w.getBase64EncodedWireTransaction({...a,messageBytes:n,signatures:{...s,[this.#i]:S.base58.decode(i)}})}#d(e){return this.#i in e&&!e[this.#i]}}function Ht(e,t,r={withRoot:!0}){if(e<0)throw new Error("Account index can not be less than 0.");switch(t){case"EVM":if(!r.pathSpec)throw new Error("Path spec is required for EVM: either BIP44 or Ledger Live");return L(e,r.pathSpec,r.withRoot);case"AVM":case"PVM":return ut(e,r.withRoot);case"SVM":return Xt(e,r.withRoot);default:throw new Error(`Unknown derivation path for VM: ${t}`)}}class $t extends z{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=_.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await i.mnemonicToSeed(e),o=a.fromSeed(n),d=Ht(t,"EVM",{pathSpec:s}),u=o.derivePath(d);if(!u.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new $t(u.privateKey,r)}signTx(e,t){const r=E(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(r))}static fromEthersWallet(e,t){const r=e.privateKey;if(!r)throw new Error("Unable to get private key from ethers wallet.");const s=Buffer.from(r.substring(2),"hex");return new $t(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}const qt=e.networks;exports.Avalanche=Ut,exports.BitcoinLedgerWallet=class extends z{constructor(e,t,r,s,n){super(e,r),this.derivationPath=t,this.transport=s,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const r=function(e){return new u.AppClient(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=j(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,c=await r.signPsbt(i,o,d),l=J(i,n,s,this.derivationPath);if(c.forEach((e=>{const[t,r]=e;l.updateInput(t,{partialSig:[{signature:r.signature,pubkey:r.pubkey}]})})),!l.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return l.finalizeAllInputs(),l.extractTransaction()}},exports.BitcoinProvider=class extends k{constructor(e=!0,r,s,n,a){super(),this.isMainnet=e,this.extraParams=a;const i=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#u=new t.HttpClient(s||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,r){const s=await this.#u.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!s?.length)return{confirmed:[],unconfirmed:[]};const n=s.map(this._parseUtxo),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,r))}async getAddressFromScript(e){const t=await this.#c.post("",{jsonrpc:"2.0",id:`decode-script-${e}`,method:"decodescript",params:[e]},{},this.extraParams);if(t.result)return t.result.address;throw new Error(`Unable to resolve address for script: ${e}. ${t.error.message}`)}async getScriptsForUtxos(e,t){const[r,s]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),n=s.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),a=n.length?(await this.#l(n,t)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...r,...s.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"},r=await this.#l([{...t,id:"1",params:[1]},{...t,id:"2",params:[3]},{...t,id:"3",params:[6]}],e).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(r[0]/1024)||1,medium:Math.ceil(r[1]/1024)||1,low:Math.ceil(r[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#c.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#u.post(`/api/v2/tx/${e}`,{},{},this.extraParams);return{block:t.blockHeight,fees:Number(t.fees),confirmations:t.confirmations,amount:Number(t.value),hash:t.txid,addresses:Array.from(new Set([...t.vin.map((e=>e.addresses||[])).flat(),...t.vout.map((e=>e.addresses||[])).flat()])),blockTime:t.blockTime,inputs:[...t.vin.map((e=>({...e,value:Number(e.value)})))],outputs:[...t.vout.map((e=>({...e,value:Number(e.value)})))]}}async getTxHistory(e){const t=await this.#u.post(`/api/v2/address/${e}`,{},{},this.extraParams),r=t.txids?.slice(0,25)??[];return await Promise.allSettled(r.map((async t=>{try{const r=await this.#u.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const r=t.vin.filter((t=>t.addresses?.includes(e))),s=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),a=t.vout.filter((t=>!t.addresses?.includes(e))),i=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=i>o;let u=o-i;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=a.map((e=>e.addresses||[])).flat(),p=d?l:c,h=p.filter(((e,t)=>p.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:h,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,r)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:r=1,pollInterval:s=500}={}){try{return await this.getTransaction(e)}catch(n){if(r>=t)throw n;return await new Promise((e=>setTimeout(e,s))),this.waitForTx(e,{maxAttempts:t,attempt:r+1,pollInterval:s})}}},exports.BitcoinProviderAbstract=k,exports.BitcoinWallet=$t,exports.BitcoinWalletAbstract=z,exports.BitcoinWalletVoid=class extends z{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=qt,exports.DerivationPath=_,exports.ETH_ACCOUNT_PATH=N,exports.ETH_COIN_PATH=U,exports.JsonRpcBatchInternal=q,exports.LedgerSigner=W,exports.SolanaLedgerSigner=class{#p;#h;constructor(e,t){this.#p=Xt(e,!1),this.#h=t}async signTx(e,t){const r=await Nt(e,t),{signatures:s,messageBytes:n,...a}=w.compileTransaction(r),i=new T(this.#h),{address:o}=await i.getAddress(this.#p),d=w.address(S.base58.encode(Uint8Array.from(o)));if(!this.#d(d,s))return e;const{signature:u}=await i.signTransaction(this.#p,Buffer.from(n)),c=S.base58.encode(Uint8Array.from(u));return w.assertIsSignature(c),w.getBase64EncodedWireTransaction({...a,messageBytes:n,signatures:{...s,[d]:S.base58.decode(c)}})}#d(e,t){return e in t&&!t[e]}},exports.SolanaSigner=Ft,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.compileSolanaTx=e=>w.compileTransaction(e),exports.createPSBTV2=j,exports.createPsbt=E,exports.createTransferTx=D,exports.createWalletPolicy=function(e,t,r,s){const n=new u.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new u.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=Nt,exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=Ht,exports.getAddressFromXPub=function(e,t){const r=R(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=a.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=R,exports.getAppEth=O,exports.getBech32Address=K,exports.getBech32AddressFromXPub=function(e,t,r){return K(R(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return K(Buffer.from(s,"hex"),r)},exports.getEVMDerivationPath=L,exports.getEvmAddressFromPubKey=function(e){return n.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e){const t=await e.send(176,1,0,0),r=t.readUInt8(1),s=t.readUInt8(2+r),n=t.subarray(2,2+r),a=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:a.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=O(e),n=await s.getAddress(r??N,t,!0),a=new y;return a.publicKey=B.Buffer.from(n.publicKey,"hex"),a.chainCode=B.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=C(e);if(!n)return 0;const{fee:a}=M(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=O(e),a="EVM"===s?Ht(t,s,{pathSpec:r}):Ht(t,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(l.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaDerivationPath=Xt,exports.getSolanaProvider=({isTestnet:e,rpcUrl:t})=>{const r=w.createSolanaRpc(e?w.devnet(t):w.mainnet(t));return new Proxy(r,{get:(e,t,r)=>t===_t||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,r))})},exports.getSolanaPublicKeyFromLedger=async(e,t)=>{const r=new T(t),{address:s}=await r.getAddress(Xt(e,!1));return s},exports.getTransferTxDetails=function(e,t,r,s,n){const a=M(e,t,r,s,V(n));return a.inputs||console.log("Unable to construct transaction, fee needed: ",a.fee),a},exports.getVoidSigner=function(e,t){return new n.VoidSigner(e,t)},exports.getWalletFromMnemonic=function(e,t,r){if(!(t>=0&&t%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return n.HDNodeWallet.fromMnemonic(n.Mnemonic.fromPhrase(e),L(t,r))},exports.getXpubFromMnemonic=async function(e){if(!i.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await i.mnemonicToSeed(e);return a.fromSeed(t).derivePath(N).neutered().toBase58()},exports.isERC20Transfer=H,exports.isNativeTxn=F,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[_t],exports.maybeGetAssociatedTokenAccount=Lt,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),t)),{})},exports.onBalanceChange=async(e,t,r,s)=>{const n=new Set(e.map((e=>e.toLowerCase()))),a=new Set(t.map((e=>e.toLowerCase()))),i=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&a.has(e.to.toLowerCase())&&H(e,n)?s(e,{type:"erc20",contractAddress:e.to}):F(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",i);return{unsubscribe:()=>o.off("block",i)}},exports.openLedgerApp=async function(e,t){try{return(await e.send(224,216,0,0,Buffer.from(t,"ascii"))).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.psbt2ToPsbt0=J,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=M,exports.serializeSolanaTx=e=>w.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:r,provider:s})=>{const{value:n}=await s.getLatestBlockhash().send(),a=[b.getTransferSolInstruction({source:w.createNoopSigner(w.address(e)),destination:w.address(t),amount:r})];return w.pipe(w.createTransactionMessage({version:0}),(e=>w.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>w.setTransactionMessageFeePayer(w.address(e),t)),(e=>w.appendTransactionMessageInstructions(a,e)))},exports.transferToken=async({from:e,to:t,mint:r,amount:s,decimals:n,provider:a})=>{const{address:i}=await Lt({mint:w.address(r),owner:w.address(e),provider:a}),{address:o,exists:d}=await Lt({mint:w.address(r),owner:w.address(t),provider:a}),u=[];d||u.push(A.getCreateAssociatedTokenIdempotentInstruction({payer:w.createNoopSigner(w.address(e)),mint:w.address(r),owner:w.address(t),ata:o})),u.push(A.getTransferCheckedInstruction({amount:s,authority:w.createNoopSigner(w.address(e)),decimals:n,mint:w.address(r),destination:o,source:i}));const{value:c}=await a.getLatestBlockhash().send();return w.pipe(w.createTransactionMessage({version:0}),(e=>w.setTransactionMessageLifetimeUsingBlockhash(c,e)),(t=>w.setTransactionMessageFeePayer(w.address(e),t)),(e=>w.appendTransactionMessageInstructions(u,e)))};
package/dist/index.d.ts CHANGED
@@ -468,6 +468,8 @@ declare function getEvmAddressFromPubKey(pubKey: Buffer): string;
468
468
  */
469
469
  declare function getBtcAddressFromPubKey(pubKey: Buffer, network: Network): string;
470
470
 
471
+ declare const getEVMDerivationPath: (accountIndex: number, pathSpec: DerivationPath, withRoot?: boolean) => string;
472
+
471
473
  declare class LedgerSigner$1 extends AbstractSigner {
472
474
  readonly type: string;
473
475
  readonly path: string;
@@ -1434,7 +1436,7 @@ declare class StaticSigner extends WalletVoid implements Signer {
1434
1436
  */
1435
1437
  declare class SimpleSigner implements Signer {
1436
1438
  /**
1437
- * Node for `m/44'/9000'/0'`
1439
+ * Node for `m/44'/9000'/n'`
1438
1440
  * @private {BIP32Interface}
1439
1441
  */
1440
1442
  private accountNodeXP;
@@ -1537,7 +1539,7 @@ declare class SimpleLedgerSigner implements Signer {
1537
1539
  private accountNode;
1538
1540
  /**
1539
1541
  * @param {number} activeAccountIndex - the index of the primary account used for static signing
1540
- * @param {string} xpubXP - optional extended public key of `m/44'/9000'/0`
1542
+ * @param {string} xpubXP - optional extended public key of `m/44'/9000'/${activeAccountIndex}`
1541
1543
  */
1542
1544
  constructor(activeAccountIndex: number, provider: JsonRpcProvider, xpubXP?: string);
1543
1545
  private reSerializeTx;
@@ -1690,13 +1692,13 @@ type Params = {
1690
1692
  };
1691
1693
  declare const getUtxosByTxFromGlacier: ({ transactionHex, chainAlias, network, url, token, headers, }: Params) => Promise<Utxo<_avalabs_avalanchejs_dist_serializable_common_types.Serializable>[]>;
1692
1694
 
1693
- declare const getVmByChainAlias: (chainAlias: string) => "EVM" | "AVM" | "PVM";
1695
+ declare const getVmByChainAlias: (chainAlias: string) => "AVM" | "EVM" | "PVM";
1694
1696
 
1695
1697
  /**
1696
1698
  * Get the xpub for m/44'/9000'/0' from the given mnemonic
1697
1699
  * @param mnemonic
1698
1700
  */
1699
- declare function getXpubFromMnemonic(mnemonic: string): string;
1701
+ declare function getXpubFromMnemonic(mnemonic: string, accountIndex: number): string;
1700
1702
 
1701
1703
  /**
1702
1704
  * Verify the given address is a valid Avalanche bech32 address
@@ -1781,6 +1783,8 @@ declare function getMaximumUtxoSet({ wallet, utxos, sizeSupportedTx, limit, feeS
1781
1783
  */
1782
1784
  declare function verifyDerivationPath(path: string): any;
1783
1785
 
1786
+ declare const getAvalancheDerivationPath: (accountIndex: number, withRoot?: boolean) => string;
1787
+
1784
1788
  type index_AbstractProvider = AbstractProvider;
1785
1789
  declare const index_AbstractProvider: typeof AbstractProvider;
1786
1790
  type index_AddDelegatorTx = AddDelegatorTx;
@@ -1854,6 +1858,7 @@ declare const index_emptySignature: typeof emptySignature;
1854
1858
  declare const index_getAddressFromXpub: typeof getAddressFromXpub;
1855
1859
  declare const index_getAddressPublicKeyFromXpub: typeof getAddressPublicKeyFromXpub;
1856
1860
  declare const index_getAssetBalance: typeof getAssetBalance;
1861
+ declare const index_getAvalancheDerivationPath: typeof getAvalancheDerivationPath;
1857
1862
  declare const index_getLedgerProvider: typeof getLedgerProvider;
1858
1863
  declare const index_getMaximumUtxoSet: typeof getMaximumUtxoSet;
1859
1864
  declare const index_getPaginatedUTXOs: typeof getPaginatedUTXOs;
@@ -1894,20 +1899,23 @@ declare const index_sortUTXOsByAmountDescending: typeof sortUTXOsByAmountDescend
1894
1899
  declare const index_sortUTXOsStaking: typeof sortUTXOsStaking;
1895
1900
  declare const index_verifyDerivationPath: typeof verifyDerivationPath;
1896
1901
  declare namespace index {
1897
- export { index_AbstractProvider as AbstractProvider, index_AddressWallet as AddressWallet, index_DevnetContext as DevnetContext, index_FujiContext as FujiContext, index_JsonRpcProvider as JsonRpcProvider, index_LedgerLiveSigner as LedgerLiveSigner, index_LedgerSigner as LedgerSigner, index_LedgerWallet as LedgerWallet, index_MainnetContext as MainnetContext, index_MnemonicWallet as MnemonicWallet, index_MnemonicWalletVoid as MnemonicWalletVoid, index_P_CHAIN_TX_SIZE_LIMIT as P_CHAIN_TX_SIZE_LIMIT, index_SimpleLedgerSigner as SimpleLedgerSigner, index_SimpleSigner as SimpleSigner, index_SizeSupportedTx as SizeSupportedTx, index_StaticSigner as StaticSigner, index_TxType as TxType, index_WalletAbstract as WalletAbstract, index_WalletVoid as WalletVoid, index_addSignaturesToAvalancheTx as addSignaturesToAvalancheTx, index_convertGlacierUtxo as convertGlacierUtxo, index_createAvalancheEvmUnsignedTx as createAvalancheEvmUnsignedTx, index_createAvalancheUnsignedTx as createAvalancheUnsignedTx, index_digestMessage as digestMessage, index_emptySignature as emptySignature, index_getAddressFromXpub as getAddressFromXpub, index_getAddressPublicKeyFromXpub as getAddressPublicKeyFromXpub, index_getAssetBalance as getAssetBalance, index_getLedgerProvider as getLedgerProvider, index_getMaximumUtxoSet as getMaximumUtxoSet, index_getPaginatedUTXOs as getPaginatedUTXOs, index_getPchainUnixNow as getPchainUnixNow, index_getStakeForAddresses as getStakeForAddresses, index_getStakedAssetBalance as getStakedAssetBalance, index_getUTXOsForAddresses as getUTXOsForAddresses, index_getUnixNow as getUnixNow, index_getUtxosByTxFromGlacier as getUtxosByTxFromGlacier, index_getVmByChainAlias as getVmByChainAlias, index_getXpubFromMnemonic as getXpubFromMnemonic, index_isAddDelegatorTx as isAddDelegatorTx, index_isAddPermissionlessDelegatorTx as isAddPermissionlessDelegatorTx, index_isAddPermissionlessValidatorTx as isAddPermissionlessValidatorTx, index_isAddSubnetValidatorTx as isAddSubnetValidatorTx, index_isAddValidatorTx as isAddValidatorTx, index_isBaseTx as isBaseTx, index_isBech32Address as isBech32Address, index_isConvertSubnetToL1Tx as isConvertSubnetToL1Tx, index_isCreateChainTx as isCreateChainTx, index_isCreateSubnetTx as isCreateSubnetTx, index_isDisableL1ValidatorTx as isDisableL1ValidatorTx, index_isExportTx as isExportTx, index_isImportTx as isImportTx, index_isIncreaseL1ValidatorBalance as isIncreaseL1ValidatorBalance, index_isObsidianApp as isObsidianApp, index_isRegisterL1ValidatorTx as isRegisterL1ValidatorTx, index_isRemoveSubnetValidatorTx as isRemoveSubnetValidatorTx, index_isSetL1ValidatorWeightTx as isSetL1ValidatorWeightTx, index_isTransferSubnetOwnershipTx as isTransferSubnetOwnershipTx, index_isTransformSubnetTx as isTransformSubnetTx, index_parseAvalancheTx as parseAvalancheTx, index_populateCredential as populateCredential, index_signedTxToHex as signedTxToHex, index_sortUTXOsByAmount as sortUTXOsByAmount, index_sortUTXOsByAmountAscending as sortUTXOsByAmountAscending, index_sortUTXOsByAmountDescending as sortUTXOsByAmountDescending, index_sortUTXOsStaking as sortUTXOsStaking, index_verifyDerivationPath as verifyDerivationPath };
1902
+ export { index_AbstractProvider as AbstractProvider, index_AddressWallet as AddressWallet, index_DevnetContext as DevnetContext, index_FujiContext as FujiContext, index_JsonRpcProvider as JsonRpcProvider, index_LedgerLiveSigner as LedgerLiveSigner, index_LedgerSigner as LedgerSigner, index_LedgerWallet as LedgerWallet, index_MainnetContext as MainnetContext, index_MnemonicWallet as MnemonicWallet, index_MnemonicWalletVoid as MnemonicWalletVoid, index_P_CHAIN_TX_SIZE_LIMIT as P_CHAIN_TX_SIZE_LIMIT, index_SimpleLedgerSigner as SimpleLedgerSigner, index_SimpleSigner as SimpleSigner, index_SizeSupportedTx as SizeSupportedTx, index_StaticSigner as StaticSigner, index_TxType as TxType, index_WalletAbstract as WalletAbstract, index_WalletVoid as WalletVoid, index_addSignaturesToAvalancheTx as addSignaturesToAvalancheTx, index_convertGlacierUtxo as convertGlacierUtxo, index_createAvalancheEvmUnsignedTx as createAvalancheEvmUnsignedTx, index_createAvalancheUnsignedTx as createAvalancheUnsignedTx, index_digestMessage as digestMessage, index_emptySignature as emptySignature, index_getAddressFromXpub as getAddressFromXpub, index_getAddressPublicKeyFromXpub as getAddressPublicKeyFromXpub, index_getAssetBalance as getAssetBalance, index_getAvalancheDerivationPath as getAvalancheDerivationPath, index_getLedgerProvider as getLedgerProvider, index_getMaximumUtxoSet as getMaximumUtxoSet, index_getPaginatedUTXOs as getPaginatedUTXOs, index_getPchainUnixNow as getPchainUnixNow, index_getStakeForAddresses as getStakeForAddresses, index_getStakedAssetBalance as getStakedAssetBalance, index_getUTXOsForAddresses as getUTXOsForAddresses, index_getUnixNow as getUnixNow, index_getUtxosByTxFromGlacier as getUtxosByTxFromGlacier, index_getVmByChainAlias as getVmByChainAlias, index_getXpubFromMnemonic as getXpubFromMnemonic, index_isAddDelegatorTx as isAddDelegatorTx, index_isAddPermissionlessDelegatorTx as isAddPermissionlessDelegatorTx, index_isAddPermissionlessValidatorTx as isAddPermissionlessValidatorTx, index_isAddSubnetValidatorTx as isAddSubnetValidatorTx, index_isAddValidatorTx as isAddValidatorTx, index_isBaseTx as isBaseTx, index_isBech32Address as isBech32Address, index_isConvertSubnetToL1Tx as isConvertSubnetToL1Tx, index_isCreateChainTx as isCreateChainTx, index_isCreateSubnetTx as isCreateSubnetTx, index_isDisableL1ValidatorTx as isDisableL1ValidatorTx, index_isExportTx as isExportTx, index_isImportTx as isImportTx, index_isIncreaseL1ValidatorBalance as isIncreaseL1ValidatorBalance, index_isObsidianApp as isObsidianApp, index_isRegisterL1ValidatorTx as isRegisterL1ValidatorTx, index_isRemoveSubnetValidatorTx as isRemoveSubnetValidatorTx, index_isSetL1ValidatorWeightTx as isSetL1ValidatorWeightTx, index_isTransferSubnetOwnershipTx as isTransferSubnetOwnershipTx, index_isTransformSubnetTx as isTransformSubnetTx, index_parseAvalancheTx as parseAvalancheTx, index_populateCredential as populateCredential, index_signedTxToHex as signedTxToHex, index_sortUTXOsByAmount as sortUTXOsByAmount, index_sortUTXOsByAmountAscending as sortUTXOsByAmountAscending, index_sortUTXOsByAmountDescending as sortUTXOsByAmountDescending, index_sortUTXOsStaking as sortUTXOsStaking, index_verifyDerivationPath as verifyDerivationPath };
1898
1903
  export type { index_AddDelegatorTx as AddDelegatorTx, index_AddPermissionlessDelegatorTx as AddPermissionlessDelegatorTx, index_AddPermissionlessValidatorTx as AddPermissionlessValidatorTx, index_AddSubnetValidatorTx as AddSubnetValidatorTx, index_AddValidatorTx as AddValidatorTx, BaseTx$1 as BaseTx, index_ChainIDAlias as ChainIDAlias, index_ConvertSubnetToL1Tx as ConvertSubnetToL1Tx, index_CreateChainTx as CreateChainTx, index_CreateSubnetTx as CreateSubnetTx, index_DisableL1ValidatorTx as DisableL1ValidatorTx, index_ExportTx as ExportTx, index_FeeData as FeeData, index_GetAvaxBalanceDict as GetAvaxBalanceDict, index_GetStakedAvaxBalanceDict as GetStakedAvaxBalanceDict, index_GlacierOutput as GlacierOutput, index_ImportTx as ImportTx, index_IncreaseL1ValidatorBalanceTx as IncreaseL1ValidatorBalanceTx, index_LedgerGetXpubResponse as LedgerGetXpubResponse, index_ParseOptions as ParseOptions, index_RegisterL1ValidatorTx as RegisterL1ValidatorTx, index_RemoveSubnetValidatorTx as RemoveSubnetValidatorTx, index_SetL1ValidatorWeightTx as SetL1ValidatorWeightTx, index_SignMessageRequest as SignMessageRequest, index_SignTxBufferRequest as SignTxBufferRequest, index_SignTxRequest as SignTxRequest, index_Signer as Signer, TransferSubnetOwnershipTx$1 as TransferSubnetOwnershipTx, index_TransformSubnetTx as TransformSubnetTx, index_Tx as Tx, index_TxBase as TxBase, index_UnknownTx as UnknownTx };
1899
1904
  }
1900
1905
 
1906
+ type DerivationPathOptions = {
1907
+ withRoot?: boolean;
1908
+ pathSpec?: DerivationPath;
1909
+ };
1901
1910
  /**
1902
1911
  * Get the derivation path used by wallet addresses
1903
1912
  * @param addressIndex Which index is the address on
1904
- * @param pathSpec BIP44 vs LedgerLive
1905
1913
  * @param vm Which VM is this address on. Coin index changes between Avalanche and EVM
1906
- * @param withRoot If false, skips the "m/" prefix. Needed for Solana Ledger app.
1914
+ * @param options
1915
+ * @param options.withRoot If false, skips the "m/" prefix. Needed for Solana Ledger app.
1916
+ * @param options.pathSpec Only relevant (and required) for EVM.
1907
1917
  */
1908
- declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, // Irrelevant for Solana
1909
- vm: 'SVM', withRoot?: boolean): string;
1910
- declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, vm: 'EVM' | 'AVM' | 'PVM', withRoot?: never): string;
1918
+ declare function getAddressDerivationPath(accountIndex: number, vm: 'SVM' | 'EVM' | 'AVM' | 'PVM', options?: DerivationPathOptions): string;
1911
1919
 
1912
1920
  /**
1913
1921
  * Get the public key from a given private key.
@@ -2050,5 +2058,5 @@ declare class SolanaLedgerSigner {
2050
2058
  signTx(base64EncodedTx: string, provider: SolanaProvider): Promise<string>;
2051
2059
  }
2052
2060
 
2053
- export { index as Avalanche, BitcoinLedgerWallet, BitcoinProvider, BitcoinProviderAbstract, BitcoinWallet, BitcoinWalletAbstract, BitcoinWalletVoid, BtcNetworks, DerivationPath, ETH_ACCOUNT_PATH, ETH_COIN_PATH, JsonRpcBatchInternal, LedgerSigner$1 as LedgerSigner, SolanaLedgerSigner, SolanaSigner, addEncodedSigToPsbt, compileSolanaTx, createPSBTV2, createPsbt, createTransferTx, createWalletPolicy, deserializeTransactionMessage, formatAddressForNetworkBech32, getAddressDerivationPath, getAddressFromXPub, getAddressPrivateKeyFromXPriv, getAddressPublicKeyFromXPub, getAppEth, getBech32Address, getBech32AddressFromXPub, getBtcAddressFromPubKey, getEvmAddressFromPubKey, getLedgerAppInfo, getLedgerExtendedPublicKey, getMaxTransferAmount, getPubKeyFromTransport, getPublicKeyFromPrivateKey, getSolanaDerivationPath, getSolanaProvider, getSolanaPublicKeyFromLedger, getTransferTxDetails, getVoidSigner, getWalletFromMnemonic, getXpubFromMnemonic$1 as getXpubFromMnemonic, isERC20Transfer, isNativeTxn, isSolanaProvider, maybeGetAssociatedTokenAccount, omitUndefinedKeys, onBalanceChange, openLedgerApp, psbt2ToPsbt0, quitLedgerApp, selectUtxos, serializeSolanaTx, transferSol, transferToken };
2061
+ export { index as Avalanche, BitcoinLedgerWallet, BitcoinProvider, BitcoinProviderAbstract, BitcoinWallet, BitcoinWalletAbstract, BitcoinWalletVoid, BtcNetworks, DerivationPath, ETH_ACCOUNT_PATH, ETH_COIN_PATH, JsonRpcBatchInternal, LedgerSigner$1 as LedgerSigner, SolanaLedgerSigner, SolanaSigner, addEncodedSigToPsbt, compileSolanaTx, createPSBTV2, createPsbt, createTransferTx, createWalletPolicy, deserializeTransactionMessage, formatAddressForNetworkBech32, getAddressDerivationPath, getAddressFromXPub, getAddressPrivateKeyFromXPriv, getAddressPublicKeyFromXPub, getAppEth, getBech32Address, getBech32AddressFromXPub, getBtcAddressFromPubKey, getEVMDerivationPath, getEvmAddressFromPubKey, getLedgerAppInfo, getLedgerExtendedPublicKey, getMaxTransferAmount, getPubKeyFromTransport, getPublicKeyFromPrivateKey, getSolanaDerivationPath, getSolanaProvider, getSolanaPublicKeyFromLedger, getTransferTxDetails, getVoidSigner, getWalletFromMnemonic, getXpubFromMnemonic$1 as getXpubFromMnemonic, isERC20Transfer, isNativeTxn, isSolanaProvider, maybeGetAssociatedTokenAccount, omitUndefinedKeys, onBalanceChange, openLedgerApp, psbt2ToPsbt0, quitLedgerApp, selectUtxos, serializeSolanaTx, transferSol, transferToken };
2054
2062
  export type { BitcoinHistoryTx, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinLedgerInputUTXO, BitcoinOutputUTXO, BitcoinTx, SolanaProvider };
@@ -39,3 +39,4 @@ export { signedTxToHex } from './utils/signedTxToHex.js';
39
39
  export { sortUTXOsByAmount, sortUTXOsByAmountAscending, sortUTXOsByAmountDescending, sortUTXOsStaking } from './utils/sortUTXOs.js';
40
40
  export { P_CHAIN_TX_SIZE_LIMIT, SizeSupportedTx, getMaximumUtxoSet } from './utils/txSizeLimits.js';
41
41
  export { verifyDerivationPath } from './utils/verifyDerivationPath.js';
42
+ export { getAvalancheDerivationPath } from './utils/getAvalancheDerivationPath.js';
@@ -1 +1 @@
1
- export{TxType,isAddDelegatorTx,isAddPermissionlessDelegatorTx,isAddPermissionlessValidatorTx,isAddSubnetValidatorTx,isAddValidatorTx,isBaseTx,isConvertSubnetToL1Tx,isCreateChainTx,isCreateSubnetTx,isDisableL1ValidatorTx,isExportTx,isImportTx,isIncreaseL1ValidatorBalance,isRegisterL1ValidatorTx,isRemoveSubnetValidatorTx,isSetL1ValidatorWeightTx,isTransferSubnetOwnershipTx,isTransformSubnetTx}from"./models.js";export{WalletAbstract}from"./wallets/WalletAbstract.js";export{WalletVoid}from"./wallets/WalletVoid.js";export{isObsidianApp}from"./wallets/ledger/isObsidianApp.js";export{getLedgerProvider}from"./wallets/ledger/getLedgerProvider.js";export{AddressWallet}from"./wallets/AddressWallet.js";export{MnemonicWalletVoid}from"./wallets/legacy/MnemonicWalletVoid.js";export{LedgerWallet}from"./wallets/legacy/LedgerWallet.js";export{MnemonicWallet}from"./wallets/legacy/MnemonicWallet.js";export{StaticSigner}from"./wallets/StaticSigner.js";export{SimpleSigner}from"./wallets/SimpleSigner.js";export{LedgerSigner}from"./wallets/ledger/LedgerSigner.js";export{SimpleLedgerSigner}from"./wallets/ledger/SimpleLedgerSigner.js";export{LedgerLiveSigner}from"./wallets/ledger/LedgerLiveSigner.js";export{AbstractProvider}from"./providers/AbstractProvider.js";export{JsonRpcProvider}from"./providers/JsonRpcProvider.js";export{DevnetContext,FujiContext,MainnetContext}from"./providers/constants.js";export{addSignaturesToAvalancheTx}from"./utils/addSignaturesToAvalancheTx.js";export{convertGlacierUtxo}from"./utils/convertGlacierUtxo.js";export{createAvalancheEvmUnsignedTx}from"./utils/createAvalancheEvmUnsignedTx.js";export{createAvalancheUnsignedTx}from"./utils/createAvalancheUnsignedTx.js";export{digestMessage}from"./utils/digestMessage.js";export{getAddressFromXpub}from"./utils/getAddressFromXpub.js";export{getAddressPublicKeyFromXpub}from"./utils/getAddressPublicKeyFromXpub.js";export{getPaginatedUTXOs,getUTXOsForAddresses}from"./utils/getAllUTXOs.js";export{getAssetBalance}from"./utils/getAssetBalance.js";export{getPchainUnixNow}from"./utils/getPchainUnixNow.js";export{getStakedAssetBalance}from"./utils/getStakedAssetBalance.js";export{getStakeForAddresses}from"./utils/getStakeForAddresses.js";export{getUnixNow}from"./utils/getUnixNow.js";export{getUtxosByTxFromGlacier}from"./utils/getUtxosByTxFromGlacier.js";export{getVmByChainAlias}from"./utils/getVmByChainAlias.js";export{getXpubFromMnemonic}from"./utils/getXpubFromMnemonic.js";export{isBech32Address}from"./utils/isBech32Address.js";export{parseAvalancheTx}from"./utils/parseAvalancheTx.js";export{emptySignature,populateCredential}from"./utils/populateCredential.js";export{signedTxToHex}from"./utils/signedTxToHex.js";export{sortUTXOsByAmount,sortUTXOsByAmountAscending,sortUTXOsByAmountDescending,sortUTXOsStaking}from"./utils/sortUTXOs.js";export{P_CHAIN_TX_SIZE_LIMIT,SizeSupportedTx,getMaximumUtxoSet}from"./utils/txSizeLimits.js";export{verifyDerivationPath}from"./utils/verifyDerivationPath.js";
1
+ export{TxType,isAddDelegatorTx,isAddPermissionlessDelegatorTx,isAddPermissionlessValidatorTx,isAddSubnetValidatorTx,isAddValidatorTx,isBaseTx,isConvertSubnetToL1Tx,isCreateChainTx,isCreateSubnetTx,isDisableL1ValidatorTx,isExportTx,isImportTx,isIncreaseL1ValidatorBalance,isRegisterL1ValidatorTx,isRemoveSubnetValidatorTx,isSetL1ValidatorWeightTx,isTransferSubnetOwnershipTx,isTransformSubnetTx}from"./models.js";export{WalletAbstract}from"./wallets/WalletAbstract.js";export{WalletVoid}from"./wallets/WalletVoid.js";export{isObsidianApp}from"./wallets/ledger/isObsidianApp.js";export{getLedgerProvider}from"./wallets/ledger/getLedgerProvider.js";export{AddressWallet}from"./wallets/AddressWallet.js";export{MnemonicWalletVoid}from"./wallets/legacy/MnemonicWalletVoid.js";export{LedgerWallet}from"./wallets/legacy/LedgerWallet.js";export{MnemonicWallet}from"./wallets/legacy/MnemonicWallet.js";export{StaticSigner}from"./wallets/StaticSigner.js";export{SimpleSigner}from"./wallets/SimpleSigner.js";export{LedgerSigner}from"./wallets/ledger/LedgerSigner.js";export{SimpleLedgerSigner}from"./wallets/ledger/SimpleLedgerSigner.js";export{LedgerLiveSigner}from"./wallets/ledger/LedgerLiveSigner.js";export{AbstractProvider}from"./providers/AbstractProvider.js";export{JsonRpcProvider}from"./providers/JsonRpcProvider.js";export{DevnetContext,FujiContext,MainnetContext}from"./providers/constants.js";export{addSignaturesToAvalancheTx}from"./utils/addSignaturesToAvalancheTx.js";export{convertGlacierUtxo}from"./utils/convertGlacierUtxo.js";export{createAvalancheEvmUnsignedTx}from"./utils/createAvalancheEvmUnsignedTx.js";export{createAvalancheUnsignedTx}from"./utils/createAvalancheUnsignedTx.js";export{digestMessage}from"./utils/digestMessage.js";export{getAddressFromXpub}from"./utils/getAddressFromXpub.js";export{getAddressPublicKeyFromXpub}from"./utils/getAddressPublicKeyFromXpub.js";export{getPaginatedUTXOs,getUTXOsForAddresses}from"./utils/getAllUTXOs.js";export{getAssetBalance}from"./utils/getAssetBalance.js";export{getPchainUnixNow}from"./utils/getPchainUnixNow.js";export{getStakedAssetBalance}from"./utils/getStakedAssetBalance.js";export{getStakeForAddresses}from"./utils/getStakeForAddresses.js";export{getUnixNow}from"./utils/getUnixNow.js";export{getUtxosByTxFromGlacier}from"./utils/getUtxosByTxFromGlacier.js";export{getVmByChainAlias}from"./utils/getVmByChainAlias.js";export{getXpubFromMnemonic}from"./utils/getXpubFromMnemonic.js";export{isBech32Address}from"./utils/isBech32Address.js";export{parseAvalancheTx}from"./utils/parseAvalancheTx.js";export{emptySignature,populateCredential}from"./utils/populateCredential.js";export{signedTxToHex}from"./utils/signedTxToHex.js";export{sortUTXOsByAmount,sortUTXOsByAmountAscending,sortUTXOsByAmountDescending,sortUTXOsStaking}from"./utils/sortUTXOs.js";export{P_CHAIN_TX_SIZE_LIMIT,SizeSupportedTx,getMaximumUtxoSet}from"./utils/txSizeLimits.js";export{verifyDerivationPath}from"./utils/verifyDerivationPath.js";export{getAvalancheDerivationPath}from"./utils/getAvalancheDerivationPath.js";
@@ -0,0 +1,3 @@
1
+ declare const getAvalancheDerivationPath: (accountIndex: number, withRoot?: boolean) => string;
2
+
3
+ export { getAvalancheDerivationPath };
@@ -0,0 +1 @@
1
+ const o=(o,t=!0)=>`${t?"m/":""}44'/9000'/${o}'/0/0`;export{o as getAvalancheDerivationPath};
@@ -1,3 +1,3 @@
1
- declare const getVmByChainAlias: (chainAlias: string) => "EVM" | "AVM" | "PVM";
1
+ declare const getVmByChainAlias: (chainAlias: string) => "AVM" | "EVM" | "PVM";
2
2
 
3
3
  export { getVmByChainAlias };
@@ -2,6 +2,6 @@
2
2
  * Get the xpub for m/44'/9000'/0' from the given mnemonic
3
3
  * @param mnemonic
4
4
  */
5
- declare function getXpubFromMnemonic(mnemonic: string): string;
5
+ declare function getXpubFromMnemonic(mnemonic: string, accountIndex: number): string;
6
6
 
7
7
  export { getXpubFromMnemonic };
@@ -1 +1 @@
1
- import{validateMnemonic as r,mnemonicToSeedSync as e}from"bip39";import{fromSeed as o}from"bip32";function t(t){if(!r(t))throw new Error("Invalid mnemonic phrase.");const i=e(t);return o(i).derivePath("44'/9000'/0'").neutered().toBase58()}export{t as getXpubFromMnemonic};
1
+ import{validateMnemonic as r,mnemonicToSeedSync as e}from"bip39";import{fromSeed as o}from"bip32";function t(t,i){if(!r(t))throw new Error("Invalid mnemonic phrase.");const n=e(t);return o(n).derivePath(`44'/9000'/${i}'`).neutered().toBase58()}export{t as getXpubFromMnemonic};
@@ -10,7 +10,7 @@ import { Signer, SignTxRequest, SignTxBufferRequest, SignMessageRequest } from '
10
10
  */
11
11
  declare class SimpleSigner implements Signer {
12
12
  /**
13
- * Node for `m/44'/9000'/0'`
13
+ * Node for `m/44'/9000'/n'`
14
14
  * @private {BIP32Interface}
15
15
  */
16
16
  private accountNodeXP;
@@ -1 +1 @@
1
- import{addTxSignatures as e,secp256k1 as t}from"@avalabs/avalanchejs";import{fromSeed as i}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import"@ledgerhq/hw-app-eth";import"ethers";import{getAddressDerivationPath as n}from"../../utils/getAddressDerivationPath.js";import"hdkey";import{DerivationPath as o}from"../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../utils/digestMessage.js";import"../utils/getAssetBalance.js";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import"bip32-path";class c{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!r(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const a=s(e),c=i(a);this.accountNodeXP=c.derivePath("m/44'/9000'/0'");const d=c.derivePath(n(t,o.BIP44,"EVM"));this.signerNodeEVM=d,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,i)=>{const r=this.accountNodeXP.derivePath(`${t?1:0}/${i}`);if(!r.privateKey)throw new Error("Unable to get private key.");return e.push(r.privateKey),e}),[])}getSigningKeys(e,t,i){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/${this.activeAccountIndex}`);if(!r.privateKey)throw new Error("Unable to derive X/P private key.");const s=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(i,!0);return[r.privateKey,...s,...e]}if("PVM"===e)return[r.privateKey,...s]}async signTx(t){const{tx:i,externalIndices:r,internalIndices:s}=t,n=i.getVM(),o=this.getSigningKeys(n,r,s);if(!o?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await e({unsignedTx:i,privateKeys:o}),t.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const i=this.getActiveAccountNode(e.chain);if(!i.privateKey)throw Error("Unable to sign message, key not found.");const r=a(e.message),s=await t.signHash(r,i.privateKey);return Buffer.from(s)}}export{c as SimpleSigner};
1
+ import{addTxSignatures as e,secp256k1 as t}from"@avalabs/avalanchejs";import{fromSeed as i}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import"@ledgerhq/hw-app-eth";import"ethers";import{DerivationPath as n}from"../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import{getAddressDerivationPath as o}from"../../utils/getAddressDerivationPath.js";import"hdkey";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../utils/digestMessage.js";import"../utils/getAssetBalance.js";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import"bip32-path";class c{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!r(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const a=s(e),c=i(a);this.accountNodeXP=c.derivePath(`m/44'/9000'/${t}'`);const p=c.derivePath(o(t,"EVM",{pathSpec:n.BIP44}));this.signerNodeEVM=p,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,i)=>{const r=this.accountNodeXP.derivePath(`${t?1:0}/${i}`);if(!r.privateKey)throw new Error("Unable to get private key.");return e.push(r.privateKey),e}),[])}getSigningKeys(e,t,i){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 s=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(i,!0);return[r.privateKey,...s,...e]}if("PVM"===e)return[r.privateKey,...s]}async signTx(t){const{tx:i,externalIndices:r,internalIndices:s}=t,n=i.getVM(),o=this.getSigningKeys(n,r,s);if(!o?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await e({unsignedTx:i,privateKeys:o}),t.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 i=this.getActiveAccountNode(e.chain);if(!i.privateKey)throw Error("Unable to sign message, key not found.");const r=a(e.message),s=await t.signHash(r,i.privateKey);return Buffer.from(s)}}export{c as SimpleSigner};
@@ -15,7 +15,7 @@ declare class SimpleLedgerSigner implements Signer {
15
15
  private accountNode;
16
16
  /**
17
17
  * @param {number} activeAccountIndex - the index of the primary account used for static signing
18
- * @param {string} xpubXP - optional extended public key of `m/44'/9000'/0`
18
+ * @param {string} xpubXP - optional extended public key of `m/44'/9000'/${activeAccountIndex}`
19
19
  */
20
20
  constructor(activeAccountIndex: number, provider: JsonRpcProvider, xpubXP?: string);
21
21
  private reSerializeTx;
@@ -1 +1 @@
1
- import{utils as t,EVMUnsignedTx as r,UnsignedTx as e}from"@avalabs/avalanchejs";import s from"bip32-path";import{getTxOutputAddresses as i}from"../../utils/getTxOutputAddresses.js";import{ZondaxProvider as n}from"./ZondaxProvider.js";import{fromBase58 as o}from"bip32";import"../../utils/addSignaturesToAvalancheTx.js";import"../../utils/convertGlacierUtxo.js";import"../../utils/createAvalancheEvmUnsignedTx.js";import"../../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../../utils/digestMessage.js";import"../../utils/getAssetBalance.js";import"../../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../../utils/parseAvalancheTx.js";import"../../utils/populateCredential.js";import"../../utils/txSizeLimits.js";const{parse:c}=t;class g{constructor(t,r,e){this.activeAccountIndex=t,this.provider=r,e&&(this.accountNode=o(e))}accountNode;reSerializeTx(t,s){return t instanceof r||"C"===s?r.fromJSON(JSON.stringify(t.toJSON())):e.fromJSON(JSON.stringify(t.toJSON()))}getChainAlias(t){return"EVM"===t.getVM()?"C":"X"}getAccountPath(t){switch(t){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(t,r){if(!this.accountNode)return null;const{publicKey:e}=this.accountNode.derivePath(t),s=this.provider.getAddress(e,r);return Buffer.from(c(s)[2]).toString("hex")}getAddressPathMap(t){const{tx:r,externalIndices:e,internalIndices:s}=t,i=this.getChainAlias(r),n=`0/${this.activeAccountIndex}`,o=new Map;if("C"===i||!this.accountNode)return o;const a=[n,...(e??[]).map((t=>`0/${t}`)),...(s??[]).map((t=>`1/${t}`))];for(const t of a){const r=this.getAddressOfPath(t,i);r&&o.set(r,t)}return o}getAddressBipPaths(t,r){return 0===r.size?[s.fromString(`0/${this.activeAccountIndex}`)]:t.reduce(((t,e)=>{const i=r.get(Buffer.from(e).toString("hex"));return i&&t.push(s.fromString(i)),t}),[])}async signTx(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=this.getChainAlias(t.tx),e=this.reSerializeTx(t.tx,r),s=Buffer.from(e.toBytes()),n=this.getAddressPathMap(t),o=this.getAddressBipPaths(e.getAddresses(),n),a=this.getAddressBipPaths([...i(e)],n);return(await this.signTxBuffer({buffer:s,chain:r,transport:t.transport,signers:o,change:a})).forEach((t=>{e.addSignature(t)})),e}async signTxBuffer(t){if(!t.transport)throw new Error("Ledger transport not provided");if(!t.signers)throw new Error("Signers not provided");const r=t.change||[],e=s.fromString(this.getAccountPath(t.chain));return[...(await n.signTx(t.transport,t.buffer,e,t.signers,r)).signatures.values()]}async signMessage(t){if(!t.transport||!t.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const r=t.signer||s.fromString(`0/${this.activeAccountIndex}`);if(2!=r.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const e=a(t.message),i=(await n.signHash(t.transport,e,s.fromString(this.getAccountPath(t.chain)),[r])).signatures.get(r.toString(!0));if(!i)throw new Error("Failed to sign message.");return i}}export{g as SimpleLedgerSigner};
1
+ import{utils as t,EVMUnsignedTx as r,UnsignedTx as e}from"@avalabs/avalanchejs";import s from"bip32-path";import{getTxOutputAddresses as i}from"../../utils/getTxOutputAddresses.js";import{ZondaxProvider as n}from"./ZondaxProvider.js";import{fromBase58 as o}from"bip32";import"../../utils/addSignaturesToAvalancheTx.js";import"../../utils/convertGlacierUtxo.js";import"../../utils/createAvalancheEvmUnsignedTx.js";import"../../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../../utils/digestMessage.js";import"../../utils/getAssetBalance.js";import"../../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../../utils/parseAvalancheTx.js";import"../../utils/populateCredential.js";import"../../utils/txSizeLimits.js";const{parse:c}=t;class g{constructor(t,r,e){this.activeAccountIndex=t,this.provider=r,e&&(this.accountNode=o(e))}accountNode;reSerializeTx(t,s){return t instanceof r||"C"===s?r.fromJSON(JSON.stringify(t.toJSON())):e.fromJSON(JSON.stringify(t.toJSON()))}getChainAlias(t){return"EVM"===t.getVM()?"C":"X"}getAccountPath(t){switch(t){case"X":case"P":return`m/44'/9000'/${this.activeAccountIndex}'`;case"C":return"m/44'/60'/0'"}}getAddressOfPath(t,r){if(!this.accountNode)return null;const{publicKey:e}=this.accountNode.derivePath(t),s=this.provider.getAddress(e,r);return Buffer.from(c(s)[2]).toString("hex")}getAddressPathMap(t){const{tx:r,externalIndices:e,internalIndices:s}=t,i=this.getChainAlias(r),n="EVM"===t.tx.getVM()?`0/${this.activeAccountIndex}`:"0/0",o=new Map;if("C"===i||!this.accountNode)return o;const a=[n,...(e??[]).map((t=>`0/${t}`)),...(s??[]).map((t=>`1/${t}`))];for(const t of a){const r=this.getAddressOfPath(t,i);r&&o.set(r,t)}return o}getAddressBipPaths(t,r,e){return 0===r.size?[s.fromString("C"===e?`0/${this.activeAccountIndex}`:"0/0")]:t.reduce(((t,e)=>{const i=r.get(Buffer.from(e).toString("hex"));return i&&t.push(s.fromString(i)),t}),[])}async signTx(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=this.getChainAlias(t.tx),e=this.reSerializeTx(t.tx,r),s=Buffer.from(e.toBytes()),n=this.getAddressPathMap(t),o=this.getAddressBipPaths(e.getAddresses(),n,r),a=this.getAddressBipPaths([...i(e)],n,r);return(await this.signTxBuffer({buffer:s,chain:r,transport:t.transport,signers:o,change:a})).forEach((t=>{e.addSignature(t)})),e}async signTxBuffer(t){if(!t.transport)throw new Error("Ledger transport not provided");if(!t.signers)throw new Error("Signers not provided");const r=t.change||[],e=s.fromString(this.getAccountPath(t.chain));return[...(await n.signTx(t.transport,t.buffer,e,t.signers,r)).signatures.values()]}async signMessage(t){if(!t.transport||!t.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const r="C"===t.chain?this.activeAccountIndex:0,e=t.signer||s.fromString(`0/${r}`);if(2!=e.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const i=a(t.message),o=(await n.signHash(t.transport,i,s.fromString(this.getAccountPath(t.chain)),[e])).signatures.get(e.toString(!0));if(!o)throw new Error("Failed to sign message.");return o}}export{g as SimpleLedgerSigner};
@@ -1 +1 @@
1
- import{MnemonicWalletVoid as r}from"./MnemonicWalletVoid.js";import{getAppEth as t}from"../../../EVM/utils/getAppEth.js";import{SigningKey as e}from"ethers";import{getAddressDerivationPath as s}from"../../../utils/getAddressDerivationPath.js";import{utils as i}from"@avalabs/avalanchejs";import"hdkey";import{DerivationPath as n}from"../../../EVM/constants.js";import{fromPublicKey as o}from"bip32";import"bip39";import"bitcoinjs-lib";import{strip0x as a}from"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import d from"bip32-path";import{isObsidianApp as p}from"../ledger/isObsidianApp.js";import{ZondaxProvider as f}from"../ledger/ZondaxProvider.js";import{getTxOutputAddresses as m}from"../../utils/getTxOutputAddresses.js";const{parse:c}=i;class g extends r{constructor(r,t,e){super(r,t,e)}getAdditionalAddressesByIndices(r,t,e){return"C"===e?[]:r.map((r=>{const s=this.getAddressAtIndex(r,t,e),[,,i]=c(s);return Buffer.from(i).toString("hex")}))}static async fromTransport(r,i){if(await p(r))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const d=t(r),m=await f.getXPUB(r,g.getAccountPath("X")),c=o(m.pubKey,m.chainCode),h=s(0,n.BIP44,"EVM"),u=await d.getAddress(h,!1),l=e.computePublicKey(Buffer.from(u.publicKey,"hex"),!0),w=Buffer.from(a(l),"hex");return new g(c.toBase58(),w,i)}static getAccountPath(r){switch(r){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(r){throw new Error("not implemented")}filterOwnedAddresses(r,t,e){const s=this.getInternalRawAddresses().map((r=>r.toString("hex"))),i=this.getExternalRawAddresses().map((r=>r.toString("hex"))),n=new Set([...s,...e??[]]),o=new Set([...i,...t??[]]),a=new Set;return r.forEach((r=>{const t=r.toString("hex");if(n.has(t)){const r=[...n].indexOf(t);a.add(`1/${r}`)}else if(o.has(t)){const r=[...o].indexOf(t);a.add(`0/${r}`)}})),a}async signTx(r){if(!r.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:e,internalIndices:s}=r,i=t.getVM(),n=Buffer.from(t.toBytes()),o="EVM"===i?"C":"X",a=t.getAddresses().map((r=>Buffer.from(r))),p=this.getAdditionalAddressesByIndices(e??[],!1,o),f=this.getAdditionalAddressesByIndices(s??[],!0,o),c=[...this.filterOwnedAddresses(a,p,f).values()].map((r=>d.fromString(r))),g=[...m(t)].map((r=>Buffer.from(r))),h=[...this.filterOwnedAddresses(g).values()].map((r=>d.fromString(r)));return(await this.signTxBuffer({buffer:n,chain:o,transport:r.transport,signers:c,change:h})).forEach((r=>{t.addSignature(r)})),t}async signTxBuffer(r){if(!r.transport)throw new Error("Ledger transport not provided");if(!r.signers)throw new Error("Signers not provided");const t=r.change||[],e=d.fromString(g.getAccountPath(r.chain));return[...(await f.signTx(r.transport,r.buffer,e,r.signers,t)).signatures.values()]}}export{g as LedgerWallet};
1
+ import{MnemonicWalletVoid as r}from"./MnemonicWalletVoid.js";import{getAppEth as t}from"../../../EVM/utils/getAppEth.js";import{SigningKey as e}from"ethers";import{DerivationPath as s}from"../../../EVM/constants.js";import{fromPublicKey as i}from"bip32";import"bip39";import"bitcoinjs-lib";import{strip0x as n}from"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import o from"bip32-path";import{isObsidianApp as a}from"../ledger/isObsidianApp.js";import{ZondaxProvider as d}from"../ledger/ZondaxProvider.js";import{getTxOutputAddresses as p}from"../../utils/getTxOutputAddresses.js";import{getAddressDerivationPath as f}from"../../../utils/getAddressDerivationPath.js";import{utils as m}from"@avalabs/avalanchejs";import"hdkey";const{parse:c}=m;class g extends r{constructor(r,t,e){super(r,t,e)}getAdditionalAddressesByIndices(r,t,e){return"C"===e?[]:r.map((r=>{const s=this.getAddressAtIndex(r,t,e),[,,i]=c(s);return Buffer.from(i).toString("hex")}))}static async fromTransport(r,o){if(await a(r))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const p=t(r),m=await d.getXPUB(r,g.getAccountPath("X")),c=i(m.pubKey,m.chainCode),h=f(0,"EVM",{pathSpec:s.BIP44}),u=await p.getAddress(h,!1),l=e.computePublicKey(Buffer.from(u.publicKey,"hex"),!0),w=Buffer.from(n(l),"hex");return new g(c.toBase58(),w,o)}static getAccountPath(r){switch(r){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(r){throw new Error("not implemented")}filterOwnedAddresses(r,t,e){const s=this.getInternalRawAddresses().map((r=>r.toString("hex"))),i=this.getExternalRawAddresses().map((r=>r.toString("hex"))),n=new Set([...s,...e??[]]),o=new Set([...i,...t??[]]),a=new Set;return r.forEach((r=>{const t=r.toString("hex");if(n.has(t)){const r=[...n].indexOf(t);a.add(`1/${r}`)}else if(o.has(t)){const r=[...o].indexOf(t);a.add(`0/${r}`)}})),a}async signTx(r){if(!r.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:e,internalIndices:s}=r,i=t.getVM(),n=Buffer.from(t.toBytes()),a="EVM"===i?"C":"X",d=t.getAddresses().map((r=>Buffer.from(r))),f=this.getAdditionalAddressesByIndices(e??[],!1,a),m=this.getAdditionalAddressesByIndices(s??[],!0,a),c=[...this.filterOwnedAddresses(d,f,m).values()].map((r=>o.fromString(r))),g=[...p(t)].map((r=>Buffer.from(r))),h=[...this.filterOwnedAddresses(g).values()].map((r=>o.fromString(r)));return(await this.signTxBuffer({buffer:n,chain:a,transport:r.transport,signers:c,change:h})).forEach((r=>{t.addSignature(r)})),t}async signTxBuffer(r){if(!r.transport)throw new Error("Ledger transport not provided");if(!r.signers)throw new Error("Signers not provided");const t=r.change||[],e=o.fromString(g.getAccountPath(r.chain));return[...(await d.signTx(r.transport,r.buffer,e,r.signers,t)).signatures.values()]}}export{g as LedgerWallet};
@@ -1 +1 @@
1
- import{MnemonicWalletVoid as e}from"./MnemonicWalletVoid.js";import{utils as t,addTxSignatures as r}from"@avalabs/avalanchejs";import{validateMnemonic as i,mnemonicToSeedSync as n}from"bip39";import{fromBase58 as o,fromSeed as s}from"bip32";import"@ledgerhq/hw-app-eth";import{SigningKey as a}from"ethers";import{getAddressDerivationPath as c}from"../../../utils/getAddressDerivationPath.js";import"hdkey";import{DerivationPath as h}from"../../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";const{strip0x:p}=t;class v extends e{constructor(e,t,r){const i=o(e).neutered(),n=new a(t),s=Buffer.from(p(n.compressedPublicKey),"hex");super(i.toBase58(),s,r),this.evmPrivKey=t,this.accountNode=o(e)}accountNode;static fromMnemonic(e,t){if(!i(e))throw new Error("Invalid mnemonic phrase.");const r=n(e),o=s(r),a=o.derivePath("m/44'/9000'/0'"),p=o.derivePath(c(0,h.BIP44,"EVM"));if(!p.privateKey)throw new Error("Unable to derive EVM private key.");return new v(a.toBase58(),p.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await r({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:i}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(i),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}export{v as MnemonicWallet};
1
+ import{MnemonicWalletVoid as e}from"./MnemonicWalletVoid.js";import{utils as t,addTxSignatures as r}from"@avalabs/avalanchejs";import{validateMnemonic as i,mnemonicToSeedSync as n}from"bip39";import{fromBase58 as o,fromSeed as s}from"bip32";import"@ledgerhq/hw-app-eth";import{SigningKey as a}from"ethers";import{DerivationPath as p}from"../../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import{getAddressDerivationPath as c}from"../../../utils/getAddressDerivationPath.js";import"hdkey";const{strip0x:h}=t;class v extends e{constructor(e,t,r){const i=o(e).neutered(),n=new a(t),s=Buffer.from(h(n.compressedPublicKey),"hex");super(i.toBase58(),s,r),this.evmPrivKey=t,this.accountNode=o(e)}accountNode;static fromMnemonic(e,t){if(!i(e))throw new Error("Invalid mnemonic phrase.");const r=n(e),o=s(r),a=o.derivePath("m/44'/9000'/0'"),h=o.derivePath(c(0,"EVM",{pathSpec:p.BIP44}));if(!h.privateKey)throw new Error("Unable to derive EVM private key.");return new v(a.toBase58(),h.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await r({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:i}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(i),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}export{v as MnemonicWallet};
@@ -1 +1 @@
1
- import{fromBase58 as e,fromSeed as t}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import{WalletVoid as n}from"../WalletVoid.js";import{WalletAbstract as d}from"../WalletAbstract.js";import"@ledgerhq/hw-app-eth";import"ethers";import{getAddressDerivationPath as i}from"../../../utils/getAddressDerivationPath.js";import{utils as a}from"@avalabs/avalanchejs";import"hdkey";import{DerivationPath as o}from"../../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";const{parse:h}=a;class l extends d{constructor(t,r,s){super(s),this.avmXpub=t,this.accountNode=e(t),this.evmWallet=new n(r,r,s)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,n){if(!r(e))throw new Error("Invalid mnemonic phrase.");const d=s(e),a=t(d),h=a.derivePath("m/44'/9000'/0'").neutered(),m=a.derivePath(i(0,o.BIP44,"EVM")).neutered();return new l(h.toBase58(),m.publicKey,n)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(h(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(h(e)[2])))}getRawAddressC(){return Buffer.from(h(this.getCurrentAddress("C"))[2])}}export{l as MnemonicWalletVoid};
1
+ import{fromBase58 as e,fromSeed as t}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import{WalletVoid as n}from"../WalletVoid.js";import{WalletAbstract as d}from"../WalletAbstract.js";import"@ledgerhq/hw-app-eth";import"ethers";import{getEVMDerivationPath as i}from"../../../EVM/utils/getEvmDerivationPath.js";import{DerivationPath as a}from"../../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import{utils as o}from"@avalabs/avalanchejs";const{parse:h}=o;class l extends d{constructor(t,r,s){super(s),this.avmXpub=t,this.accountNode=e(t),this.evmWallet=new n(r,r,s)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,n){if(!r(e))throw new Error("Invalid mnemonic phrase.");const d=s(e),o=t(d),h=o.derivePath("m/44'/9000'/0'").neutered(),m=o.derivePath(i(0,a.BIP44)).neutered();return new l(h.toBase58(),m.publicKey,n)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(h(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(h(e)[2])))}getRawAddressC(){return Buffer.from(h(this.getCurrentAddress("C"))[2])}}export{l as MnemonicWalletVoid};
@@ -1 +1 @@
1
- import{networks as r}from"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import"@solana/kit";import"@solana-program/system";import"@solana-program/token";import"@ledgerhq/hw-app-solana";import"bip39";import"@noble/curves/ed25519";import"@scure/base";import"micro-key-producer/slip10.js";import"@avalabs/avalanchejs";import"hdkey";import"bip32";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"ledger-bitcoin";import"@ledgerhq/hw-app-btc/lib/bip32";const o=r;export{o as BtcNetworks};
1
+ import{networks as a}from"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import"bip32";import"bip39";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"ledger-bitcoin";import"@ledgerhq/hw-app-btc/lib/bip32";import"../Avalanche/wallets/WalletAbstract.js";import"../Avalanche/utils/addSignaturesToAvalancheTx.js";import"../Avalanche/utils/convertGlacierUtxo.js";import"../Avalanche/utils/createAvalancheEvmUnsignedTx.js";import"../Avalanche/utils/createAvalancheUnsignedTx.js";import"create-hash";import"@avalabs/avalanchejs";import"../Avalanche/utils/getAssetBalance.js";import"../Avalanche/utils/getUtxosByTxFromGlacier.js";import"../Avalanche/utils/parseAvalancheTx.js";import"../Avalanche/utils/populateCredential.js";import"../Avalanche/utils/txSizeLimits.js";import"bip32-path";import"@avalabs/hw-app-avalanche";import"../Avalanche/wallets/legacy/MnemonicWalletVoid.js";import"../Avalanche/wallets/legacy/LedgerWallet.js";import"../Avalanche/wallets/legacy/MnemonicWallet.js";import"../Avalanche/wallets/StaticSigner.js";import"../Avalanche/wallets/ledger/LedgerSigner.js";import"../Avalanche/wallets/ledger/SimpleLedgerSigner.js";import"../Avalanche/providers/AbstractProvider.js";import"../Avalanche/providers/constants.js";import"@avalabs/core-chains-sdk";import"@solana/kit";import"@solana-program/system";import"@solana-program/token";import"@ledgerhq/hw-app-solana";import"@noble/curves/ed25519";import"@scure/base";import"micro-key-producer/slip10.js";import"hdkey";const e=a;export{e as BtcNetworks};
@@ -1 +1 @@
1
- import"@ledgerhq/hw-app-eth";import"ethers";import"@solana/kit";import"@solana-program/system";import"@solana-program/token";import"@ledgerhq/hw-app-solana";import"bip39";import"@noble/curves/ed25519";import"@scure/base";import"micro-key-producer/slip10.js";import"@avalabs/avalanchejs";import"hdkey";import"bip32";import{getAddressPublicKeyFromXPub as r}from"../../EVM/utils/getAddressPublicKeyFromXPub.js";import{getBech32Address as o}from"./getBech32Address.js";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";function t(t,e,p){const i=r(t,e);return o(i,p)}export{t as getBech32AddressFromXPub};
1
+ import"@ledgerhq/hw-app-eth";import"ethers";import"bip32";import{getAddressPublicKeyFromXPub as t}from"../../EVM/utils/getAddressPublicKeyFromXPub.js";import"bip39";import{getBech32Address as r}from"./getBech32Address.js";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";function e(e,i,o){const p=t(e,i);return r(p,o)}export{e as getBech32AddressFromXPub};
@@ -1 +1 @@
1
- import{ECPair as t}from"bitcoinjs-lib";import{BitcoinWalletAbstract as r}from"./BitcoinWalletAbstract.js";import{createPsbt as e}from"../utils/createPsbt.js";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import{getAddressDerivationPath as i}from"../../utils/getAddressDerivationPath.js";import"@avalabs/avalanchejs";import"hdkey";import{DerivationPath as o}from"../../EVM/constants.js";import{fromSeed as s}from"bip32";import{validateMnemonic as n,mnemonicToSeed as a}from"bip39";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"ledger-bitcoin";import"@ledgerhq/hw-app-btc/lib/bip32";class p extends r{keypair;constructor(r,e){const i=t.fromPrivateKey(r);super(i.publicKey,e),this.keypair=i}static async fromMnemonic(t,r,e,m=o.BIP44){if(r<0)throw new Error("Account index must be >= 0");if(!n(t))throw new Error("Invalid mnemonic phrase.");const l=await a(t),c=s(l),h=i(r,m,"EVM"),f=c.derivePath(h);if(!f.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new p(f.privateKey,e)}signTx(t,r){const i=e(t,r,this.provider.getNetwork());return Promise.resolve(this.signPsbt(i))}static fromEthersWallet(t,r){const e=t.privateKey;if(!e)throw new Error("Unable to get private key from ethers wallet.");const i=Buffer.from(e.substring(2),"hex");return new p(i,r)}signPsbt(t){return t.signAllInputs(this.keypair),t.validateSignaturesOfAllInputs(),t.finalizeAllInputs(),t.extractTransaction()}}export{p as BitcoinWallet};
1
+ import{ECPair as t}from"bitcoinjs-lib";import{BitcoinWalletAbstract as r}from"./BitcoinWalletAbstract.js";import{createPsbt as e}from"../utils/createPsbt.js";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import{DerivationPath as i}from"../../EVM/constants.js";import{fromSeed as o}from"bip32";import{validateMnemonic as s,mnemonicToSeed as n}from"bip39";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"ledger-bitcoin";import"@ledgerhq/hw-app-btc/lib/bip32";import{getAddressDerivationPath as a}from"../../utils/getAddressDerivationPath.js";import"@avalabs/avalanchejs";import"hdkey";class p extends r{keypair;constructor(r,e){const i=t.fromPrivateKey(r);super(i.publicKey,e),this.keypair=i}static async fromMnemonic(t,r,e,m=i.BIP44){if(r<0)throw new Error("Account index must be >= 0");if(!s(t))throw new Error("Invalid mnemonic phrase.");const l=await n(t),c=o(l),h=a(r,"EVM",{pathSpec:m}),f=c.derivePath(h);if(!f.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new p(f.privateKey,e)}signTx(t,r){const i=e(t,r,this.provider.getNetwork());return Promise.resolve(this.signPsbt(i))}static fromEthersWallet(t,r){const e=t.privateKey;if(!e)throw new Error("Unable to get private key from ethers wallet.");const i=Buffer.from(e.substring(2),"hex");return new p(i,r)}signPsbt(t){return t.signAllInputs(this.keypair),t.validateSignaturesOfAllInputs(),t.finalizeAllInputs(),t.extractTransaction()}}export{p as BitcoinWallet};
@@ -1 +1 @@
1
- import{BitcoinWalletAbstract as t}from"./BitcoinWalletAbstract.js";import{AppClient as r}from"ledger-bitcoin";import"bitcoinjs-lib";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import"@solana/kit";import"@solana-program/system";import"@solana-program/token";import"@ledgerhq/hw-app-solana";import"bip39";import"@noble/curves/ed25519";import"@scure/base";import"micro-key-producer/slip10.js";import"@avalabs/avalanchejs";import"hdkey";import"bip32";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import{createPSBTV2 as i}from"../utils/createPSBTV2.js";import{psbt2ToPsbt0 as a}from"../utils/psbt2ToPsbt0.js";class e extends t{constructor(t,r,i,a,e){super(t,i),this.derivationPath=r,this.transport=a,this.walletPolicyDetails=e}setTransport(t){this.transport=t}async signTx(t,e){const o=function(t){return new r(t)}(this.transport),s=this.ecPair.publicKey,p=this.provider.getNetwork(),n=await o.getMasterFingerprint(),l=i(t,e,p,Buffer.from(n,"hex"),s,this.derivationPath),{policy:m,hmac:c}=this.walletPolicyDetails,h=await o.signPsbt(l,m,c),u=a(l,p,s,this.derivationPath);if(h.forEach((t=>{const[r,i]=t;u.updateInput(r,{partialSig:[{signature:i.signature,pubkey:i.pubkey}]})})),!u.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return u.finalizeAllInputs(),u.extractTransaction()}}export{e as BitcoinLedgerWallet};
1
+ import{BitcoinWalletAbstract as t}from"./BitcoinWalletAbstract.js";import{AppClient as i}from"ledger-bitcoin";import"bitcoinjs-lib";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import"bip32";import"bip39";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import{createPSBTV2 as r}from"../utils/createPSBTV2.js";import{psbt2ToPsbt0 as e}from"../utils/psbt2ToPsbt0.js";class s extends t{constructor(t,i,r,e,s){super(t,r),this.derivationPath=i,this.transport=e,this.walletPolicyDetails=s}setTransport(t){this.transport=t}async signTx(t,s){const a=function(t){return new i(t)}(this.transport),o=this.ecPair.publicKey,n=this.provider.getNetwork(),p=await a.getMasterFingerprint(),l=r(t,s,n,Buffer.from(p,"hex"),o,this.derivationPath),{policy:c,hmac:h}=this.walletPolicyDetails,m=await a.signPsbt(l,c,h),u=e(l,n,o,this.derivationPath);if(m.forEach((t=>{const[i,r]=t;u.updateInput(i,{partialSig:[{signature:r.signature,pubkey:r.pubkey}]})})),!u.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return u.finalizeAllInputs(),u.extractTransaction()}}export{s as BitcoinLedgerWallet};
@@ -1 +1 @@
1
- import{AbstractSigner as t,defineProperties as s,getAddress as i,toUtf8Bytes as e,hexlify as r,Signature as a,Transaction as n,TypedDataEncoder as o}from"ethers";import{getAppEth as h}from"./utils/getAppEth.js";import{getAddressDerivationPath as p}from"../utils/getAddressDerivationPath.js";import"@avalabs/avalanchejs";import"hdkey";import"bip32";import"bip39";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import{TransportStatusError as c,StatusCodes as d}from"@ledgerhq/hw-transport";import{TypedDataUtils as m,SignTypedDataVersion as g}from"@metamask/eth-sig-util";class l extends t{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(t=0,i,e,r){super(),this.path=p(t,e,"EVM"),this.accountIndex=t,this.transport=i,this.derivationSpec=e,this._eth=h(i),s(this,{path:this.path,type:"default",provider:r??null})}setTransport(t){this._eth=h(t),this.transport=t}async getAddress(){const t=await this._eth.getAddress(this.path);return i(t.address)}async signMessage(t){"string"==typeof t&&(t=e(t));const s=r(t).substring(2),i=await this._eth.signPersonalMessage(this.path,s);return i.r="0x"+i.r,i.s="0x"+i.s,a.from(i).serialized}async signTransaction(t){const s=await this.populateTransaction(t);delete s.from;const i=n.from(s),e=i.unsignedSerialized,r=await this._eth.signTransaction(this.path,e.slice(2),null);return i.signature={v:BigInt("0x"+r.v),r:"0x"+r.r,s:"0x"+r.s},i.serialized}connect(t){return new l(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(t,s,i){const{EIP712Domain:e,...r}=s,n=o.getPrimaryType(r);try{const e=await this._eth.signEIP712Message(this.path,{domain:{name:t.name||void 0,chainId:t.chainId?Number(t.chainId):void 0,version:t.version||void 0,verifyingContract:t.verifyingContract||void 0,salt:t.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...s},primaryType:n,message:i});return e.r="0x"+e.r,e.s="0x"+e.s,a.from(e).serialized}catch(e){if(e instanceof c&&e.statusCode===d.INS_NOT_SUPPORTED){const e=m.hashStruct(n,i,s,g.V4),r=m.hashStruct("EIP712Domain",t,s,g.V4),o=await this._eth.signEIP712HashedMessage(this.path,r.toString("hex"),e.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,a.from(o).serialized}throw e}}}export{l as LedgerSigner};
1
+ import{AbstractSigner as t,defineProperties as s,getAddress as i,toUtf8Bytes as e,hexlify as r,Signature as a,Transaction as n,TypedDataEncoder as o}from"ethers";import{getAppEth as h}from"./utils/getAppEth.js";import{getEVMDerivationPath as p}from"./utils/getEvmDerivationPath.js";import"bip32";import"bip39";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import{TransportStatusError as c,StatusCodes as d}from"@ledgerhq/hw-transport";import{TypedDataUtils as m,SignTypedDataVersion as g}from"@metamask/eth-sig-util";class u extends t{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(t=0,i,e,r){super(),this.path=p(t,e),this.accountIndex=t,this.transport=i,this.derivationSpec=e,this._eth=h(i),s(this,{path:this.path,type:"default",provider:r??null})}setTransport(t){this._eth=h(t),this.transport=t}async getAddress(){const t=await this._eth.getAddress(this.path);return i(t.address)}async signMessage(t){"string"==typeof t&&(t=e(t));const s=r(t).substring(2),i=await this._eth.signPersonalMessage(this.path,s);return i.r="0x"+i.r,i.s="0x"+i.s,a.from(i).serialized}async signTransaction(t){const s=await this.populateTransaction(t);delete s.from;const i=n.from(s),e=i.unsignedSerialized,r=await this._eth.signTransaction(this.path,e.slice(2),null);return i.signature={v:BigInt("0x"+r.v),r:"0x"+r.r,s:"0x"+r.s},i.serialized}connect(t){return new u(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(t,s,i){const{EIP712Domain:e,...r}=s,n=o.getPrimaryType(r);try{const e=await this._eth.signEIP712Message(this.path,{domain:{name:t.name||void 0,chainId:t.chainId?Number(t.chainId):void 0,version:t.version||void 0,verifyingContract:t.verifyingContract||void 0,salt:t.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...s},primaryType:n,message:i});return e.r="0x"+e.r,e.s="0x"+e.s,a.from(e).serialized}catch(e){if(e instanceof c&&e.statusCode===d.INS_NOT_SUPPORTED){const e=m.hashStruct(n,i,s,g.V4),r=m.hashStruct("EIP712Domain",t,s,g.V4),o=await this._eth.signEIP712HashedMessage(this.path,r.toString("hex"),e.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,a.from(o).serialized}throw e}}}export{u as LedgerSigner};
@@ -0,0 +1,5 @@
1
+ import { DerivationPath } from '../constants.js';
2
+
3
+ declare const getEVMDerivationPath: (accountIndex: number, pathSpec: DerivationPath, withRoot?: boolean) => string;
4
+
5
+ export { getEVMDerivationPath };
@@ -0,0 +1 @@
1
+ import{DerivationPath as r}from"../constants.js";const e=(e,t,s=!0)=>{switch(t){case r.BIP44:return`${s?"m/":""}44'/60'/0'/0/${e}`;case r.LedgerLive:return`${s?"m/":""}44'/60'/${e}'/0/0`;default:throw new Error("Invalid path spec")}};export{e as getEVMDerivationPath};
@@ -1 +1 @@
1
- import{HDNodeWallet as r,Mnemonic as e}from"ethers";import{getAddressDerivationPath as t}from"../../utils/getAddressDerivationPath.js";import"@avalabs/avalanchejs";import"@ledgerhq/hw-app-eth";import"hdkey";function o(o,a,i){if(!(a>=0&&a%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return r.fromMnemonic(e.fromPhrase(o),t(a,i,"EVM"))}export{o as getWalletFromMnemonic};
1
+ import{HDNodeWallet as r,Mnemonic as e}from"ethers";import{getEVMDerivationPath as t}from"./getEvmDerivationPath.js";function o(o,n,i){if(!(n>=0&&n%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return r.fromMnemonic(e.fromPhrase(o),t(n,i))}export{o as getWalletFromMnemonic};
package/esm/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export { getAddressFromXPub } from './EVM/utils/getAddressFromXPub.js';
10
10
  export { getXpubFromMnemonic } from './EVM/utils/getXpubFromMnemonic.js';
11
11
  export { getEvmAddressFromPubKey } from './EVM/utils/getEvmAddressFromPubKey.js';
12
12
  export { getBtcAddressFromPubKey } from './EVM/utils/getBtcAddressFromPubKey.js';
13
+ export { getEVMDerivationPath } from './EVM/utils/getEvmDerivationPath.js';
13
14
  export { DerivationPath, ETH_ACCOUNT_PATH, ETH_COIN_PATH } from './EVM/constants.js';
14
15
  export { LedgerSigner } from './EVM/LedgerSigner.js';
15
16
  import * as index from './Avalanche/index.js';
package/esm/index.js CHANGED
@@ -1 +1 @@
1
- export{BtcNetworks}from"./BitcoinVM/index.js";export{getAppEth}from"./EVM/utils/getAppEth.js";export{getVoidSigner}from"./EVM/utils/getVoidSigner.js";export{getWalletFromMnemonic}from"./EVM/utils/getWalletFromMnemonic.js";export{isERC20Transfer,isNativeTxn,onBalanceChange}from"./EVM/utils/blockPolling.js";export{JsonRpcBatchInternal}from"./EVM/utils/jsonRpcBatchProvider.js";export{getAddressPrivateKeyFromXPriv}from"./EVM/utils/getAddressPrivateKeyFromXPriv.js";export{getAddressPublicKeyFromXPub}from"./EVM/utils/getAddressPublicKeyFromXPub.js";export{getAddressFromXPub}from"./EVM/utils/getAddressFromXPub.js";export{getXpubFromMnemonic}from"./EVM/utils/getXpubFromMnemonic.js";export{getEvmAddressFromPubKey}from"./EVM/utils/getEvmAddressFromPubKey.js";export{getBtcAddressFromPubKey}from"./EVM/utils/getBtcAddressFromPubKey.js";export{DerivationPath,ETH_ACCOUNT_PATH,ETH_COIN_PATH}from"./EVM/constants.js";export{LedgerSigner}from"./EVM/LedgerSigner.js";import*as e from"./Avalanche/index.js";export{e as Avalanche};export{getAddressDerivationPath}from"./utils/getAddressDerivationPath.js";export{getPublicKeyFromPrivateKey}from"./utils/getPublicKeyFromPrivateKey.js";export{getPubKeyFromTransport}from"./utils/getPubKeyFromTransport.js";export{getLedgerExtendedPublicKey}from"./utils/getLedgerExtendedPublicKey.js";export{omitUndefinedKeys}from"./utils/omitUndefinedKeys.js";export{getLedgerAppInfo}from"./utils/getLedgerAppInfo.js";export{openLedgerApp}from"./utils/openLedgerApp.js";export{quitLedgerApp}from"./utils/quitLedgerApp.js";export{compileSolanaTx}from"./SolanaVM/utils/compileSolanaTx.js";export{deserializeTransactionMessage}from"./SolanaVM/utils/deserializeSolanaTx.js";export{serializeSolanaTx}from"./SolanaVM/utils/serializeSolanaTx.js";export{getSolanaProvider,isSolanaProvider}from"./SolanaVM/utils/solanaProvider.js";export{transferSol}from"./SolanaVM/utils/transferSol.js";export{transferToken}from"./SolanaVM/utils/transferToken.js";export{getSolanaDerivationPath}from"./SolanaVM/utils/derivationPath.js";export{getSolanaPublicKeyFromLedger}from"./SolanaVM/utils/getSolanaPublicKeyFromLedger.js";export{maybeGetAssociatedTokenAccount}from"./SolanaVM/utils/maybeGetAssociatedTokenAccount.js";export{SolanaSigner}from"./SolanaVM/wallets/SolanaSigner.js";export{SolanaLedgerSigner}from"./SolanaVM/wallets/SolanaLedgerSigner.js";export{BitcoinProviderAbstract}from"./BitcoinVM/providers/BitcoinProviderAbstract.js";export{BitcoinProvider}from"./BitcoinVM/providers/BitcoinProvider.js";export{addEncodedSigToPsbt}from"./BitcoinVM/utils/addEncodedSigToPsbt.js";export{createPsbt}from"./BitcoinVM/utils/createPsbt.js";export{createTransferTx}from"./BitcoinVM/utils/createTransferTx.js";export{formatAddressForNetworkBech32}from"./BitcoinVM/utils/formatAddressForNetworkBech32.js";export{getBech32Address}from"./BitcoinVM/utils/getBech32Address.js";export{getBech32AddressFromXPub}from"./BitcoinVM/utils/getBech32AddressFromXPub.js";export{getMaxTransferAmount}from"./BitcoinVM/utils/getMaxTransferAmount.js";export{selectUtxos}from"./BitcoinVM/utils/selectUtxos.js";export{createWalletPolicy}from"./BitcoinVM/utils/createWalletPolicy.js";export{createPSBTV2}from"./BitcoinVM/utils/createPSBTV2.js";export{psbt2ToPsbt0}from"./BitcoinVM/utils/psbt2ToPsbt0.js";export{getTransferTxDetails}from"./BitcoinVM/utils/getTransferTxDetails.js";export{BitcoinWalletAbstract}from"./BitcoinVM/wallets/BitcoinWalletAbstract.js";export{BitcoinWallet}from"./BitcoinVM/wallets/BitcoinWallet.js";export{BitcoinLedgerWallet}from"./BitcoinVM/wallets/BitcoinWalletLedger.js";export{BitcoinWalletVoid}from"./BitcoinVM/wallets/BitcoinWalletVoid.js";
1
+ export{BtcNetworks}from"./BitcoinVM/index.js";export{getAppEth}from"./EVM/utils/getAppEth.js";export{getVoidSigner}from"./EVM/utils/getVoidSigner.js";export{getWalletFromMnemonic}from"./EVM/utils/getWalletFromMnemonic.js";export{isERC20Transfer,isNativeTxn,onBalanceChange}from"./EVM/utils/blockPolling.js";export{JsonRpcBatchInternal}from"./EVM/utils/jsonRpcBatchProvider.js";export{getAddressPrivateKeyFromXPriv}from"./EVM/utils/getAddressPrivateKeyFromXPriv.js";export{getAddressPublicKeyFromXPub}from"./EVM/utils/getAddressPublicKeyFromXPub.js";export{getAddressFromXPub}from"./EVM/utils/getAddressFromXPub.js";export{getXpubFromMnemonic}from"./EVM/utils/getXpubFromMnemonic.js";export{getEvmAddressFromPubKey}from"./EVM/utils/getEvmAddressFromPubKey.js";export{getBtcAddressFromPubKey}from"./EVM/utils/getBtcAddressFromPubKey.js";export{getEVMDerivationPath}from"./EVM/utils/getEvmDerivationPath.js";export{DerivationPath,ETH_ACCOUNT_PATH,ETH_COIN_PATH}from"./EVM/constants.js";export{LedgerSigner}from"./EVM/LedgerSigner.js";import*as e from"./Avalanche/index.js";export{e as Avalanche};export{getAddressDerivationPath}from"./utils/getAddressDerivationPath.js";export{getPublicKeyFromPrivateKey}from"./utils/getPublicKeyFromPrivateKey.js";export{getPubKeyFromTransport}from"./utils/getPubKeyFromTransport.js";export{getLedgerExtendedPublicKey}from"./utils/getLedgerExtendedPublicKey.js";export{omitUndefinedKeys}from"./utils/omitUndefinedKeys.js";export{getLedgerAppInfo}from"./utils/getLedgerAppInfo.js";export{openLedgerApp}from"./utils/openLedgerApp.js";export{quitLedgerApp}from"./utils/quitLedgerApp.js";export{compileSolanaTx}from"./SolanaVM/utils/compileSolanaTx.js";export{deserializeTransactionMessage}from"./SolanaVM/utils/deserializeSolanaTx.js";export{serializeSolanaTx}from"./SolanaVM/utils/serializeSolanaTx.js";export{getSolanaProvider,isSolanaProvider}from"./SolanaVM/utils/solanaProvider.js";export{transferSol}from"./SolanaVM/utils/transferSol.js";export{transferToken}from"./SolanaVM/utils/transferToken.js";export{getSolanaDerivationPath}from"./SolanaVM/utils/derivationPath.js";export{getSolanaPublicKeyFromLedger}from"./SolanaVM/utils/getSolanaPublicKeyFromLedger.js";export{maybeGetAssociatedTokenAccount}from"./SolanaVM/utils/maybeGetAssociatedTokenAccount.js";export{SolanaSigner}from"./SolanaVM/wallets/SolanaSigner.js";export{SolanaLedgerSigner}from"./SolanaVM/wallets/SolanaLedgerSigner.js";export{BitcoinProviderAbstract}from"./BitcoinVM/providers/BitcoinProviderAbstract.js";export{BitcoinProvider}from"./BitcoinVM/providers/BitcoinProvider.js";export{addEncodedSigToPsbt}from"./BitcoinVM/utils/addEncodedSigToPsbt.js";export{createPsbt}from"./BitcoinVM/utils/createPsbt.js";export{createTransferTx}from"./BitcoinVM/utils/createTransferTx.js";export{formatAddressForNetworkBech32}from"./BitcoinVM/utils/formatAddressForNetworkBech32.js";export{getBech32Address}from"./BitcoinVM/utils/getBech32Address.js";export{getBech32AddressFromXPub}from"./BitcoinVM/utils/getBech32AddressFromXPub.js";export{getMaxTransferAmount}from"./BitcoinVM/utils/getMaxTransferAmount.js";export{selectUtxos}from"./BitcoinVM/utils/selectUtxos.js";export{createWalletPolicy}from"./BitcoinVM/utils/createWalletPolicy.js";export{createPSBTV2}from"./BitcoinVM/utils/createPSBTV2.js";export{psbt2ToPsbt0}from"./BitcoinVM/utils/psbt2ToPsbt0.js";export{getTransferTxDetails}from"./BitcoinVM/utils/getTransferTxDetails.js";export{BitcoinWalletAbstract}from"./BitcoinVM/wallets/BitcoinWalletAbstract.js";export{BitcoinWallet}from"./BitcoinVM/wallets/BitcoinWallet.js";export{BitcoinLedgerWallet}from"./BitcoinVM/wallets/BitcoinWalletLedger.js";export{BitcoinWalletVoid}from"./BitcoinVM/wallets/BitcoinWalletVoid.js";
@@ -1,14 +1,17 @@
1
1
  import { DerivationPath } from '../EVM/constants.js';
2
2
 
3
+ type DerivationPathOptions = {
4
+ withRoot?: boolean;
5
+ pathSpec?: DerivationPath;
6
+ };
3
7
  /**
4
8
  * Get the derivation path used by wallet addresses
5
9
  * @param addressIndex Which index is the address on
6
- * @param pathSpec BIP44 vs LedgerLive
7
10
  * @param vm Which VM is this address on. Coin index changes between Avalanche and EVM
8
- * @param withRoot If false, skips the "m/" prefix. Needed for Solana Ledger app.
11
+ * @param options
12
+ * @param options.withRoot If false, skips the "m/" prefix. Needed for Solana Ledger app.
13
+ * @param options.pathSpec Only relevant (and required) for EVM.
9
14
  */
10
- declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, // Irrelevant for Solana
11
- vm: 'SVM', withRoot?: boolean): string;
12
- declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, vm: 'EVM' | 'AVM' | 'PVM', withRoot?: never): string;
15
+ declare function getAddressDerivationPath(accountIndex: number, vm: 'SVM' | 'EVM' | 'AVM' | 'PVM', options?: DerivationPathOptions): string;
13
16
 
14
17
  export { getAddressDerivationPath };
@@ -1 +1 @@
1
- import"@solana/kit";import"@solana-program/system";import"@solana-program/token";import{getSolanaDerivationPath as o}from"../SolanaVM/utils/derivationPath.js";import"@ledgerhq/hw-app-solana";import"bip39";import"@noble/curves/ed25519";import"@scure/base";import"micro-key-producer/slip10.js";import{DerivationPath as r}from"../EVM/constants.js";function t(t,i,n,a=!0){if(t<0)throw new Error("Account index can not be less than 0.");if("SVM"===n)return o(t,a);const e="EVM"===n?"60":"9000";return i==r.BIP44?`m/44'/${e}'/0'/0/${t}`:`m/44'/${e}'/${t}'/0/0`}export{t as getAddressDerivationPath};
1
+ import"@ledgerhq/hw-app-eth";import"ethers";import{getEVMDerivationPath as a}from"../EVM/utils/getEvmDerivationPath.js";import"bip32";import"bip39";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"../Avalanche/wallets/WalletAbstract.js";import"../Avalanche/utils/addSignaturesToAvalancheTx.js";import"../Avalanche/utils/convertGlacierUtxo.js";import"../Avalanche/utils/createAvalancheEvmUnsignedTx.js";import"../Avalanche/utils/createAvalancheUnsignedTx.js";import"create-hash";import"@avalabs/avalanchejs";import"../Avalanche/utils/getAssetBalance.js";import"../Avalanche/utils/getUtxosByTxFromGlacier.js";import"../Avalanche/utils/parseAvalancheTx.js";import"../Avalanche/utils/populateCredential.js";import"../Avalanche/utils/txSizeLimits.js";import"bip32-path";import{getAvalancheDerivationPath as t}from"../Avalanche/utils/getAvalancheDerivationPath.js";import"@avalabs/hw-app-avalanche";import"../Avalanche/wallets/legacy/MnemonicWalletVoid.js";import"../Avalanche/wallets/legacy/LedgerWallet.js";import"../Avalanche/wallets/legacy/MnemonicWallet.js";import"../Avalanche/wallets/StaticSigner.js";import"@solana/kit";import"@solana-program/system";import"@solana-program/token";import{getSolanaDerivationPath as e}from"../SolanaVM/utils/derivationPath.js";import"@ledgerhq/hw-app-solana";import"@noble/curves/ed25519";import"@scure/base";import"micro-key-producer/slip10.js";import"hdkey";import"../Avalanche/wallets/ledger/LedgerSigner.js";import"../Avalanche/wallets/ledger/SimpleLedgerSigner.js";import"../Avalanche/providers/AbstractProvider.js";import"../Avalanche/providers/constants.js";import"@avalabs/core-chains-sdk";function r(r,i,o={withRoot:!0}){if(r<0)throw new Error("Account index can not be less than 0.");switch(i){case"EVM":if(!o.pathSpec)throw new Error("Path spec is required for EVM: either BIP44 or Ledger Live");return a(r,o.pathSpec,o.withRoot);case"AVM":case"PVM":return t(r,o.withRoot);case"SVM":return e(r,o.withRoot);default:throw new Error(`Unknown derivation path for VM: ${i}`)}}export{r as getAddressDerivationPath};
@@ -1 +1 @@
1
- import{getAppEth as t}from"../EVM/utils/getAppEth.js";import{getAddressDerivationPath as r}from"./getAddressDerivationPath.js";async function e(e,o,s,i="EVM"){const f=t(e),n=r(o,s,i),p=await f.getAddress(n,!1,!1);return Buffer.from(p.publicKey,"hex")}export{e as getPubKeyFromTransport};
1
+ import{getAppEth as t}from"../EVM/utils/getAppEth.js";import{getAddressDerivationPath as e}from"./getAddressDerivationPath.js";async function r(r,o,s,i="EVM"){const p=t(r),a="EVM"===i?e(o,i,{pathSpec:s}):e(o,i),f=await p.getAddress(a,!1,!1);return Buffer.from(f.publicKey,"hex")}export{r as getPubKeyFromTransport};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avalabs/core-wallets-sdk",
3
- "version": "3.1.0-alpha.68",
3
+ "version": "3.1.0-alpha.69",
4
4
  "license": "Limited Ecosystem License",
5
5
  "private": false,
6
6
  "type": "module",
@@ -70,5 +70,5 @@
70
70
  "peerDependencies": {
71
71
  "ethers": "^6.7.1"
72
72
  },
73
- "gitHead": "be66a2a549a79504475484cf1593d9bc8cad6df2"
73
+ "gitHead": "d82bc3cb16e23c20801ee53933f619163a76ae7e"
74
74
  }