@avalabs/core-wallets-sdk 3.1.0-alpha.44 → 3.1.0-alpha.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1987,8 +1987,11 @@ declare namespace index {
1987
1987
  * @param addressIndex Which index is the address on
1988
1988
  * @param pathSpec BIP44 vs LedgerLive
1989
1989
  * @param vm Which VM is this address on. Coin index changes between Avalanche and EVM
1990
+ * @param withRoot If false, skips the "m/" prefix. Needed for Solana Ledger app.
1990
1991
  */
1991
- declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, vm: 'EVM' | 'AVM' | 'PVM'): string;
1992
+ declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, // Irrelevant for Solana
1993
+ vm: 'SVM', withRoot?: boolean): string;
1994
+ declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, vm: 'EVM' | 'AVM' | 'PVM', withRoot?: never): string;
1992
1995
 
1993
1996
  /**
1994
1997
  * Get the public key from a given private key.
@@ -2070,6 +2073,10 @@ declare const transferToken: ({ from, to, mint, amount, provider, }: {
2070
2073
  version: 0;
2071
2074
  }>, "feePayer">>;
2072
2075
 
2076
+ declare const getSolanaDerivationPath: (accountIndex: number, withRoot?: boolean) => string;
2077
+
2078
+ declare const getSolanaPublicKeyFromLedger: (accountIndex: number, transport: Transport) => Promise<Buffer>;
2079
+
2073
2080
  declare class SolanaSigner {
2074
2081
  #private;
2075
2082
  constructor(privateKey: Buffer);
@@ -2077,4 +2084,10 @@ declare class SolanaSigner {
2077
2084
  signTx(base64EncodedTx: string, provider: SolanaProvider): Promise<string>;
2078
2085
  }
2079
2086
 
2080
- export { index as Avalanche, BitcoinHistoryTx, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinLedgerInputUTXO, BitcoinLedgerWallet, BitcoinOutputUTXO, BitcoinProvider, BitcoinProviderAbstract, BitcoinTx, BitcoinWallet, BitcoinWalletAbstract, BitcoinWalletVoid, DerivationPath, ETH_ACCOUNT_PATH, ETH_COIN_PATH, JsonRpcBatchInternal, LedgerSigner$1 as LedgerSigner, SolanaProvider, SolanaSigner, addEncodedSigToPsbt, compileSolanaTx, createPSBTV2, createPsbt, createTransferTx, createWalletPolicy, deserializeTransactionMessage, formatAddressForNetworkBech32, getAddressDerivationPath, getAddressFromXPub, getAddressPrivateKeyFromXPriv, getAddressPublicKeyFromXPub, getAppEth, getBech32Address, getBech32AddressFromXPub, getBtcAddressFromPubKey, getEvmAddressFromPubKey, getLedgerAppInfo, getLedgerExtendedPublicKey, getMaxTransferAmount, getPubKeyFromTransport, getPublicKeyFromPrivateKey, getSolanaProvider, getTransferTxDetails, getVoidSigner, getWalletFromMnemonic, getXpubFromMnemonic$1 as getXpubFromMnemonic, isERC20Transfer, isNativeTxn, isSolanaProvider, omitUndefinedKeys, onBalanceChange, openLedgerApp, psbt2ToPsbt0, quitLedgerApp, selectUtxos, serializeSolanaTx, transferSol, transferToken };
2087
+ declare class SolanaLedgerSigner {
2088
+ #private;
2089
+ constructor(accountIndex: number, transport: Transport);
2090
+ signTx(base64EncodedTx: string, provider: SolanaProvider): Promise<string>;
2091
+ }
2092
+
2093
+ export { index as Avalanche, BitcoinHistoryTx, BitcoinInputUTXO, BitcoinInputUTXOWithOptionalScript, BitcoinLedgerInputUTXO, BitcoinLedgerWallet, BitcoinOutputUTXO, BitcoinProvider, BitcoinProviderAbstract, BitcoinTx, BitcoinWallet, BitcoinWalletAbstract, BitcoinWalletVoid, DerivationPath, ETH_ACCOUNT_PATH, ETH_COIN_PATH, JsonRpcBatchInternal, LedgerSigner$1 as LedgerSigner, SolanaLedgerSigner, SolanaProvider, 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, omitUndefinedKeys, onBalanceChange, openLedgerApp, psbt2ToPsbt0, quitLedgerApp, selectUtxos, serializeSolanaTx, transferSol, transferToken };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@avalabs/avalanchejs"),i=require("hdkey"),o=require("buffer"),d=require("@openzeppelin/contracts/build/contracts/ERC20.json"),u=require("bip32"),c=require("bip39"),l=require("@ledgerhq/hw-transport"),h=require("@metamask/eth-sig-util"),p=require("ledger-bitcoin"),g=require("@ledgerhq/hw-app-btc/lib/bip32"),m=require("@noble/hashes/sha256"),f=require("@avalabs/glacier-sdk"),x=require("@avalabs/core-chains-sdk"),v=require("create-hash"),w=require("xss"),y=require("bip32-path"),A=require("@avalabs/hw-app-avalanche"),b=require("@solana/kit"),I=require("@solana-program/system"),T=require("@solana-program/token"),S=require("@noble/curves/ed25519"),P=require("@scure/base"),B=require("micro-key-producer/slip10.js");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 D(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 M(e,t,r,s,n,a){const i=D(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 U(e){return new s(e,"w0w")}const O="m/44'/60'",N=`${O}/0'`;var _=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(_||{});function L(e,t,r){if(e<0)throw new Error("Account index can not be less than 0.");const s="EVM"===r?"60":"9000";return t==_.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const X=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),F=(e,t)=>{const r=new n.Interface(d.abi).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var H=[{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 R 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,H,this._parentProvider),this._maxCalls=62)}#e;#t=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#e.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function $(e,t){return u.fromBase58(e).derivePath(`0/${t}`).publicKey}let q=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,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=U(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=U(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,a=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof l.TransportStatusError&&s.statusCode===l.StatusCodes.INS_NOT_SUPPORTED){const s=h.TypedDataUtils.hashStruct(i,r,t,h.SignTypedDataVersion.V4),a=h.TypedDataUtils.hashStruct("EIP712Domain",e,t,h.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 W(t,r,s,n,a,i){const o=new p.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,g.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function 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 J{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 M(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class z extends J{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(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await c.mnemonicToSeed(e),a=u.fromSeed(n),i=L(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new z(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 z(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}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 a.EVM;case"X":return a.AVM;case"P":return a.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:Q,AddressMaps:Z}=a.utils,ee=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const i=Q(e);let o=Z.fromTransferableInputs(i,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>a.pvmSerial.isCreateChainTx(e)||a.pvmSerial.isAddSubnetValidatorTx(e)||a.pvmSerial.isRemoveSubnetValidatorTx(e)||a.pvmSerial.isTransformSubnetTx(e)||a.pvmSerial.isTransferSubnetOwnershipTx(e)||a.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),i=a.OutputOwners.fromNative(n.controlKeys.map((e=>a.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new a.utils.AddressMap(i)),r})({tx:e,provider:r,addressMaps:o});return new a.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else a.pvmSerial.isDisableL1ValidatorTx(e)&&(o=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),i=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new a.utils.AddressMap(i)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(o,e,r));return new a.UnsignedTx(e,n,o,s)},{bufferToHex:te,packTx:re}=a.utils,{publicKeyBytesToAddress:se,recoverPublicKey:ne}=a.secp256k1,ae=new a.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=m.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 a.utils.bufferToHex(a.utils.addChecksum(e.toBytes()))}const{getManagerForVM:de,hexToBuffer:ue,unpackWithManager:ce}=a.utils,le=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=Y(t);if(n===a.EVM)throw new Error("EVM transactions are not supported");const i=ue(e),o=ce(n,i),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const i=de(s).unpack(t,a.avaxSerial.SignedTx),o=await ee({tx:e,utxos:n,provider:r,credentials:i.getCredentials()});return e.getSigIndices().map(((e,t)=>new a.Credential(ie(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new a.Credential(ie(e))))}})({tx:o,txBytes:i,provider:r,vm:n,utxos:s});return ee({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:he,format:pe}=a.utils,{publicKeyBytesToAddress:ge}=a.secp256k1;class me{constructor(e,t){this.baseUrl=e,this.context=t;const r=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(r)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}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 a.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new a.avm.AVMApi(this.baseUrl)}getApiP(){return new a.pvm.PVMApi(this.baseUrl)}getApiC(){return new a.evm.EVMApi(this.baseUrl)}getInfo(){return new a.info.InfoApi(this.baseUrl)}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=ge(a);return pe(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return pe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=he(e);return pe(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,i)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&i(new Error("Timeout")),d=s instanceof a.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),d.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{o()}),1e3)}};o()}))}}const fe={weights:a.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},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},we={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:fe};class ye extends me{constructor(e,t){super(e,t)}static async fromBaseURL(e){const t=await a.Context.getContextFromURI(e);try{await new a.info.InfoApi(e).getUpgradesInfo();return new ye(e,t)}catch{return new ye(e,t)}}static getDefaultMainnetProvider(){return new ye(x.AVALANCHE_XP_NETWORK.rpcUrl,xe)}static getDefaultFujiProvider(){return new ye(x.AVALANCHE_XP_TEST_NETWORK.rpcUrl,ve)}static getDefaultDevnetProvider(){return new ye(x.AVALANCHE_P_DEV_NETWORK.rpcUrl,we)}}const{bytesCompare:Ae,parseBech32:be}=a.utils,Ie=(e,t)=>"P"===t,Te=(e,t,r)=>{const s=Ie(0,t)?e.amount:e.asset?.amount;return new a.TransferOutput(new a.BigIntPr(BigInt(s)),a.OutputOwners.fromNative(e.addresses.map((e=>be(e)[1])).sort(Ae),BigInt(r??0),e.threshold))},Se=(e,t)=>{const r=((e,t)=>{const r=t===f.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=Ie(0,r)?e.txHash:e.creationTxHash,n=Ie(0,r)?e.assetId:e.asset?.assetId;return new a.Utxo(a.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),a.Id.fromString(n),((e,t)=>Ie(0,t)?e.stakeableLocktime?new a.pvmSerial.StakeableLockOut(new a.BigIntPr(BigInt(e.stakeableLocktime??0)),Te(e,t,e.platformLocktime??0)):Te(e,t,e.platformLocktime):Te(e,t,e.locktime))(e,r))},{unpackWithManager:Pe,parse:Be,bufferToHex:Ce,AddressMaps:ke,AddressMap:Ee}=a.utils;function De(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return v("sha256").update(s).digest()}const Ve=1024,Me=1024;async function Ke(e,t,r){const s=e.slice(0,Ve),n=e.slice(Ve),a=await Ue(t,{...r,addresses:s});if(n.length){const s=await Ke(n,t,{...r,addresses:e});return a.merge(s)}return a}async function Ue(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 a.utils.UtxoSet(s);if(s.length>=Me){const s=await Ue(e,{...t,startIndex:r});return n.merge(s)}return n}function Oe(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:Ne}=a.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}=a.utils;function He(e,t=!0){try{if(t){const[t]=a.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else a.utils.parseBech32(e);return!0}catch(e){return!1}}const Re=e=>{if([xe.xBlockchainID,ve.xBlockchainID,we.xBlockchainID].includes(e))return"AVM";if([xe.pBlockchainID,ve.pBlockchainID,we.pBlockchainID].includes(e))return"PVM";if([xe.cBlockchainID,ve.cBlockchainID,we.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},$e=(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 We={parseCreateSubnetTx:e=>a.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=>a.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=>a.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=>a.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:G.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>a.pvmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.evmSerial.isImportTx(e)?a.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:G.Import,chain:e.getVM(),source:Re(e.sourceChain.value()),amount:qe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:G.Import,chain:e.getVM(),source:Re(e.sourceChain.value()),amount:qe(e.ins,r),...t}):null,parseExportTx:e=>a.pvmSerial.isExportTx(e)||a.avmSerial.isExportTx(e)||a.evmSerial.isExportTx(e)?a.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:G.Export,chain:e.getVM(),destination:Re(e.destinationChain.toString()),amount:$e(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:G.Export,chain:e.getVM(),destination:Re(e.destination.value()),amount:$e(e.outs,r),...t}):null,parseBaseTx:e=>a.avmSerial.isAvmBaseTx(e)||a.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,i=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),a.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof a.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof a.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),o=Oe(),d=i.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:G.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!a.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return a.pvmSerial.isSigner(e.signer)&&(r=a.utils.bufferToHex(e.signer.proof.publicKey),t=a.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type: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=>a.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=>a.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=>a.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:n(a.Address.fromHex(e.address.toString("hex"))),validators:e.validators.map((e=>({nodeId:a.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>a.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:G.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>a.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:G.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>a.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:G.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>a.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}=a.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=Oe(),r=e.map((e=>({utxo:e,...a.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),i=Ye(s,["amount"],"desc"),o=Ye(n,["stakeableLocktime","amount"],"desc"),[d,...u]=i;return[...d?[d]:[],...o,...u].map((e=>e.utxo))}function Ze(e,t){return Ye(e.map((e=>({utxo:e,...a.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}=a.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 a.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 a.utils.UtxoSet(t),amount:it(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:Qe,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new a.utils.UtxoSet(t),nodeId:nt,start:Oe(),end:Oe()+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(a.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(a.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:Qe,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new a.utils.UtxoSet(t),nodeId:nt,start:Oe(),end:Oe()+BigInt(1e3),weight:it(t,e.getProvider().getContext().baseTxFee),subnetId:at,feeState:r})},ExportP:{sortFunction:et,unsignedTxBuilder:(e,t,r)=>e.exportP({amount:it(t,e.getProvider().getContext().baseTxFee),utxoSet:new a.utils.UtxoSet(t),destination:"X",feeState:r})},ImportP:{sortFunction:et,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new a.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function dt(e){return y.validateString(e,!0)&&6===e.split("/").length}function ut(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:ct,hexToBuffer:lt}=a.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:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=ct(s)[2],i=this.provider.getAvaxID(),o=a.TransferableOutput.fromNative(i,e,[n]),d=Ze(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>ct(e)[2])),l=ct(this.getChangeAddress("X"))[2];return a.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:i}){const o=this.provider.getChainID(t),d=this.getAddresses("P").map((e=>ct(e)[2]));ct(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const u=ct(r)[2],c=e.getUTXOs();return ut(n),a.pvm.newImportTx({fromAddressesBytes:d,utxos:c,toAddressesBytes:[u],sourceChainId:o,threshold:s,feeState:n,locktime:i},this.provider.getContext())}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>ct(e)[2])),i=ct(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=ct(r)[2];return a.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[i]})}importC(e,r,s,n,i){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>ct(e)[2]));i=i||this.getAddressEVM();const u=Buffer.from(t.strip0x(i),"hex");return a.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const i=lt(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=ct(n)[2],u=s/BigInt(1e9);return a.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,i,[d],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const i=ct(n)[2],o=this.provider.getAvaxID(),d=a.TransferableOutput.fromNative(o,e,[i]),u=Ze(t.getUTXOs(),!0),c=this.provider.getChainID(r),l=this.getAddresses("P").map((e=>ct(e)[2])),h=ct(this.getChangeAddress("P"))[2];return ut(s),a.pvm.newExportTx({changeAddressesBytes:[h],fromAddressesBytes:l,utxos:u,outputs:[d],destinationChainId:c,feeState:s},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const i=tt(e.getUTXOs());s=s??this.getCurrentAddress("P");const o=ct(s)[2],d=this.provider.getContext(),u=[a.TransferableOutput.fromNative(d.avaxAssetID,t,[o])],c=this.getAddresses("P").map((e=>ct(e)[2])),l=ct(this.getChangeAddress("P"))[2],h=n?.changeAddresses??[l];return ut(r),a.pvm.newBaseTx({changeAddressesBytes:h,fromAddressesBytes:c,utxos:i,outputs:u,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},d)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:i,fromAddresses:o}){const[d,u,c]=ct(r);if(d!==t||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const l=Object.entries(s).map((([e,t])=>a.TransferableOutput.fromNative(e,t,[c]))),h=Ze(e.getUTXOs(),!0),p=(o??this.getAddresses(t)).map((e=>ct(e)[2])),g=ct(this.getChangeAddress("P"))[2],m=i?.changeAddresses??[g];return"X"===t?a.avm.newBaseTx(this.provider.getContext(),p,h,l,i):(ut(n),a.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:p,utxos:h,outputs:l,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:i,validators:o,options:d,fromAddresses:u}){const c=(u??this.getAddresses("P")).map((e=>ct(e)[2])),l=ct(this.getChangeAddress("P"))[2],h=d?.changeAddresses??[l],p=o.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:i,remainingBalanceOwner:o})=>{const d=new a.pvmSerial.ProofOfPossession(Uint8Array.from(a.utils.hexToBuffer(t)),Uint8Array.from(a.utils.hexToBuffer(r))),u=a.PChainOwner.fromNative(o.addresses.map((e=>ct(e)[2])),o.threshold??1),c=a.PChainOwner.fromNative(i.addresses.map((e=>ct(e)[2])),i.threshold??1);return a.L1Validator.fromNative(e,n,s,d,u,c)}));return a.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:h,validators:p,fromAddressesBytes:c,address:ct(i)[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:i,options:o}){const d=(i??this.getAddresses("P")).map((e=>ct(e)[2])),u=ct(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[u];return a.pvm.newRegisterL1ValidatorTx({utxos:Ze(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(a.utils.hexToBuffer(r)),changeAddressesBytes:c,feeState:n,fromAddressesBytes:d,memo:o?.memo,message:Uint8Array.from(a.utils.hexToBuffer(s)),minIssuanceTime:o?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){const i=(n??this.getAddresses("P")).map((e=>ct(e)[2])),o=ct(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return a.pvm.newSetL1ValidatorWeightTx({utxos:Ze(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,message:Uint8Array.from(a.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:i}){const o=(s??this.getAddresses("P")).map((e=>ct(e)[2])),d=ct(this.getChangeAddress("P"))[2],u=r?.changeAddresses??[d];return a.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:i,utxos:Ze(e.getUTXOs(),!0),changeAddressesBytes:u,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:i}){const o=(s??this.getAddresses("P")).map((e=>ct(e)[2])),d=ct(this.getChangeAddress("P"))[2],u=r?.changeAddresses??[d];return a.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:i,utxos:Ze(e.getUTXOs(),!0),changeAddressesBytes:u,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:i,subnetAuth:o,feeState:d,options:u,fromAddresses:c}){const l=Ze(e.getUTXOs(),!0),h=(c??this.getAddresses("P")).map((e=>ct(e)[2])),p=ct(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[p];return ut(d),a.pvm.newCreateChainTx({chainName:r,feeState:d,fromAddressesBytes:h,fxIds:n,genesisData:i,subnetAuth:o,subnetId:t,utxos:l,vmId:s,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:i,locktime:o}){const d=Ze(e.getUTXOs(),!0),u=(s??this.getAddresses("P")).map((e=>ct(e)[2])),c=ct(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c],h=t.map((e=>ct(e)[2]));return ut(r),a.pvm.newCreateSubnetTx({fromAddressesBytes:u,changeAddressesBytes:l,utxos:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:i,locktime:o,subnetOwners:h},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d,fromAddresses:u,options:c}){const l=Ze(e.getUTXOs(),!0),h=(u??this.getAddresses("P")).map((e=>ct(e)[2])),p=ct(this.getChangeAddress("P"))[2],g=c?.changeAddresses??[p];return ut(d),a.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:h,utxos:l,minIssuanceTime:c?.minIssuanceTime,memo:c?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,fromAddresses:u,rewardAddresses:c,delegatorRewardAddresses:l,publicKey:h,signature:p,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=Qe(e.getUTXOs()),w=(u??this.getAddresses("P")).map((e=>ct(e)[2])),y=(c??[this.getCurrentAddress("P")]).map((e=>ct(e)[2])),A=(l??[this.getCurrentAddress("P")]).map((e=>ct(e)[2]));if(!(i!==a.networkIDs.PrimaryNetworkID.toString()||h&&p))throw new Error("Must provide public key and signature for primary subnet.");const b=ct(this.getChangeAddress("P"))[2],I=g?.changeAddresses??[b];return ut(d),a.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:A,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:I,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,publicKey:h,rewardAddresses:y,signature:p,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,fromAddresses:o,rewardAddresses:d,options:u,locktime:c,feeState:l,threshold:h,stakingAssetId:p}){const g=Qe(e.getUTXOs()),m=(o??this.getAddresses("P")).map((e=>ct(e)[2])),f=(d??[this.getCurrentAddress("P")]).map((e=>ct(e)[2])),x=ct(this.getChangeAddress("P"))[2],v=u?.changeAddresses??[x];return ut(l),a.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,changeAddressesBytes:v,nodeId:t,start:r,end:s,weight:n,subnetId:i,rewardAddresses:f,locktime:c,stakingAssetId:p,threshold:h,feeState:l},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:i,options:o}){const d=Ze(e.getUTXOs(),!0),u=(n??this.getAddresses("P")).map((e=>ct(e)[2])),c=ct(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c];return ut(i),a.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:d,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:i},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:i,options:o,threshold:d,locktime:u}){const c=Ze(e.getUTXOs(),!0),l=(i??this.getAddresses("P")).map((e=>ct(e)[2])),h=ct(this.getChangeAddress("P"))[2],p=o?.changeAddresses??[h],g=s.map((e=>ct(e)[2]));return ut(n),a.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:p,fromAddressesBytes:l,utxos:c,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:d,locktime:u},this.provider.getContext())}}class pt 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 pt(o,d,s)}static fromMnemonic(e,t,r,s){if(!c.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=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return pt.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 gt={type:"zondax",getApp:e=>new A(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,r={show:!1,hrp:"avax"}){const s=this.getApp(e);return{publicKey:(await s.getAddressAndPubKey(t.toString(),r.show,r.hrp)).publicKey}},async getXPUB(e,t){const r=this.getApp(e),s=await r.getExtendedPubKey(t,!1);return{pubKey:s.publicKey,chainCode:s.chain_code}},async signHash(e,t,r,s){const n=this.getApp(e),a=s.map((e=>e.toString(!0))),i=await n.signHash(r.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const a=this.getApp(e),i=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(r.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function mt(e){return!(await gt.getVersion(e)>="0.6.0")}const{parse:ft}=a.utils;class xt extends ht{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new pt(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath(L(0,_.BIP44,"EVM")).neutered();return new xt(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(ft(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(ft(e)[2])))}getRawAddressC(){return Buffer.from(ft(this.getCurrentAddress("C"))[2])}}const{isTransferOut:vt,isStakeableLockOut:wt}=a.utils;function yt(e){const t=e.output;return vt(t)||wt(t)?t.getOwners():[]}function At(e){const t=e.getTx();return a.avmSerial.isExportTx(t)||a.pvmSerial.isExportTx(t)?new Set(t.outs.map(yt).flat()):a.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(yt).flat()):new Set((t.baseTx?.outputs??[]).map(yt).flat())}const{parse:bt}=a.utils;class It extends xt{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]=bt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await mt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=U(e),a=await gt.getXPUB(e,It.getAccountPath("X")),i=u.fromPublicKey(a.pubKey,a.chainCode),o=L(0,_.BIP44,"EVM"),d=await s.getAddress(o,!1),c=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new It(i.toBase58(),l,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>y.fromString(e))),l=[...At(t)].map((e=>Buffer.from(e))),h=[...this.filterOwnedAddresses(l).values()].map((e=>y.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:h})).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=y.fromString(It.getAccountPath(e.chain));return[...(await gt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:Tt}=a.utils;class St extends xt{constructor(e,t,r){const s=u.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(Tt(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=u.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath(L(0,_.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new St(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Pt,sign:Bt,signHash:Ct}=a.secp256k1,{addChecksum:kt}=a.utils;class Et extends pt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(Pt(e)),Buffer.from(Pt(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!dt(r)||!dt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(t),o=a.derivePath(r);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Et(i.privateKey,o.privateKey,s)}async signMessage(e){const t=De(e.message),r=this.getSigningKey(e.chain);return Buffer.from(kt(await Ct(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Bt(e.buffer,t))]}}const{strip0x:Dt}=a.utils;class Vt extends pt{constructor(e,t,r,s,i){const o=a.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=a.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),i),this.pathXP=t,this.pathC=s,!dt(t)||!dt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await mt(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(Dt(o.publicKey),"hex"),c=Buffer.from(Dt(d.publicKey),"hex"),l=Buffer.from(Dt(n.SigningKey.computePublicKey(u,!0)),"hex"),h=Buffer.from(Dt(n.SigningKey.computePublicKey(c,!0)),"hex");return new Vt(h,t,l,r,a)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=y.fromString(this.getAccountPath(e.chain)),r=y.fromString(this.getPartialSignerPath(e.chain));return[...(await gt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Mt}=a.utils;var Kt=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:we,FujiContext:ve,JsonRpcProvider:ye,LedgerSigner:Vt,LedgerWallet:It,MainnetContext:xe,MnemonicWallet:St,MnemonicWalletVoid:xt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=u.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof a.EVMUnsignedTx||"C"===t?a.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):a.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Mt(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?[y.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(y.fromString(s)),e}),[])}async signTx(e){if(!e.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([...At(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=y.fromString(this.getAccountPath(e.chain));return[...(await gt.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||y.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=De(e.message),s=(await gt.signHash(e.transport,r,y.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(L(t,_.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),i=this.getSigningKeys(n,r,s);if(!i?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await a.addTxSignatures({unsignedTx:t,privateKeys:i}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=De(e.message),s=await a.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:st,StaticSigner:Et,TxType:G,WalletAbstract:ht,WalletVoid:pt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const i=await le({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>i.addSignature(e))));const o=i.getCredentials(),d=i.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=o[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new a.Credential(s)),e}),[]),u=new a.UnsignedTx(i.getTx(),i.getInputUtxos(),i.addressMaps,d);return{signedTxHex:oe(new a.avaxSerial.SignedTx(i.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:Se,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=Pe(r,e),i=Be(t)[2],o=Ce(i);if(a.evmSerial.isExportTx(n))return new a.EVMUnsignedTx(n,[],new ke([Ee.fromJSON([[o,0]])]));if(a.evmSerial.isImportTx(n)){const e=ke.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new a.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:ee,digestMessage:De,emptySignature:ae,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=u.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(i,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return u.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=Oe();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},getLedgerProvider:async function(e){return gt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=ot[r],o=Oe(),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:Ue,getPchainUnixNow:async function(e){const t=e?x.AVALANCHE_XP_TEST_NETWORK.rpcUrl:x.AVALANCHE_XP_NETWORK.rpcUrl,r=await new a.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:_e,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[a.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Ke,getUnixNow:Oe,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:i})=>{const o=Y(t),d=Xe(e),u=Fe(o,d);if(a.evmSerial.isExportTx(u))return[];const c=(e=>{if(a.evmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case a.EVM:return f.BlockchainId.C_CHAIN;case a.AVM:return f.BlockchainId.X_CHAIN;case a.PVM:return f.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Le(u),h=new f.Glacier({BASE:s,TOKEN:n,HEADERS:i}),p=[...new Set(l.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(p.map((e=>h.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:r,txHash:e}))));return l.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=Se(n,r);return e.push(a),e}),[])},getVmByChainAlias:Y,getXpubFromMnemonic:function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=c.mnemonicToSeedSync(e);return u.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address: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:mt,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50}={}){try{const n=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(We)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=je(i,n),u=Je(i),c=ze(i).get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0),h=u.get(n.avaxAssetID)??BigInt(0);let p=BigInt(0);a.evmSerial.isImportExportTx(i)?(p=await t.getApiC().getBaseFee()/BigInt(1e9),0n===p&&(p=1n)):"PVM"===i.vm&&(p=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0))));const{isValid:g,txFee:m}=Ge({unsignedTx:e,context:n,burnedAmount:l,baseFee:p,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:h,totalAvaxInput:c,isValidAvaxBurnedAmount:g,txFee:m},assetId:n.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 Ut=(e,t)=>{const r=b.getTransactionDecoder().decode(b.getBase64Encoder().encode(e)),s=b.getCompiledTransactionMessageDecoder().decode(r.messageBytes);return b.decompileTransactionMessageFetchingLookupTables(s,t)},Ot=Symbol();class Nt{#r;#s;constructor(e){this.#r=Uint8Array.from(e),this.#s=b.address(P.base58.encode(S.ed25519.getPublicKey(this.#r)))}static fromMnemonic(e,t){const r=c.mnemonicToSeedSync(e),s=B.fromMasterSeed(Uint8Array.from(r)).derive(`m/44'/501'/${t}'/0'`);return new Nt(Buffer.from(s.privateKey))}async signTx(e,t){const r=await Ut(e,t),{signatures:s,messageBytes:n}=b.compileTransaction(r);if(!this.#n(s))return e;const a=P.base58.encode(S.ed25519.sign(Uint8Array.from(n),this.#r));return b.assertIsSignature(a),b.getBase64EncodedWireTransaction({messageBytes:n,signatures:{...s,[this.#s]:P.base58.decode(a)}})}#n(e){return this.#s in e&&!e[this.#s]}}Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Kt,exports.BitcoinLedgerWallet=class extends J{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 p(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=W(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=j(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.#a=new t.HttpClient(s||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#i=new t.HttpClient(n||d,i)}#a;#i;async#o(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#i.post("",e,{},this.extraParams))))).flat():this.#i.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#a.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,r){const s=await this.#a.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.#i.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.#o(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.#a.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.#i.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.#o([{...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.#i.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#a.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.#a.post(`/api/v2/address/${e}`,{},{},this.extraParams);return await Promise.allSettled(t.txids?.slice(0,25).map((async t=>{try{const r=await this.#a.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(),h=d?l:c,p=h.filter(((e,t)=>h.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:p,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=z,exports.BitcoinWalletAbstract=J,exports.BitcoinWalletVoid=class extends J{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=_,exports.ETH_ACCOUNT_PATH=N,exports.ETH_COIN_PATH=O,exports.JsonRpcBatchInternal=R,exports.LedgerSigner=q,exports.SolanaSigner=Nt,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.compileSolanaTx=e=>b.compileTransaction(e),exports.createPSBTV2=W,exports.createPsbt=E,exports.createTransferTx=M,exports.createWalletPolicy=function(e,t,r,s){const n=new p.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new p.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=Ut,exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=L,exports.getAddressFromXPub=function(e,t){const r=$(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=u.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=$,exports.getAppEth=U,exports.getBech32Address=K,exports.getBech32AddressFromXPub=function(e,t,r){return K($(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=U(e),n=await s.getAddress(r??N,t,!0),a=new i;return a.publicKey=o.Buffer.from(n.publicKey,"hex"),a.chainCode=o.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=C(e);if(!n)return 0;const{fee:a}=D(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=U(e),a=L(t,r,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(a.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaProvider=({isTestnet:e,rpcUrl:t})=>{const r=b.createSolanaRpc(e?b.devnet(t):b.mainnet(t));return new Proxy(r,{get:(e,t,r)=>t===Ot||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,r))})},exports.getTransferTxDetails=function(e,t,r,s,n){const a=D(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,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await c.mnemonicToSeed(e);return u.fromSeed(t).derivePath(N).neutered().toBase58()},exports.isERC20Transfer=F,exports.isNativeTxn=X,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[Ot],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())&&F(e,n)?s(e,{type:"erc20",contractAddress:e.to}):X(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=D,exports.serializeSolanaTx=e=>b.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:r,provider:s})=>{const{value:n}=await s.getLatestBlockhash().send(),a=[I.getTransferSolInstruction({source:b.createNoopSigner(b.address(e)),destination:b.address(t),amount:r})];return b.pipe(b.createTransactionMessage({version:0}),(e=>b.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>b.setTransactionMessageFeePayer(b.address(e),t)),(e=>b.appendTransactionMessageInstructions(a,e)))},exports.transferToken=async({from:e,to:t,mint:r,amount:s,provider:n})=>{const[a]=await T.findAssociatedTokenPda({mint:b.address(r),owner:b.address(e),tokenProgram:T.TOKEN_PROGRAM_ADDRESS}),[i]=await T.findAssociatedTokenPda({mint:b.address(r),owner:b.address(t),tokenProgram:T.TOKEN_PROGRAM_ADDRESS}),o=await T.getCreateAssociatedTokenIdempotentInstruction({payer:b.createNoopSigner(b.address(e)),mint:b.address(r),owner:b.address(t),ata:i}),d=T.getTransferInstruction({amount:s,source:a,destination:i,authority:b.createNoopSigner(b.address(e))}),{value:u}=await n.getLatestBlockhash().send();return b.pipe(b.createTransactionMessage({version:0}),(e=>b.setTransactionMessageLifetimeUsingBlockhash(u,e)),(t=>b.setTransactionMessageFeePayer(b.address(e),t)),(e=>b.appendTransactionMessageInstructions([o,d],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("@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"),h=require("micro-key-producer/slip10.js"),p=require("@avalabs/avalanchejs"),g=require("hdkey"),m=require("buffer"),f=require("@openzeppelin/contracts/build/contracts/ERC20.json"),x=require("bip32"),v=require("@ledgerhq/hw-transport"),w=require("@metamask/eth-sig-util"),y=require("ledger-bitcoin"),A=require("@ledgerhq/hw-app-btc/lib/bip32"),b=require("@noble/hashes/sha256"),I=require("@avalabs/glacier-sdk"),T=require("@avalabs/core-chains-sdk"),S=require("create-hash"),P=require("xss"),B=require("bip32-path"),C=require("@avalabs/hw-app-avalanche");function k(e){return e.reduce(((e,t)=>e+t.value),0)}class E{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:k(r.confirmed),balanceUnconfirmed:k(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function D(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 V(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 M(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function K(e,t,r,s,n,a){const i=V(e,t,r,s,M(n));return i.inputs?{...i,psbt:D(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function U(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function O(e){return new s(e,"w0w")}const N=(e,t)=>{const r=a.getTransactionDecoder().decode(a.getBase64Encoder().encode(e)),s=a.getCompiledTransactionMessageDecoder().decode(r.messageBytes);return a.decompileTransactionMessageFetchingLookupTables(s,t)},_=Symbol(),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=h.fromMasterSeed(Uint8Array.from(r)).derive(`m/44'/501'/${t}'/0'`);return new X(Buffer.from(s.privateKey))}async signTx(e,t){const r=await N(e,t),{signatures:s,messageBytes:n}=a.compileTransaction(r);if(!this.#r(s))return e;const i=l.base58.encode(c.ed25519.sign(Uint8Array.from(n),this.#e));return a.assertIsSignature(i),a.getBase64EncodedWireTransaction({messageBytes:n,signatures:{...s,[this.#t]:l.base58.decode(i)}})}#r(e){return this.#t in e&&!e[this.#t]}}const F="m/44'/60'",H=`${F}/0'`;var R=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(R||{});function q(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==R.BIP44?`m/44'/${n}'/0'/0/${e}`:`m/44'/${n}'/${e}'/0/0`}const $=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),W=(e,t)=>{const r=new n.Interface(f.abi).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var 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 J extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#s="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#s.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#s,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,j,this._parentProvider),this._maxCalls=62)}#s;#n=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.#n++,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.#s.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function z(e,t){return x.fromBase58(e).derivePath(`0/${t}`).publicKey}let G=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=q(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 v.TransportStatusError&&s.statusCode===v.StatusCodes.INS_NOT_SUPPORTED){const s=w.TypedDataUtils.hashStruct(i,r,t,w.SignTypedDataVersion.V4),a=w.TypedDataUtils.hashStruct("EIP712Domain",e,t,w.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 Y(t,r,s,n,a,i){const o=new y.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,A.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 Q(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 U(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,r,s){return K(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class ee 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=R.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=x.fromSeed(n),i=q(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new ee(o.privateKey,r)}signTx(e,t){const r=D(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 ee(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}var te=(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))(te||{});const re=e=>{switch(e){case"C":return p.EVM;case"X":return p.AVM;case"P":return p.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:se,AddressMaps:ne}=p.utils,ae=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=se(e);let i=ne.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>p.pvmSerial.isCreateChainTx(e)||p.pvmSerial.isAddSubnetValidatorTx(e)||p.pvmSerial.isRemoveSubnetValidatorTx(e)||p.pvmSerial.isTransformSubnetTx(e)||p.pvmSerial.isTransferSubnetOwnershipTx(e)||p.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=p.OutputOwners.fromNative(n.controlKeys.map((e=>p.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 p.utils.AddressMap(a)),r})({tx:e,provider:r,addressMaps:i});return new p.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else p.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 p.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(i,e,r));return new p.UnsignedTx(e,n,i,s)},{bufferToHex:ie,packTx:oe}=p.utils,{publicKeyBytesToAddress:de,recoverPublicKey:ue}=p.secp256k1,ce=new p.Signature(new Uint8Array(Array(65).fill(0))),le=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(ce);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=oe(n.getTx()),d=b.sha256(o),u=ce.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=ue(d,e.toBytes()),r={toHex:()=>ie(de(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function he(e){return p.utils.bufferToHex(p.utils.addChecksum(e.toBytes()))}const{getManagerForVM:pe,hexToBuffer:ge,unpackWithManager:me}=p.utils,fe=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=re(t);if(n===p.EVM)throw new Error("EVM transactions are not supported");const a=ge(e),i=me(n,a),o=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=pe(s).unpack(t,p.avaxSerial.SignedTx),i=await ae({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new p.Credential(le(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new p.Credential(le(e))))}})({tx:i,txBytes:a,provider:r,vm:n,utxos:s});return ae({tx:i,provider:r,credentials:o,utxos:s})},{parseBech32:xe,format:ve}=p.utils,{publicKeyBytesToAddress:we}=p.secp256k1;class ye{constructor(e,t){this.baseUrl=e,this.context=t;const r=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(r)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}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 p.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new p.avm.AVMApi(this.baseUrl)}getApiP(){return new p.pvm.PVMApi(this.baseUrl)}getApiC(){return new p.evm.EVMApi(this.baseUrl)}getInfo(){return new p.info.InfoApi(this.baseUrl)}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=we(a);return ve(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return ve(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=xe(e);return ve(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=he(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 p.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 Ae={weights:p.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)},be={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:Ae},Ie={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:Ae},Te={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:Ae};class Se extends ye{constructor(e,t){super(e,t)}static async fromBaseURL(e){const t=await p.Context.getContextFromURI(e);try{await new p.info.InfoApi(e).getUpgradesInfo();return new Se(e,t)}catch{return new Se(e,t)}}static getDefaultMainnetProvider(){return new Se(T.AVALANCHE_XP_NETWORK.rpcUrl,be)}static getDefaultFujiProvider(){return new Se(T.AVALANCHE_XP_TEST_NETWORK.rpcUrl,Ie)}static getDefaultDevnetProvider(){return new Se(T.AVALANCHE_P_DEV_NETWORK.rpcUrl,Te)}}const{bytesCompare:Pe,parseBech32:Be}=p.utils,Ce=(e,t)=>"P"===t,ke=(e,t,r)=>{const s=Ce(0,t)?e.amount:e.asset?.amount;return new p.TransferOutput(new p.BigIntPr(BigInt(s)),p.OutputOwners.fromNative(e.addresses.map((e=>Be(e)[1])).sort(Pe),BigInt(r??0),e.threshold))},Ee=(e,t)=>{const r=((e,t)=>{const r=t===I.Network.FUJI,{cBlockchainID:s,xBlockchainID:n,pBlockchainID:a}=r?Ie:be;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=Ce(0,r)?e.txHash:e.creationTxHash,n=Ce(0,r)?e.assetId:e.asset?.assetId;return new p.Utxo(p.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),p.Id.fromString(n),((e,t)=>Ce(0,t)?e.stakeableLocktime?new p.pvmSerial.StakeableLockOut(new p.BigIntPr(BigInt(e.stakeableLocktime??0)),ke(e,t,e.platformLocktime??0)):ke(e,t,e.platformLocktime):ke(e,t,e.locktime))(e,r))},{unpackWithManager:De,parse:Ve,bufferToHex:Me,AddressMaps:Ke,AddressMap:Ue}=p.utils;function Oe(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 S("sha256").update(s).digest()}const Ne=1024,_e=1024;async function Le(e,t,r){const s=e.slice(0,Ne),n=e.slice(Ne),a=await Xe(t,{...r,addresses:s});if(n.length){const s=await Le(n,t,{...r,addresses:e});return a.merge(s)}return a}async function Xe(e,t){if(t.addresses.length>Ne)throw new Error(`Can not get UTXOs for more than ${Ne} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new p.utils.UtxoSet(s);if(s.length>=_e){const s=await Xe(e,{...t,startIndex:r});return n.merge(s)}return n}function Fe(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:He}=p.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:qe,hexToBuffer:$e,unpackWithManager:We}=p.utils;function je(e,t=!0){try{if(t){const[t]=p.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else p.utils.parseBech32(e);return!0}catch(e){return!1}}const Je=e=>{if([be.xBlockchainID,Ie.xBlockchainID,Te.xBlockchainID].includes(e))return"AVM";if([be.pBlockchainID,Ie.pBlockchainID,Te.pBlockchainID].includes(e))return"PVM";if([be.cBlockchainID,Ie.cBlockchainID,Te.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},ze=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),Ge=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0));var Ye={parseCreateSubnetTx:e=>p.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:te.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>p.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:te.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=>p.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:te.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=>p.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:te.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>p.pvmSerial.isImportTx(e)||p.avmSerial.isImportTx(e)||p.evmSerial.isImportTx(e)?p.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:te.Import,chain:e.getVM(),source:Je(e.sourceChain.value()),amount:Ge(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:te.Import,chain:e.getVM(),source:Je(e.sourceChain.value()),amount:Ge(e.ins,r),...t}):null,parseExportTx:e=>p.pvmSerial.isExportTx(e)||p.avmSerial.isExportTx(e)||p.evmSerial.isExportTx(e)?p.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:te.Export,chain:e.getVM(),destination:Je(e.destinationChain.toString()),amount:ze(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:te.Export,chain:e.getVM(),destination:Je(e.destination.value()),amount:ze(e.outs,r),...t}):null,parseBaseTx:e=>p.avmSerial.isAvmBaseTx(e)||p.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())})),p.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 p.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 p.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=Fe(),o=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=i)));return{type:te.Base,chain:e.getVM(),outputs:o,memo:P(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!p.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return p.pvmSerial.isSigner(e.signer)&&(r=p.utils.bufferToHex(e.signer.proof.publicKey),t=p.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:te.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=>p.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:te.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=>p.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:te.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=>p.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:te.ConvertSubnetToL1,chain:e.getVM(),managerAddress:n(p.Address.fromHex(e.address.toString("hex"))),validators:e.validators.map((e=>({nodeId:p.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=>p.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:te.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>p.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:te.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>p.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:te.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>p.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:te.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:Qe,getOutputAmounts:Ze,getInputAmounts:et,validateBurnedAmount:tt}=p.utils;function rt(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 st(e){const t=Fe(),r=e.map((e=>({utxo:e,...p.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),a=rt(s,["amount"],"desc"),i=rt(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function nt(e,t){return rt(e.map((e=>({utxo:e,...p.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const at=e=>nt(e,!0),it=e=>nt(e,!1);const{getUtxoInfo:ot}=p.utils;var dt=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(dt||{});const ut="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",ct="11111111111111111111111111111111LpoYY",lt=(e,t)=>e.reduce(((e,t)=>e+ot(t).amount),BigInt(0))-t,ht={BaseP:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new p.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:lt(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:it,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new p.utils.UtxoSet(t),amount:lt(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:st,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new p.utils.UtxoSet(t),nodeId:ut,start:Fe(),end:Fe()+BigInt(1e3),weight:lt(t,e.getProvider().getContext().baseTxFee),subnetId:ct,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(p.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(p.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:st,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new p.utils.UtxoSet(t),nodeId:ut,start:Fe(),end:Fe()+BigInt(1e3),weight:lt(t,e.getProvider().getContext().baseTxFee),subnetId:ct,feeState:r})},ExportP:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>e.exportP({amount:lt(t,e.getProvider().getContext().baseTxFee),utxoSet:new p.utils.UtxoSet(t),destination:"X",feeState:r})},ImportP:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new p.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function pt(e){return B.validateString(e,!0)&&6===e.split("/").length}function gt(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:mt,hexToBuffer:ft}=p.utils;class xt{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Le(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 Le(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=mt(s)[2],a=this.provider.getAvaxID(),i=p.TransferableOutput.fromNative(a,e,[n]),o=nt(t.getUTXOs(),!0),d=this.provider.getChainID(r),u=this.getAddresses("X").map((e=>mt(e)[2])),c=mt(this.getChangeAddress("X"))[2];return p.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=>mt(e)[2]));mt(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const d=mt(r)[2],u=e.getUTXOs();return gt(n),p.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=>mt(e)[2])),a=mt(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const i=mt(r)[2];return p.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=>mt(e)[2]));a=a||this.getAddressEVM();const d=Buffer.from(t.strip0x(a),"hex");return p.evm.newImportTxFromBaseFee(this.provider.getContext(),d,o,e.getUTXOs(),i,s,n)}exportC(e,t,r,s,n){const a=ft(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=mt(n)[2],d=s/BigInt(1e9);return p.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=mt(n)[2],i=this.provider.getAvaxID(),o=p.TransferableOutput.fromNative(i,e,[a]),d=nt(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>mt(e)[2])),l=mt(this.getChangeAddress("P"))[2];return gt(s),p.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=it(e.getUTXOs());s=s??this.getCurrentAddress("P");const i=mt(s)[2],o=this.provider.getContext(),d=[p.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>mt(e)[2])),c=mt(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c];return gt(r),p.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]=mt(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>p.TransferableOutput.fromNative(e,t,[u]))),l=nt(e.getUTXOs(),!0),h=(i??this.getAddresses(t)).map((e=>mt(e)[2])),g=mt(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?p.avm.newBaseTx(this.provider.getContext(),h,l,c,a):(gt(n),p.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:h,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=>mt(e)[2])),c=mt(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c],h=i.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:a,remainingBalanceOwner:i})=>{const o=new p.pvmSerial.ProofOfPossession(Uint8Array.from(p.utils.hexToBuffer(t)),Uint8Array.from(p.utils.hexToBuffer(r))),d=p.PChainOwner.fromNative(i.addresses.map((e=>mt(e)[2])),i.threshold??1),u=p.PChainOwner.fromNative(a.addresses.map((e=>mt(e)[2])),a.threshold??1);return p.L1Validator.fromNative(e,n,s,o,d,u)}));return p.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:h,fromAddressesBytes:u,address:mt(a)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:nt(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=>mt(e)[2])),d=mt(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return p.pvm.newRegisterL1ValidatorTx({utxos:nt(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(p.utils.hexToBuffer(r)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:i?.memo,message:Uint8Array.from(p.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=>mt(e)[2])),i=mt(this.getChangeAddress("P"))[2],o=s?.changeAddresses??[i];return p.pvm.newSetL1ValidatorWeightTx({utxos:nt(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:a,memo:s?.memo,message:Uint8Array.from(p.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=>mt(e)[2])),o=mt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return p.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:nt(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=>mt(e)[2])),o=mt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return p.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:nt(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=nt(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>mt(e)[2])),h=mt(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[h];return gt(o),p.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=nt(e.getUTXOs(),!0),d=(s??this.getAddresses("P")).map((e=>mt(e)[2])),u=mt(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],l=t.map((e=>mt(e)[2]));return gt(r),p.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=nt(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>mt(e)[2])),h=mt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[h];return gt(o),p.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:h,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=st(e.getUTXOs()),w=(d??this.getAddresses("P")).map((e=>mt(e)[2])),y=(u??[this.getCurrentAddress("P")]).map((e=>mt(e)[2])),A=(c??[this.getCurrentAddress("P")]).map((e=>mt(e)[2]));if(!(a!==p.networkIDs.PrimaryNetworkID.toString()||l&&h))throw new Error("Must provide public key and signature for primary subnet.");const b=mt(this.getChangeAddress("P"))[2],I=g?.changeAddresses??[b];return gt(o),p.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:A,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:I,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:i,feeState:o,publicKey:l,rewardAddresses:y,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:l,stakingAssetId:h}){const g=st(e.getUTXOs()),m=(i??this.getAddresses("P")).map((e=>mt(e)[2])),f=(o??[this.getCurrentAddress("P")]).map((e=>mt(e)[2])),x=mt(this.getChangeAddress("P"))[2],v=d?.changeAddresses??[x];return gt(c),p.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:l,feeState:c},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:a,options:i}){const o=nt(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>mt(e)[2])),u=mt(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return gt(a),p.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=nt(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>mt(e)[2])),l=mt(this.getChangeAddress("P"))[2],h=i?.changeAddresses??[l],g=s.map((e=>mt(e)[2]));return gt(n),p.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 vt extends xt{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 vt(o,d,s)}static fromMnemonic(e,t,r,s){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!pt(r)||!pt(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=x.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return vt.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 wt={type:"zondax",getApp:e=>new C(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 yt(e){return!(await wt.getVersion(e)>="0.6.0")}const{parse:At}=p.utils;class bt extends xt{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=x.fromBase58(e),this.evmWallet=new vt(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=x.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath(q(0,R.BIP44,"EVM")).neutered();return new bt(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(At(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(At(e)[2])))}getRawAddressC(){return Buffer.from(At(this.getCurrentAddress("C"))[2])}}const{isTransferOut:It,isStakeableLockOut:Tt}=p.utils;function St(e){const t=e.output;return It(t)||Tt(t)?t.getOwners():[]}function Pt(e){const t=e.getTx();return p.avmSerial.isExportTx(t)||p.pvmSerial.isExportTx(t)?new Set(t.outs.map(St).flat()):p.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(St).flat()):new Set((t.baseTx?.outputs??[]).map(St).flat())}const{parse:Bt}=p.utils;class Ct extends bt{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]=Bt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await yt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=O(e),a=await wt.getXPUB(e,Ct.getAccountPath("X")),i=x.fromPublicKey(a.pubKey,a.chainCode),o=q(0,R.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 Ct(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=>B.fromString(e))),l=[...Pt(t)].map((e=>Buffer.from(e))),h=[...this.filterOwnedAddresses(l).values()].map((e=>B.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:h})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=B.fromString(Ct.getAccountPath(e.chain));return[...(await wt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:kt}=p.utils;class Et extends bt{constructor(e,t,r){const s=x.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(kt(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=x.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=u.mnemonicToSeedSync(e),s=x.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath(q(0,R.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new Et(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await p.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:Dt,sign:Vt,signHash:Mt}=p.secp256k1,{addChecksum:Kt}=p.utils;class Ut extends vt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(Dt(e)),Buffer.from(Dt(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(!pt(r)||!pt(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=x.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 Ut(i.privateKey,o.privateKey,s)}async signMessage(e){const t=Oe(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Kt(await Mt(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await p.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Vt(e.buffer,t))]}}const{strip0x:Ot}=p.utils;class Nt extends vt{constructor(e,t,r,s,a){const i=p.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),o=p.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=s,!pt(t)||!pt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await yt(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!pt(t)||!pt(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(Ot(o.publicKey),"hex"),c=Buffer.from(Ot(d.publicKey),"hex"),l=Buffer.from(Ot(n.SigningKey.computePublicKey(u,!0)),"hex"),h=Buffer.from(Ot(n.SigningKey.computePublicKey(c,!0)),"hex");return new Nt(h,t,l,r,a)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=B.fromString(this.getAccountPath(e.chain)),r=B.fromString(this.getPartialSignerPath(e.chain));return[...(await wt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:_t}=p.utils;var Lt=Object.freeze({__proto__:null,AbstractProvider:ye,AddressWallet:class extends xt{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=>!je(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!je(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(!je(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:Te,FujiContext:Ie,JsonRpcProvider:Se,LedgerSigner:Nt,LedgerWallet:Ct,MainnetContext:be,MnemonicWallet:Et,MnemonicWalletVoid:bt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=x.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof p.EVMUnsignedTx||"C"===t?p.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):p.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(_t(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),a=`0/${this.activeAccountIndex}`,i=new Map;if("C"===n||!this.accountNode)return i;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[a,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&i.set(t,e)}return i}getAddressBipPaths(e,t){return 0===t.size?[B.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(B.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(r.getAddresses(),n),i=this.getAddressBipPaths([...Pt(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=B.fromString(this.getAccountPath(e.chain));return[...(await wt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||B.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=Oe(e.message),s=(await wt.signHash(e.transport,r,B.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!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=x.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(q(t,R.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 p.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=Oe(e.message),s=await p.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:dt,StaticSigner:Ut,TxType:te,WalletAbstract:xt,WalletVoid:vt,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 fe({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 p.Credential(s)),e}),[]),d=new p.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,o);return{signedTxHex:he(new p.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:Ee,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=De(r,e),a=Ve(t)[2],i=Me(a);if(p.evmSerial.isExportTx(n))return new p.EVMUnsignedTx(n,[],new Ke([Ue.fromJSON([[i,0]])]));if(p.evmSerial.isImportTx(n)){const e=Ke.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[a]);return new p.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:ae,digestMessage:Oe,emptySignature:ce,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=x.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 x.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=Fe();return n.forEach((e=>{const t=He(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 wt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=ht[r],o=Fe(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=ot(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*ot(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(ot)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:Xe,getPchainUnixNow:async function(e){const t=e?T.AVALANCHE_XP_TEST_NETWORK.rpcUrl:T.AVALANCHE_XP_NETWORK.rpcUrl,r=await new p.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:Re,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[p.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Le,getUnixNow:Fe,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:a})=>{const i=re(t),o=$e(e),d=We(i,o);if(p.evmSerial.isExportTx(d))return[];const u=(e=>{if(p.evmSerial.isImportTx(e)||p.avmSerial.isImportTx(e)||p.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case p.EVM:return I.BlockchainId.C_CHAIN;case p.AVM:return I.BlockchainId.X_CHAIN;case p.PVM:return I.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=qe(d),l=new I.Glacier({BASE:s,TOKEN:n,HEADERS:a}),h=[...new Set(c.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(h.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=Ee(n,r);return e.push(a),e}),[])},getVmByChainAlias:re,getXpubFromMnemonic:function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=u.mnemonicToSeedSync(e);return x.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:je,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:yt,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50}={}){try{const n=t.getContext(),a=e.getTx(),i=(e=>{for(const t of Object.values(Ye)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(a),o=Qe(a,n),d=Ze(a),u=et(a).get(n.avaxAssetID)??BigInt(0),c=o.get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0);let h=BigInt(0);p.evmSerial.isImportExportTx(a)?(h=await t.getApiC().getBaseFee()/BigInt(1e9),0n===h&&(h=1n)):"PVM"===a.vm&&(h=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0))));const{isValid:g,txFee:m}=tt({unsignedTx:e,context:n,burnedAmount:c,baseFee:h,feeTolerance:s});return await i({feeData:{totalAvaxBurned:c,totalAvaxOutput:l,totalAvaxInput:u,isValidAvaxBurnedAmount:g,txFee:m},assetId:n.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:te.Unknown}}},populateCredential:le,signedTxToHex:he,sortUTXOsByAmount:nt,sortUTXOsByAmountAscending:it,sortUTXOsByAmountDescending:at,sortUTXOsStaking:st,verifyDerivationPath:pt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Lt,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 y(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=Y(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=Q(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 E{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.#a=new t.HttpClient(s||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#i=new t.HttpClient(n||d,i)}#a;#i;async#o(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#i.post("",e,{},this.extraParams))))).flat():this.#i.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#a.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,r){const s=await this.#a.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.#i.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.#o(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.#a.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.#i.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.#o([{...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.#i.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#a.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.#a.post(`/api/v2/address/${e}`,{},{},this.extraParams);return await Promise.allSettled(t.txids?.slice(0,25).map((async t=>{try{const r=await this.#a.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(),h=d?l:c,p=h.filter(((e,t)=>h.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:p,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=E,exports.BitcoinWallet=ee,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.DerivationPath=R,exports.ETH_ACCOUNT_PATH=H,exports.ETH_COIN_PATH=F,exports.JsonRpcBatchInternal=J,exports.LedgerSigner=G,exports.SolanaLedgerSigner=class{#d;#u;constructor(e,t){this.#d=L(e,!1),this.#u=t}async signTx(e,t){const r=await N(e,t),{signatures:s,messageBytes:n}=a.compileTransaction(r),i=new d(this.#u),{address:o}=await i.getAddress(this.#d),u=a.address(l.base58.encode(Uint8Array.from(o)));if(!this.#r(u,s))return e;const{signature:c}=await i.signTransaction(this.#d,Buffer.from(n)),h=l.base58.encode(Uint8Array.from(c));return a.assertIsSignature(h),a.getBase64EncodedWireTransaction({messageBytes:n,signatures:{...s,[u]:l.base58.decode(h)}})}#r(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=Y,exports.createPsbt=D,exports.createTransferTx=K,exports.createWalletPolicy=function(e,t,r,s){const n=new y.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new y.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=N,exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=q,exports.getAddressFromXPub=function(e,t){const r=z(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=x.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=z,exports.getAppEth=O,exports.getBech32Address=U,exports.getBech32AddressFromXPub=function(e,t,r){return U(z(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return U(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=m.Buffer.from(n.publicKey,"hex"),a.chainCode=m.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=k(e);if(!n)return 0;const{fee:a}=V(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=O(e),a=q(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(p.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===_||("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=V(e,t,r,s,M(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),q(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 x.fromSeed(t).derivePath(H).neutered().toBase58()},exports.isERC20Transfer=W,exports.isNativeTxn=$,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[_],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())&&W(e,n)?s(e,{type:"erc20",contractAddress:e.to}):$(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=Q,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=V,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,provider:n})=>{const[i]=await o.findAssociatedTokenPda({mint:a.address(r),owner:a.address(e),tokenProgram:o.TOKEN_PROGRAM_ADDRESS}),[d]=await o.findAssociatedTokenPda({mint:a.address(r),owner:a.address(t),tokenProgram:o.TOKEN_PROGRAM_ADDRESS}),u=await o.getCreateAssociatedTokenIdempotentInstruction({payer:a.createNoopSigner(a.address(e)),mint:a.address(r),owner:a.address(t),ata:d}),c=o.getTransferInstruction({amount:s,source:i,destination:d,authority:a.createNoopSigner(a.address(e))}),{value:l}=await n.getLatestBlockhash().send();return a.pipe(a.createTransactionMessage({version:0}),(e=>a.setTransactionMessageLifetimeUsingBlockhash(l,e)),(t=>a.setTransactionMessageFeePayer(a.address(e),t)),(e=>a.appendTransactionMessageInstructions([u,c],e)))};
@@ -1 +1 @@
1
- import"@ledgerhq/hw-app-eth";import"ethers";import"@avalabs/avalanchejs";import"hdkey";import"buffer";import"@openzeppelin/contracts/build/contracts/ERC20.json";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 o(o,e,i){const p=t(o,e);return r(p,i)}export{o as getBech32AddressFromXPub};
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"buffer";import"@openzeppelin/contracts/build/contracts/ERC20.json";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 +1 @@
1
- import{BitcoinWalletAbstract as t}from"./BitcoinWalletAbstract.js";import i from"ledger-bitcoin";import"bitcoinjs-lib";import"coinselect";import"@ledgerhq/hw-app-eth";import"ethers";import"@avalabs/avalanchejs";import"hdkey";import"buffer";import"@openzeppelin/contracts/build/contracts/ERC20.json";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
+ import{BitcoinWalletAbstract as t}from"./BitcoinWalletAbstract.js";import 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"buffer";import"@openzeppelin/contracts/build/contracts/ERC20.json";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 o}from"../utils/psbt2ToPsbt0.js";class e extends t{constructor(t,r,i,o,e){super(t,i),this.derivationPath=r,this.transport=o,this.walletPolicyDetails=e}setTransport(t){this.transport=t}async signTx(t,e){const a=function(t){return new r(t)}(this.transport),s=this.ecPair.publicKey,p=this.provider.getNetwork(),n=await a.getMasterFingerprint(),l=i(t,e,p,Buffer.from(n,"hex"),s,this.derivationPath),{policy:m,hmac:c}=this.walletPolicyDetails,h=await a.signPsbt(l,m,c),u=o(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};
@@ -0,0 +1,3 @@
1
+ declare const getSolanaDerivationPath: (accountIndex: number, withRoot?: boolean) => string;
2
+
3
+ export { getSolanaDerivationPath };
@@ -0,0 +1 @@
1
+ const o=(o,t=!0)=>`${t?"m/":""}44'/501'/${o}'/0'`;export{o as getSolanaDerivationPath};
@@ -0,0 +1,5 @@
1
+ import Transport from '@ledgerhq/hw-transport';
2
+
3
+ declare const getSolanaPublicKeyFromLedger: (accountIndex: number, transport: Transport) => Promise<Buffer>;
4
+
5
+ export { getSolanaPublicKeyFromLedger };
@@ -0,0 +1 @@
1
+ import r from"@ledgerhq/hw-app-solana";import{getSolanaDerivationPath as t}from"./derivationPath.js";const a=async(a,e)=>{const o=new r(e),{address:s}=await o.getAddress(t(a,!1));return s};export{a as getSolanaPublicKeyFromLedger};
@@ -0,0 +1,10 @@
1
+ import Transport from '@ledgerhq/hw-transport';
2
+ import { SolanaProvider } from '../utils/solanaProvider.js';
3
+
4
+ declare class SolanaLedgerSigner {
5
+ #private;
6
+ constructor(accountIndex: number, transport: Transport);
7
+ signTx(base64EncodedTx: string, provider: SolanaProvider): Promise<string>;
8
+ }
9
+
10
+ export { SolanaLedgerSigner };
@@ -0,0 +1 @@
1
+ import{base58 as r}from"@scure/base";import t from"@ledgerhq/hw-app-solana";import{compileTransaction as a,address as s,assertIsSignature as i,getBase64EncodedWireTransaction as e}from"@solana/kit";import{deserializeTransactionMessage as o}from"../utils/deserializeSolanaTx.js";import"@solana-program/system";import"@solana-program/token";import{getSolanaDerivationPath as n}from"../utils/derivationPath.js";class m{#r;#t;constructor(r,t){this.#r=n(r,!1),this.#t=t}async signTx(n,m){const d=await o(n,m),{signatures:p,messageBytes:u}=a(d),g=new t(this.#t),{address:h}=await g.getAddress(this.#r),c=s(r.encode(Uint8Array.from(h)));if(!this.#a(c,p))return n;const{signature:f}=await g.signTransaction(this.#r,Buffer.from(u)),l=r.encode(Uint8Array.from(f));return i(l),e({messageBytes:u,signatures:{...p,[c]:r.decode(l)}})}#a(r,t){return r in t&&!t[r]}}export{m as SolanaLedgerSigner};
package/esm/index.d.ts CHANGED
@@ -47,4 +47,7 @@ export { serializeSolanaTx } from './SolanaVM/utils/serializeSolanaTx.js';
47
47
  export { SolanaProvider, getSolanaProvider, isSolanaProvider } from './SolanaVM/utils/solanaProvider.js';
48
48
  export { transferSol } from './SolanaVM/utils/transferSol.js';
49
49
  export { transferToken } from './SolanaVM/utils/transferToken.js';
50
+ export { getSolanaDerivationPath } from './SolanaVM/utils/derivationPath.js';
51
+ export { getSolanaPublicKeyFromLedger } from './SolanaVM/utils/getSolanaPublicKeyFromLedger.js';
50
52
  export { SolanaSigner } from './SolanaVM/wallets/SolanaSigner.js';
53
+ export { SolanaLedgerSigner } from './SolanaVM/wallets/SolanaLedgerSigner.js';
package/esm/index.js CHANGED
@@ -1 +1 @@
1
- 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";export{networks as BtcNetworks}from"bitcoinjs-lib";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{SolanaSigner}from"./SolanaVM/wallets/SolanaSigner.js";
1
+ 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";export{networks as BtcNetworks}from"bitcoinjs-lib";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{SolanaSigner}from"./SolanaVM/wallets/SolanaSigner.js";export{SolanaLedgerSigner}from"./SolanaVM/wallets/SolanaLedgerSigner.js";
@@ -5,7 +5,10 @@ import { DerivationPath } from '../EVM/constants.js';
5
5
  * @param addressIndex Which index is the address on
6
6
  * @param pathSpec BIP44 vs LedgerLive
7
7
  * @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.
8
9
  */
9
- declare function getAddressDerivationPath(addressIndex: number, pathSpec: DerivationPath, vm: 'EVM' | 'AVM' | 'PVM'): string;
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;
10
13
 
11
14
  export { getAddressDerivationPath };
@@ -1 +1 @@
1
- import{DerivationPath as n}from"../EVM/constants.js";function t(t,o,r){if(t<0)throw new Error("Account index can not be less than 0.");const c="EVM"===r?"60":"9000";return o==n.BIP44?`m/44'/${c}'/0'/0/${t}`:`m/44'/${c}'/${t}'/0/0`}export{t as getAddressDerivationPath};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avalabs/core-wallets-sdk",
3
- "version": "3.1.0-alpha.44",
3
+ "version": "3.1.0-alpha.45",
4
4
  "license": "Limited Ecosystem License",
5
5
  "private": false,
6
6
  "main": "dist/index.js",
@@ -31,11 +31,12 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "@avalabs/avalanchejs": "4.2.0-alpha.1",
34
- "@avalabs/core-chains-sdk": "3.1.0-alpha.44",
35
- "@avalabs/glacier-sdk": "3.1.0-alpha.44",
34
+ "@avalabs/core-chains-sdk": "3.1.0-alpha.45",
35
+ "@avalabs/glacier-sdk": "3.1.0-alpha.45",
36
36
  "@avalabs/hw-app-avalanche": "0.14.1",
37
37
  "@ledgerhq/hw-app-btc": "10.2.4",
38
38
  "@ledgerhq/hw-app-eth": "6.36.1",
39
+ "@ledgerhq/hw-app-solana": "7.2.4",
39
40
  "@ledgerhq/hw-transport": "6.30.6",
40
41
  "@metamask/eth-sig-util": "7.0.2",
41
42
  "@noble/curves": "1.6.0",
@@ -58,5 +59,5 @@
58
59
  "peerDependencies": {
59
60
  "ethers": "^6.7.1"
60
61
  },
61
- "gitHead": "dfe5104408ca5f6fc06fde5811007c5679a85ff6"
62
+ "gitHead": "d03474f473574db35d534a6f02085d021885daf4"
62
63
  }