@avalabs/core-wallets-sdk 3.1.0-alpha.64 → 3.1.0-alpha.66

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.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@solana/kit"),i=require("@solana-program/system"),o=require("@solana-program/token"),d=require("@ledgerhq/hw-app-solana"),u=require("bip39"),c=require("@noble/curves/ed25519"),l=require("@scure/base"),p=require("micro-key-producer/slip10.js"),h=require("@avalabs/avalanchejs"),g=require("hdkey"),m=require("bip32"),f=require("@ledgerhq/hw-transport"),x=require("@metamask/eth-sig-util"),v=require("ledger-bitcoin"),y=require("@ledgerhq/hw-app-btc/lib/bip32"),w=require("@noble/hashes/sha256"),b=require("@avalabs/glacier-sdk"),A=require("@avalabs/core-chains-sdk"),T=require("create-hash"),I=require("xss"),S=require("bip32-path"),P=require("@avalabs/hw-app-avalanche"),B=require("buffer");function C(e){return e.reduce(((e,t)=>e+t.value),0)}class k{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:C(r.confirmed),balanceUnconfirmed:C(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function E(t,r,s){const n=new e.Psbt({network:s});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),r.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function 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 M(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function V(e,t,r,s,n,a){const i=D(e,t,r,s,M(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=(e,t)=>{const r=a.getTransactionDecoder().decode(a.getBase64Encoder().encode(e)),s=a.getCompiledTransactionMessageDecoder().decode(r.messageBytes);return a.decompileTransactionMessageFetchingLookupTables(s,t)},N=Symbol(),_=async({mint:e,owner:t,provider:r})=>{const[s]=await o.findAssociatedTokenPda({mint:a.address(e),owner:a.address(t),tokenProgram:o.TOKEN_PROGRAM_ADDRESS}),n=await r.getAccountInfo(s,{encoding:"base64"}).send();return{address:s,exists:Boolean(n.value),info:n}},L=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class X{#e;#t;constructor(e){this.#e=Uint8Array.from(e),this.#t=a.address(l.base58.encode(c.ed25519.getPublicKey(this.#e)))}static fromMnemonic(e,t){const r=u.mnemonicToSeedSync(e),s=p.fromMasterSeed(Uint8Array.from(r)).derive(`m/44'/501'/${t}'/0'`);return new X(Buffer.from(s.privateKey))}#r(e){try{return a.getCompiledTransactionMessageDecoder().decode(e),!0}catch{return!1}}async signMessage(e){const t=l.base64.decode(e);if(this.#r(t))throw new Error("Cannot use signMessage() to sign transactions!");return l.base64.encode(c.ed25519.sign(t,this.#e))}async signTx(e,t){const r=await O(e,t),{signatures:s,messageBytes:n,...i}=a.compileTransaction(r);if(!this.#s(s))return e;const o=l.base58.encode(c.ed25519.sign(Uint8Array.from(n),this.#e));return a.assertIsSignature(o),a.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...s,[this.#t]:l.base58.decode(o)}})}#s(e){return this.#t in e&&!e[this.#t]}}const F="m/44'/60'",H=`${F}/0'`;var R=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(R||{});function $(e,t,r,s=!0){if(e<0)throw new Error("Account index can not be less than 0.");if("SVM"===r)return L(e,s);const n="EVM"===r?"60":"9000";return t==R.BIP44?`m/44'/${n}'/0'/0/${e}`:`m/44'/${n}'/${e}'/0/0`}var q=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];const W=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),j=(e,t)=>{const r=new n.Interface(q).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var J=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"}];class z extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#n="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#n.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#n,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,J,this._parentProvider),this._maxCalls=62)}#n;#a=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#a++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#n.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function G(e,t){return m.fromBase58(e).derivePath(`0/${t}`).publicKey}let Y=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=$(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=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 f.TransportStatusError&&s.statusCode===f.StatusCodes.INS_NOT_SUPPORTED){const s=x.TypedDataUtils.hashStruct(i,r,t,x.SignTypedDataVersion.V4),a=x.TypedDataUtils.hashStruct("EIP712Domain",e,t,x.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function Q(t,r,s,n,a,i){const o=new v.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,y.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function Z(t,r,s,n){const a=new e.Psbt({network:r}),i=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<i;e++){const r=t.getInputWitnessUtxo(e),i=t.getInputBip32Derivation(e,s);a.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:i?[{path:n,pubkey:s,masterFingerprint:i.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)a.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return a}class ee{constructor(t,r){this.pubkey=t,this.provider=r;try{this.ecPair=e.ECPair.fromPublicKey(t)}catch(e){throw new Error("Not a valid public key.")}}ecPair;getAddressP2PKH(){return e.payments.p2pkh({pubkey:this.ecPair.publicKey,network:this.provider.getNetwork()}).address}getAddressBech32(){return K(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,r,s){return V(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class te extends ee{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=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=m.fromSeed(n),i=$(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new te(o.privateKey,r)}signTx(e,t){const r=E(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(r))}static fromEthersWallet(e,t){const r=e.privateKey;if(!r)throw new Error("Unable to get private key from ethers wallet.");const s=Buffer.from(r.substring(2),"hex");return new te(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}const re=e.networks;var se=(e=>(e.Base="base",e.AddValidator="add_validator",e.AddDelegator="add_delegator",e.Export="export",e.Import="import",e.CreateSubnet="create_subnet",e.CreateChain="create_chain",e.ConvertSubnetToL1="convert_subnet_to_l1",e.RegisterL1Validator="register_l1_validator",e.SetL1ValidatorWeight="set_l1_validator_weight",e.IncreaseL1ValidatorBalance="increase_l1_validator_balance",e.DisableL1Validator="disable_l1_validator",e.AddSubnetValidator="add_subnet_validator",e.RemoveSubnetValidator="remove_subnet_validator",e.AddPermissionlessValidator="add_permissionless_validator",e.AddPermissionlessDelegator="add_permissionless_delegator",e.TransformSubnet="transform_subnet",e.TransferSubnetOwnership="transfer_subnet_ownership",e.Unknown="unknown",e))(se||{});const ne=e=>{switch(e){case"C":return h.EVM;case"X":return h.AVM;case"P":return h.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:ae,AddressMaps:ie}=h.utils,oe=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=ae(e);let i=ie.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>h.pvmSerial.isCreateChainTx(e)||h.pvmSerial.isAddSubnetValidatorTx(e)||h.pvmSerial.isRemoveSubnetValidatorTx(e)||h.pvmSerial.isTransformSubnetTx(e)||h.pvmSerial.isTransferSubnetOwnershipTx(e)||h.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),a=h.OutputOwners.fromNative(n.controlKeys.map((e=>h.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new h.utils.AddressMap(a)),r})({tx:e,provider:r,addressMaps:i});return new h.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else h.pvmSerial.isDisableL1ValidatorTx(e)&&(i=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),a=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new h.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(i,e,r));return new h.UnsignedTx(e,n,i,s)},{bufferToHex:de,packTx:ue}=h.utils,{publicKeyBytesToAddress:ce,recoverPublicKey:le}=h.secp256k1,pe=new h.Signature(new Uint8Array(Array(65).fill(0))),he=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(pe);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=ue(n.getTx()),d=w.sha256(o),u=pe.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=le(d,e.toBytes()),r={toHex:()=>de(ce(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function ge(e){return h.utils.bufferToHex(h.utils.addChecksum(e.toBytes()))}const{getManagerForVM:me,hexToBuffer:fe,unpackWithManager:xe}=h.utils,ve=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=ne(t);if(n===h.EVM)throw new Error("EVM transactions are not supported");const a=fe(e),i=xe(n,a),o=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=me(s).unpack(t,h.avaxSerial.SignedTx),i=await oe({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new h.Credential(he(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new h.Credential(he(e))))}})({tx:i,txBytes:a,provider:r,vm:n,utxos:s});return oe({tx:i,provider:r,credentials:o,utxos:s})},{parseBech32:ye,format:we}=h.utils,{publicKeyBytesToAddress:be}=h.secp256k1;class Ae{constructor(e,t){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 h.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new h.avm.AVMApi(this.baseUrl)}getApiP(){return new h.pvm.PVMApi(this.baseUrl)}getApiC(){return new h.evm.EVMApi(this.baseUrl)}getInfo(){return new h.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=be(a);return we(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return we(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ye(e);return we(t,this.getHrp(),r)}getApiByVM(e){switch(e){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(e){switch(e){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(e){const t=e.unsignedTx.getVM(),r=ge(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,a)=>{const i=async()=>{let o;switch(r&&n+r<Date.now()&&a(new Error("Timeout")),o=s instanceof h.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),o.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{i()}),1e3)}};i()}))}}const Te={weights:h.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},Ie={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:Te},Se={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:Te},Pe={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:Te};class Be extends Ae{constructor(e,t){super(e,t)}static async fromBaseURL(e){const t=await h.Context.getContextFromURI(e);try{await new h.info.InfoApi(e).getUpgradesInfo();return new Be(e,t)}catch{return new Be(e,t)}}static getDefaultMainnetProvider(){return new Be(A.AVALANCHE_XP_NETWORK.rpcUrl,Ie)}static getDefaultFujiProvider(){return new Be(A.AVALANCHE_XP_TEST_NETWORK.rpcUrl,Se)}static getDefaultDevnetProvider(){return new Be(A.AVALANCHE_P_DEV_NETWORK.rpcUrl,Pe)}}const{bytesCompare:Ce,parseBech32:ke}=h.utils,Ee=(e,t)=>"P"===t,De=(e,t,r)=>{const s=Ee(0,t)?e.amount:e.asset?.amount;return new h.TransferOutput(new h.BigIntPr(BigInt(s)),h.OutputOwners.fromNative(e.addresses.map((e=>ke(e)[1])).sort(Ce),BigInt(r??0),e.threshold))},Me=(e,t)=>{const r=((e,t)=>{const r=t===b.Network.FUJI,{cBlockchainID:s,xBlockchainID:n,pBlockchainID:a}=r?Se:Ie;if(s===e)return"C";if(n===e)return"X";if(a===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=Ee(0,r)?e.txHash:e.creationTxHash,n=Ee(0,r)?e.assetId:e.asset?.assetId;return new h.Utxo(h.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),h.Id.fromString(n),((e,t)=>Ee(0,t)?e.stakeableLocktime?new h.pvmSerial.StakeableLockOut(new h.BigIntPr(BigInt(e.stakeableLocktime??0)),De(e,t,e.platformLocktime??0)):De(e,t,e.platformLocktime):De(e,t,e.locktime))(e,r))},{unpackWithManager:Ve,parse:Ke,bufferToHex:Ue,AddressMaps:Oe,AddressMap:Ne}=h.utils;function _e(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return T("sha256").update(s).digest()}const Le=1024,Xe=1024;async function Fe(e,t,r){const s=e.slice(0,Le),n=e.slice(Le),a=await He(t,{...r,addresses:s});if(n.length){const s=await Fe(n,t,{...r,addresses:e});return a.merge(s)}return a}async function He(e,t){if(t.addresses.length>Le)throw new Error(`Can not get UTXOs for more than ${Le} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new h.utils.UtxoSet(s);if(s.length>=Xe){const s=await He(e,{...t,startIndex:r});return n.merge(s)}return n}function Re(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:$e}=h.utils;async function qe(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await qe(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:We,hexToBuffer:je,unpackWithManager:Je}=h.utils;function ze(e,t=!0){try{if(t){const[t]=h.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else h.utils.parseBech32(e);return!0}catch(e){return!1}}const Ge=e=>{if([Ie.xBlockchainID,Se.xBlockchainID,Pe.xBlockchainID].includes(e))return"AVM";if([Ie.pBlockchainID,Se.pBlockchainID,Pe.pBlockchainID].includes(e))return"PVM";if([Ie.cBlockchainID,Se.cBlockchainID,Pe.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},Ye=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),Qe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0));var Ze={parseCreateSubnetTx:e=>h.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:se.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>h.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:se.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>h.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:se.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>h.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:se.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>h.pvmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.evmSerial.isImportTx(e)?h.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:se.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:Qe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:se.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:Qe(e.ins,r),...t}):null,parseExportTx:e=>h.pvmSerial.isExportTx(e)||h.avmSerial.isExportTx(e)||h.evmSerial.isExportTx(e)?h.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:se.Export,chain:e.getVM(),destination:Ge(e.destinationChain.toString()),amount:Ye(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:se.Export,chain:e.getVM(),destination:Ge(e.destination.value()),amount:Ye(e.outs,r),...t}):null,parseBaseTx:e=>h.avmSerial.isAvmBaseTx(e)||h.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,a=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),h.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof h.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof h.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),i=Re(),o=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=i)));return{type:se.Base,chain:e.getVM(),outputs:o,memo:I(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!h.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return h.pvmSerial.isSigner(e.signer)&&(r=h.utils.bufferToHex(e.signer.proof.publicKey),t=h.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:se.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>h.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:se.AddPermissionlessDelegator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),stakeOuts:e.stake,delegatorRewardsOwner:e.getDelegatorRewardsOwner(),...t}):null,parseTransferSubnetOwnershipTx:e=>h.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:se.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>h.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:se.ConvertSubnetToL1,chain:e.getVM(),managerAddress:`0x${e.address.toString("hex")}`,validators:e.validators.map((e=>({nodeId:h.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>h.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:se.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>h.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:se.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>h.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:se.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>h.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:se.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:et,getOutputAmounts:tt,getInputAmounts:rt,validateBurnedAmount:st}=h.utils;function nt(e,t,r){return[...e].sort(((e,s)=>{for(let n=0;n<t.length;n++){const a=t[n];if(e[a]>s[a])return"asc"===r?1:-1;if(e[a]<s[a])return"asc"===r?-1:1}return 0}))}function at(e){const t=Re(),r=e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),a=nt(s,["amount"],"desc"),i=nt(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function it(e,t){return nt(e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const ot=e=>it(e,!0),dt=e=>it(e,!1);const{getUtxoInfo:ut}=h.utils;var ct=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(ct||{});const lt="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",pt="11111111111111111111111111111111LpoYY",ht=(e,t)=>e.reduce(((e,t)=>e+ut(t).amount),BigInt(0))-t,gt={BaseP:{sortFunction:ot,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new h.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:ht(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:dt,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new h.utils.UtxoSet(t),amount:ht(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new h.utils.UtxoSet(t),nodeId:lt,start:Re(),end:Re()+BigInt(1e3),weight:ht(t,e.getProvider().getContext().baseTxFee),subnetId:pt,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(h.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(h.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:at,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new h.utils.UtxoSet(t),nodeId:lt,start:Re(),end:Re()+BigInt(1e3),weight:ht(t,e.getProvider().getContext().baseTxFee),subnetId:pt,feeState:r})},ExportP:{sortFunction:ot,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext(),n=function({numberIns:e=1},t){const r=h.Common.createDimensions({bandwidth:161*e+254,dbRead:e,dbWrite:2+e,compute:200*e});return h.Common.dimensionsToGas(r,t)}({numberIns:t.length},s.platformFeeConfig.weights),a=r?n*r.price:s.baseTxFee;return e.exportP({amount:ht(t,a),utxoSet:new h.utils.UtxoSet(t),destination:"X",feeState:r})}},ImportP:{sortFunction:ot,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new h.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function mt(e){return S.validateString(e,!0)&&6===e.split("/").length}function ft(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:xt,hexToBuffer:vt}=h.utils;class yt{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Fe(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return qe(this.getAddresses("P"),e)}async getAtomicUTXOs(e,t){if(e===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(e),s=this.provider.getChainID(t);return Fe(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}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=xt(s)[2],a=this.provider.getAvaxID(),i=h.TransferableOutput.fromNative(a,e,[n]),o=it(t.getUTXOs(),!0),d=this.provider.getChainID(r),u=this.getAddresses("X").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("X"))[2];return h.avm.newExportTx(this.provider.getContext(),d,u,o,[i],{threshold:1,changeAddresses:[c]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:a}){const i=this.provider.getChainID(t),o=this.getAddresses("P").map((e=>xt(e)[2]));xt(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const d=xt(r)[2],u=e.getUTXOs();return ft(n),h.pvm.newImportTx({fromAddressesBytes:o,utxos:u,toAddressesBytes:[d],sourceChainId:i,threshold:s,feeState:n,locktime:a},this.provider.getContext())}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>xt(e)[2])),a=xt(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const i=xt(r)[2];return h.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[i],n,{changeAddresses:[a]})}importC(e,r,s,n,a){const i=this.provider.getChainID(r),o=this.getAddresses("C").map((e=>xt(e)[2]));a=a||this.getAddressEVM();const d=Buffer.from(t.strip0x(a),"hex");return h.evm.newImportTxFromBaseFee(this.provider.getContext(),d,o,e.getUTXOs(),i,s,n)}exportC(e,t,r,s,n){const a=vt(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=xt(n)[2],d=s/BigInt(1e9);return h.evm.newExportTxFromBaseFee(this.provider.getContext(),d,e,i,a,[o],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const a=xt(n)[2],i=this.provider.getAvaxID(),o=h.TransferableOutput.fromNative(i,e,[a]),d=it(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>xt(e)[2])),l=xt(this.getChangeAddress("P"))[2];return ft(s),h.pvm.newExportTx({changeAddressesBytes:[l],fromAddressesBytes:c,utxos:d,outputs:[o],destinationChainId:u,feeState:s},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const a=dt(e.getUTXOs());s=s??this.getCurrentAddress("P");const i=xt(s)[2],o=this.provider.getContext(),d=[h.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c];return ft(r),h.pvm.newBaseTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:a,outputs:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},o)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:a,fromAddresses:i}){const[o,d,u]=xt(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>h.TransferableOutput.fromNative(e,t,[u]))),l=it(e.getUTXOs(),!0),p=(i??this.getAddresses(t)).map((e=>xt(e)[2])),g=xt(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?h.avm.newBaseTx(this.provider.getContext(),p,l,c,a):(ft(n),h.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:p,utxos:l,outputs:c,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:a,validators:i,options:o,fromAddresses:d}){const u=(d??this.getAddresses("P")).map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c],p=i.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:a,remainingBalanceOwner:i})=>{const o=new h.pvmSerial.ProofOfPossession(Uint8Array.from(h.utils.hexToBuffer(t)),Uint8Array.from(h.utils.hexToBuffer(r))),d=h.PChainOwner.fromNative(i.addresses.map((e=>xt(e)[2])),i.threshold??1),u=h.PChainOwner.fromNative(a.addresses.map((e=>xt(e)[2])),a.threshold??1);return h.L1Validator.fromNative(e,n,s,o,d,u)}));return h.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:p,fromAddressesBytes:u,address:xt(a)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:it(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:a,options:i}){const o=(a??this.getAddresses("P")).map((e=>xt(e)[2])),d=xt(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return h.pvm.newRegisterL1ValidatorTx({utxos:it(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(h.utils.hexToBuffer(r)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:i?.memo,message:Uint8Array.from(h.utils.hexToBuffer(s)),minIssuanceTime:i?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){const a=(n??this.getAddresses("P")).map((e=>xt(e)[2])),i=xt(this.getChangeAddress("P"))[2],o=s?.changeAddresses??[i];return h.pvm.newSetL1ValidatorWeightTx({utxos:it(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:a,memo:s?.memo,message:Uint8Array.from(h.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:a}){const i=(s??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return h.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:it(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:a}){const i=(s??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=r?.changeAddresses??[o];return h.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:it(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:a,subnetAuth:i,feeState:o,options:d,fromAddresses:u}){const c=it(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[p];return ft(o),h.pvm.newCreateChainTx({chainName:r,feeState:o,fromAddressesBytes:l,fxIds:n,genesisData:a,subnetAuth:i,subnetId:t,utxos:c,vmId:s,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:a,locktime:i}){const o=it(e.getUTXOs(),!0),d=(s??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],l=t.map((e=>xt(e)[2]));return ft(r),h.pvm.newCreateSubnetTx({fromAddressesBytes:d,changeAddressesBytes:c,utxos:o,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:a,locktime:i,subnetOwners:l},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:i,feeState:o,fromAddresses:d,options:u}){const c=it(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[p];return ft(o),h.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:l,utxos:c,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:a,subnetAuth:i,feeState:o},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:i,feeState:o,fromAddresses:d,rewardAddresses:u,delegatorRewardAddresses:c,publicKey:l,signature:p,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=at(e.getUTXOs()),y=(d??this.getAddresses("P")).map((e=>xt(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),b=(c??[this.getCurrentAddress("P")]).map((e=>xt(e)[2]));if(!(a!==h.networkIDs.PrimaryNetworkID.toString()||l&&p))throw new Error("Must provide public key and signature for primary subnet.");const A=xt(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[A];return ft(o),h.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:y,delegatorRewardsOwner:b,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,start:r,end:s,weight:n,subnetId:a,shares:i,feeState:o,publicKey:l,rewardAddresses:w,signature:p,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:a,fromAddresses:i,rewardAddresses:o,options:d,locktime:u,feeState:c,threshold:l,stakingAssetId:p}){const g=at(e.getUTXOs()),m=(i??this.getAddresses("P")).map((e=>xt(e)[2])),f=(o??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),x=xt(this.getChangeAddress("P"))[2],v=d?.changeAddresses??[x];return ft(c),h.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:d?.minIssuanceTime,memo:d?.memo,changeAddressesBytes:v,nodeId:t,start:r,end:s,weight:n,subnetId:a,rewardAddresses:f,locktime:u,stakingAssetId:p,threshold:l,feeState:c},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:a,options:i}){const o=it(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return ft(a),h.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:c,fromAddressesBytes:d,utxos:o,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:a},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:a,options:i,threshold:o,locktime:d}){const u=it(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>xt(e)[2])),l=xt(this.getChangeAddress("P"))[2],p=i?.changeAddresses??[l],g=s.map((e=>xt(e)[2]));return ft(n),h.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:p,fromAddressesBytes:c,utxos:u,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:o,locktime:d},this.provider.getContext())}}class wt extends yt{constructor(e,t,r){if(super(r),this.pubkeyXP=e,this.pubkeyC=t,33!==t.length||33!==e.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(e,r,s){const a=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new wt(o,d,s)}static fromMnemonic(e,t,r,s){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!mt(r)||!mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=u.mnemonicToSeedSync(e),a=m.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return wt.fromPublicKey(o.publicKey,i.publicKey,s)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return n.computeAddress(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(e){return[this.getAddress(e)]}getChangeAddress(e){return this.getAddress(e)}getCurrentAddress(e){return this.getAddress(e)}}const bt={type:"zondax",getApp:e=>new P(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,r={show:!1,hrp:"avax"}){const s=this.getApp(e);return{publicKey:(await s.getAddressAndPubKey(t.toString(),r.show,r.hrp)).publicKey}},async getXPUB(e,t){const r=this.getApp(e),s=await r.getExtendedPubKey(t,!1);return{pubKey:s.publicKey,chainCode:s.chain_code}},async signHash(e,t,r,s){const n=this.getApp(e),a=s.map((e=>e.toString(!0))),i=await n.signHash(r.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const a=this.getApp(e),i=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(r.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function At(e){return!(await bt.getVersion(e)>="0.6.0")}const{parse:Tt}=h.utils;class It extends yt{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=m.fromBase58(e),this.evmWallet=new wt(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=u.mnemonicToSeedSync(e),s=m.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath($(0,R.BIP44,"EVM")).neutered();return new It(n.toBase58(),a.publicKey,t)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const r=`${t?1:0}/${e}`,s=this.pubkeyCache[r];if(s)return s;const{publicKey:n}=this.accountNode.derivePath(r);return this.pubkeyCache[r]=n,n}getAddressAtIndex(e,t=!1,r){const s=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(s,r)}getExternalAddresses(e){const t=[];for(let r=0;r<=this.externalIndex;r++)t.push(this.getAddressAtIndex(r,!1,e));return t}getInternalAddresses(e){const t=[];for(let r=0;r<=this.internalIndex;r++)t.push(this.getAddressAtIndex(r,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getRawAddressC(){return Buffer.from(Tt(this.getCurrentAddress("C"))[2])}}const{isTransferOut:St,isStakeableLockOut:Pt}=h.utils;function Bt(e){const t=e.output;return St(t)||Pt(t)?t.getOwners():[]}function Ct(e){const t=e.getTx();return h.avmSerial.isExportTx(t)||h.pvmSerial.isExportTx(t)?new Set(t.outs.map(Bt).flat()):h.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(Bt).flat()):new Set((t.baseTx?.outputs??[]).map(Bt).flat())}const{parse:kt}=h.utils;class Et extends It{constructor(e,t,r){super(e,t,r)}getAdditionalAddressesByIndices(e,t,r){return"C"===r?[]:e.map((e=>{const s=this.getAddressAtIndex(e,t,r),[,,n]=kt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await At(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=U(e),a=await bt.getXPUB(e,Et.getAccountPath("X")),i=m.fromPublicKey(a.pubKey,a.chainCode),o=$(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 Et(i.toBase58(),c,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>S.fromString(e))),l=[...Ct(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>S.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:p})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=S.fromString(Et.getAccountPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:Dt}=h.utils;class Mt extends It{constructor(e,t,r){const s=m.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(Dt(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=m.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=u.mnemonicToSeedSync(e),s=m.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath($(0,R.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new Mt(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Vt,sign:Kt,signHash:Ut}=h.secp256k1,{addChecksum:Ot}=h.utils;class Nt extends wt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(Vt(e)),Buffer.from(Vt(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!mt(r)||!mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=u.mnemonicToSeedSync(e),a=m.fromSeed(n),i=a.derivePath(t),o=a.derivePath(r);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Nt(i.privateKey,o.privateKey,s)}async signMessage(e){const t=_e(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Ot(await Ut(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Kt(e.buffer,t))]}}const{strip0x:_t}=h.utils;class Lt extends wt{constructor(e,t,r,s,a){const i=h.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),o=h.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=s,!mt(t)||!mt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await At(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!mt(t)||!mt(r))throw new Error("Invalid path configuration.");const i=new s(e),o=await i.getAddress(r,!1),d=await i.getAddress(t,!1),u=Buffer.from(_t(o.publicKey),"hex"),c=Buffer.from(_t(d.publicKey),"hex"),l=Buffer.from(_t(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(_t(n.SigningKey.computePublicKey(c,!0)),"hex");return new Lt(p,t,l,r,a)}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=S.fromString(this.getAccountPath(e.chain)),r=S.fromString(this.getPartialSignerPath(e.chain)),s=_e(e.message),n=(await bt.signHash(e.transport,s,t,[r])).signatures.get(r.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=S.fromString(this.getAccountPath(e.chain)),r=S.fromString(this.getPartialSignerPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Xt}=h.utils;var Ft=Object.freeze({__proto__:null,AbstractProvider:Ae,AddressWallet:class extends yt{constructor(e,t,r,s,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=r,this.xpChangeAddress=s,r.length<1)throw new Error("Must have at least 1 xp address.");if(!n.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(r.some((e=>!ze(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!ze(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(s)}setChangeAddress(e){if(!ze(e,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=e}getAddressEVM(){return this.addressC}getAddresses(e){return("C"===e?[this.addressCoreEth]:this.xpAddresses).map((t=>this.provider.formatAddress(t,e)))}getChangeAddress(e){const t="C"===e?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(t,e)}getCurrentAddress(e){const t="C"===e?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(t,e)}},DevnetContext:Pe,FujiContext:Se,JsonRpcProvider:Be,LedgerSigner:Lt,LedgerWallet:Et,MainnetContext:Ie,MnemonicWallet:Mt,MnemonicWalletVoid:It,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=m.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof h.EVMUnsignedTx||"C"===t?h.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):h.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Xt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),a=`0/${this.activeAccountIndex}`,i=new Map;if("C"===n||!this.accountNode)return i;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[a,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&i.set(t,e)}return i}getAddressBipPaths(e,t){return 0===t.size?[S.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(S.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(r.getAddresses(),n),i=this.getAddressBipPaths([...Ct(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=S.fromString(this.getAccountPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||S.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=_e(e.message),s=(await bt.signHash(e.transport,r,S.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=u.mnemonicToSeedSync(e),s=m.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath($(t,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 h.addTxSignatures({unsignedTx:t,privateKeys:a}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=_e(e.message),s=await h.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:ct,StaticSigner:Nt,TxType:se,WalletAbstract:yt,WalletVoid:wt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await ve({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const i=a.getCredentials(),o=a.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=i[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new h.Credential(s)),e}),[]),d=new h.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,o);return{signedTxHex:ge(new h.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:Me,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,credentials:s,utxos:n})=>{const a=Ve(r,e),i=Ke(t)[2],o=Ue(i);if(h.evmSerial.isExportTx(a))return new h.EVMUnsignedTx(a,[],new Oe([Ne.fromJSON([[o,0]])]),s);if(h.evmSerial.isImportTx(a)){const e=Oe.fromTransferableInputs(a.importedInputs,n,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new h.UnsignedTx(a,n,e,s)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:oe,digestMessage:_e,emptySignature:pe,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=m.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(i,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return m.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=Re();return n.forEach((e=>{const t=$e(e);s[t.threshold>1?"multisig":t.locktime>a?"locked":t.stakeableLocktime>a?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getLedgerProvider:async function(e){return bt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=gt[r],o=Re(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=ut(e);return t<o&&(s<o||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),u=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let a=-1;for(;s<=n;){const i=Math.floor((s+n)/2);t(e.slice(0,i+1))<=r?(a=i,s=i+1):n=i-1}return a}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*ut(t).threshold)),0);return 6+e.toBytes().length+t}(i(e,t,n))}catch(e){return console.log("Unable to estimate size of utxos",{e:e,utxos:t.map(ut)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:He,getPchainUnixNow:async function(e){const t=e?A.AVALANCHE_XP_TEST_NETWORK.rpcUrl:A.AVALANCHE_XP_NETWORK.rpcUrl,r=await new h.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:qe,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[h.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Fe,getUnixNow:Re,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:a})=>{const i=ne(t),o=je(e),d=Je(i,o);if(h.evmSerial.isExportTx(d))return[];const u=(e=>{if(h.evmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case h.EVM:return b.BlockchainId.C_CHAIN;case h.AVM:return b.BlockchainId.X_CHAIN;case h.PVM:return b.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=We(d),l=new b.Glacier({BASE:s,TOKEN:n,HEADERS:a}),p=[...new Set(c.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(p.map((e=>l.primaryNetworkTransactions.getTxByHash({blockchainId:u,network:r,txHash:e}))));return c.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=Me(n,r);return e.push(a),e}),[])},getVmByChainAlias:ne,getXpubFromMnemonic:function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=u.mnemonicToSeedSync(e);return m.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:ze,isConvertSubnetToL1Tx:function(e){return"convert_subnet_to_l1"===e.type},isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isDisableL1ValidatorTx:function(e){return"disable_l1_validator"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isIncreaseL1ValidatorBalance:function(e){return"increase_l1_validator_balance"===e.type},isObsidianApp:At,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50,baseFee:n}={}){try{const a=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(Ze)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=et(i,a),u=tt(i),c=rt(i).get(a.avaxAssetID)??BigInt(0),l=d.get(a.avaxAssetID)??BigInt(0),p=u.get(a.avaxAssetID)??BigInt(0);let g=n;void 0===g&&(g=0n,h.evmSerial.isImportExportTx(i)?(g=await t.getApiC().getBaseFee()/BigInt(1e9),0n===g&&(g=1n)):"PVM"===i.vm&&(g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0)))));const{isValid:m,txFee:f}=st({unsignedTx:e,context:a,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f,baseFee:g},assetId:a.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:se.Unknown}}},populateCredential:he,signedTxToHex:ge,sortUTXOsByAmount:it,sortUTXOsByAmountAscending:dt,sortUTXOsByAmountDescending:ot,sortUTXOsStaking:at,verifyDerivationPath:mt});exports.Avalanche=Ft,exports.BitcoinLedgerWallet=class extends ee{constructor(e,t,r,s,n){super(e,r),this.derivationPath=t,this.transport=s,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const r=function(e){return new v.AppClient(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=Q(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=Z(i,n,s,this.derivationPath);if(u.forEach((e=>{const[t,r]=e;c.updateInput(t,{partialSig:[{signature:r.signature,pubkey:r.pubkey}]})})),!c.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return c.finalizeAllInputs(),c.extractTransaction()}},exports.BitcoinProvider=class extends k{constructor(e=!0,r,s,n,a){super(),this.isMainnet=e,this.extraParams=a;const i=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#i=new t.HttpClient(s||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#o=new t.HttpClient(n||d,i)}#i;#o;async#d(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#o.post("",e,{},this.extraParams))))).flat():this.#o.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#i.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,r){const s=await this.#i.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.#o.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.#d(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.#i.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.#o.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.#d([{...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.#o.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#i.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.#i.post(`/api/v2/address/${e}`,{},{},this.extraParams),r=t.txids?.slice(0,25)??[];return await Promise.allSettled(r.map((async t=>{try{const r=await this.#i.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const r=t.vin.filter((t=>t.addresses?.includes(e))),s=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),a=t.vout.filter((t=>!t.addresses?.includes(e))),i=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=i>o;let u=o-i;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=a.map((e=>e.addresses||[])).flat(),p=d?l:c,h=p.filter(((e,t)=>p.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:h,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,r)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:r=1,pollInterval:s=500}={}){try{return await this.getTransaction(e)}catch(n){if(r>=t)throw n;return await new Promise((e=>setTimeout(e,s))),this.waitForTx(e,{maxAttempts:t,attempt:r+1,pollInterval:s})}}},exports.BitcoinProviderAbstract=k,exports.BitcoinWallet=te,exports.BitcoinWalletAbstract=ee,exports.BitcoinWalletVoid=class extends ee{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=re,exports.DerivationPath=R,exports.ETH_ACCOUNT_PATH=H,exports.ETH_COIN_PATH=F,exports.JsonRpcBatchInternal=z,exports.LedgerSigner=Y,exports.SolanaLedgerSigner=class{#u;#c;constructor(e,t){this.#u=L(e,!1),this.#c=t}async signTx(e,t){const r=await O(e,t),{signatures:s,messageBytes:n,...i}=a.compileTransaction(r),o=new d(this.#c),{address:u}=await o.getAddress(this.#u),c=a.address(l.base58.encode(Uint8Array.from(u)));if(!this.#s(c,s))return e;const{signature:p}=await o.signTransaction(this.#u,Buffer.from(n)),h=l.base58.encode(Uint8Array.from(p));return a.assertIsSignature(h),a.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...s,[c]:l.base58.decode(h)}})}#s(e,t){return e in t&&!t[e]}},exports.SolanaSigner=X,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.compileSolanaTx=e=>a.compileTransaction(e),exports.createPSBTV2=Q,exports.createPsbt=E,exports.createTransferTx=V,exports.createWalletPolicy=function(e,t,r,s){const n=new v.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new v.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=O,exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=$,exports.getAddressFromXPub=function(e,t){const r=G(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=m.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=G,exports.getAppEth=U,exports.getBech32Address=K,exports.getBech32AddressFromXPub=function(e,t,r){return K(G(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return K(Buffer.from(s,"hex"),r)},exports.getEvmAddressFromPubKey=function(e){return n.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e){const t=await e.send(176,1,0,0),r=t.readUInt8(1),s=t.readUInt8(2+r),n=t.subarray(2,2+r),a=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:a.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=U(e),n=await s.getAddress(r??H,t,!0),a=new g;return a.publicKey=B.Buffer.from(n.publicKey,"hex"),a.chainCode=B.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=C(e);if(!n)return 0;const{fee:a}=D(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=U(e),a=$(t,r,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(h.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaDerivationPath=L,exports.getSolanaProvider=({isTestnet:e,rpcUrl:t})=>{const r=a.createSolanaRpc(e?a.devnet(t):a.mainnet(t));return new Proxy(r,{get:(e,t,r)=>t===N||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,r))})},exports.getSolanaPublicKeyFromLedger=async(e,t)=>{const r=new d(t),{address:s}=await r.getAddress(L(e,!1));return s},exports.getTransferTxDetails=function(e,t,r,s,n){const a=D(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),$(t,r,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await u.mnemonicToSeed(e);return m.fromSeed(t).derivePath(H).neutered().toBase58()},exports.isERC20Transfer=j,exports.isNativeTxn=W,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[N],exports.maybeGetAssociatedTokenAccount=_,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,r)=>(void 0!==e[r]&&(t[r]=e[r]),t)),{})},exports.onBalanceChange=async(e,t,r,s)=>{const n=new Set(e.map((e=>e.toLowerCase()))),a=new Set(t.map((e=>e.toLowerCase()))),i=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&a.has(e.to.toLowerCase())&&j(e,n)?s(e,{type:"erc20",contractAddress:e.to}):W(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",i);return{unsubscribe:()=>o.off("block",i)}},exports.openLedgerApp=async function(e,t){try{return(await e.send(224,216,0,0,Buffer.from(t,"ascii"))).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.psbt2ToPsbt0=Z,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=D,exports.serializeSolanaTx=e=>a.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:r,provider:s})=>{const{value:n}=await s.getLatestBlockhash().send(),o=[i.getTransferSolInstruction({source:a.createNoopSigner(a.address(e)),destination:a.address(t),amount:r})];return a.pipe(a.createTransactionMessage({version:0}),(e=>a.setTransactionMessageLifetimeUsingBlockhash(n,e)),(t=>a.setTransactionMessageFeePayer(a.address(e),t)),(e=>a.appendTransactionMessageInstructions(o,e)))},exports.transferToken=async({from:e,to:t,mint:r,amount:s,decimals:n,provider:i})=>{const{address:d}=await _({mint:a.address(r),owner:a.address(e),provider:i}),{address:u,exists:c}=await _({mint:a.address(r),owner:a.address(t),provider:i}),l=[];c||l.push(o.getCreateAssociatedTokenIdempotentInstruction({payer:a.createNoopSigner(a.address(e)),mint:a.address(r),owner:a.address(t),ata:u})),l.push(o.getTransferCheckedInstruction({amount:s,authority:a.createNoopSigner(a.address(e)),decimals:n,mint:a.address(r),destination:u,source:d}));const{value:p}=await i.getLatestBlockhash().send();return a.pipe(a.createTransactionMessage({version:0}),(e=>a.setTransactionMessageLifetimeUsingBlockhash(p,e)),(t=>a.setTransactionMessageFeePayer(a.address(e),t)),(e=>a.appendTransactionMessageInstructions(l,e)))};
1
+ "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),s=require("coinselect"),r=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@solana/kit"),i=require("@solana-program/system"),o=require("@solana-program/token"),d=require("@ledgerhq/hw-app-solana"),u=require("bip39"),c=require("@noble/curves/ed25519"),l=require("@scure/base"),p=require("micro-key-producer/slip10.js"),h=require("@avalabs/avalanchejs"),g=require("hdkey"),m=require("bip32"),f=require("@ledgerhq/hw-transport"),x=require("@metamask/eth-sig-util"),v=require("ledger-bitcoin"),y=require("@ledgerhq/hw-app-btc/lib/bip32"),w=require("@noble/hashes/sha256"),b=require("@avalabs/glacier-sdk"),A=require("@avalabs/core-chains-sdk"),T=require("create-hash"),I=require("xss"),S=require("bip32-path"),P=require("@avalabs/hw-app-avalanche"),B=require("buffer");function C(e){return e.reduce(((e,t)=>e+t.value),0)}class k{async getUtxoBalance(e,t=!0){const s=await this.getUTXOs(e,t);return{balance:C(s.confirmed),balanceUnconfirmed:C(s.unconfirmed),utxos:s.confirmed,utxosUnconfirmed:s.unconfirmed}}}function E(t,s,r){const n=new e.Psbt({network:r});return t.forEach((e=>{n.addInput({hash:e.txHash,index:e.index,witnessUtxo:{script:Buffer.from(e.script,"hex"),value:e.value}})})),s.forEach((e=>{n.addOutput({value:e.value,address:e.address})})),n}function D(e,t,r,n,a){const i=[{address:e,value:r}],{inputs:o,outputs:d,fee:u}=s(a,i,n);if(!o||!d)return{fee:u};const c=[d[0]],l=d[1];return l&&c.push({address:t,value:l.value}),{inputs:o,outputs:c,fee:u}}function M(e){const t=[];return e.filter((e=>{const s=e.txHash+e.index.toString();return!t.includes(s)&&(t.push(s),!0)}))}function V(e,t,s,r,n,a){const i=D(e,t,s,r,M(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,s){return e.payments.p2wpkh({pubkey:t,network:s}).address}function O(e){return new r(e,"w0w")}const U=(e,t)=>{const s=a.getTransactionDecoder().decode(a.getBase64Encoder().encode(e)),r=a.getCompiledTransactionMessageDecoder().decode(s.messageBytes);return a.decompileTransactionMessageFetchingLookupTables(r,t)},N=Symbol(),_=async({mint:e,owner:t,provider:s})=>{const[r]=await o.findAssociatedTokenPda({mint:a.address(e),owner:a.address(t),tokenProgram:o.TOKEN_PROGRAM_ADDRESS}),n=await s.getAccountInfo(r,{encoding:"base64"}).send();return{address:r,exists:Boolean(n.value),info:n}},L=(e,t=!0)=>`${t?"m/":""}44'/501'/${e}'/0'`;class X{#e;#t;constructor(e){this.#e=Uint8Array.from(e),this.#t=a.address(l.base58.encode(c.ed25519.getPublicKey(this.#e)))}static fromMnemonic(e,t){const s=u.mnemonicToSeedSync(e),r=p.fromMasterSeed(Uint8Array.from(s)).derive(`m/44'/501'/${t}'/0'`);return new X(Buffer.from(r.privateKey))}#s(e){try{return a.getCompiledTransactionMessageDecoder().decode(e),!0}catch{return!1}}async signMessage(e){const t=l.base64.decode(e);if(this.#s(t))throw new Error("Cannot use signMessage() to sign transactions!");return l.base64.encode(c.ed25519.sign(t,this.#e))}async signTx(e,t){const s=await U(e,t),{signatures:r,messageBytes:n,...i}=a.compileTransaction(s);if(!this.#r(r))return e;const o=l.base58.encode(c.ed25519.sign(Uint8Array.from(n),this.#e));return a.assertIsSignature(o),a.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...r,[this.#t]:l.base58.decode(o)}})}#r(e){return this.#t in e&&!e[this.#t]}}const F="m/44'/60'",H=`${F}/0'`;var q=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(q||{});function R(e,t,s,r=!0){if(e<0)throw new Error("Account index can not be less than 0.");if("SVM"===s)return L(e,r);const n="EVM"===s?"60":"9000";return t==q.BIP44?`m/44'/${n}'/0'/0/${e}`:`m/44'/${n}'/${e}'/0/0`}var $=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"subtractedValue",type:"uint256"}],name:"decreaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"addedValue",type:"uint256"}],name:"increaseAllowance",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];const W=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),j=(e,t)=>{const s=new n.Interface($).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===s?.name)return t.has(s.args[0]?.toLowerCase());if("transferFrom"===s?.name){const e=t.has(s.args[0]?.toLowerCase()),r=t.has(s.args[1]?.toLowerCase());return e||r}return!1};var J=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"}];class z extends n.JsonRpcProvider{url;constructor(e,t,s){super(t,s,{staticNetwork:s}),this.#n="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#n.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#n,s,{staticNetwork:s}),this._multicallContract=new n.Contract(e.multiContractAddress,J,this._parentProvider),this._maxCalls=62)}#n;#a=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const s={method:e,params:t,id:this.#a++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const r={request:s,resolve:null,reject:null},n=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return this._pendingBatch.push(r),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,s)=>{const r=t[s];if(r.error){const t=new Error(r.error.message);t.code=r.error.code,t.data=r.error.data,e.reject(t)}else e.resolve(r.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const s=this.#n.clone();s.body=t;return(await s.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function G(e,t){return m.fromBase58(e).derivePath(`0/${t}`).publicKey}let Y=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,s,r){super(),this.path=R(e,s,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=s,this._eth=O(t),n.defineProperties(this,{path:this.path,type:"default",provider:r??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),s=await this._eth.signPersonalMessage(this.path,t);return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const s=n.Transaction.from(t),r=s.unsignedSerialized,a=await this._eth.signTransaction(this.path,r.slice(2),null);return s.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},s.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,s){const{EIP712Domain:r,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const r=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:s});return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}catch(r){if(r instanceof f.TransportStatusError&&r.statusCode===f.StatusCodes.INS_NOT_SUPPORTED){const r=x.TypedDataUtils.hashStruct(i,s,t,x.SignTypedDataVersion.V4),a=x.TypedDataUtils.hashStruct("EIP712Domain",e,t,x.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),r.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw r}}};function Q(t,s,r,n,a,i){const o=new v.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(s.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,y.pathStringToArray(i))})),s.forEach(((t,s)=>{const n=e.address.toOutputScript(t.address,r);o.setOutputAmount(s,t.value),o.setOutputScript(s,n)})),o}function Z(t,s,r,n){const a=new e.Psbt({network:s}),i=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<i;e++){const s=t.getInputWitnessUtxo(e),i=t.getInputBip32Derivation(e,r);a.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:s?{value:s.amount,script:s.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:i?[{path:n,pubkey:r,masterFingerprint:i.masterFingerprint}]:void 0})}for(let r=0;r<o;r++)a.addOutput({value:t.getOutputAmount(r),address:e.address.fromOutputScript(t.getOutputScript(r),s)});return a}class ee{constructor(t,s){this.pubkey=t,this.provider=s;try{this.ecPair=e.ECPair.fromPublicKey(t)}catch(e){throw new Error("Not a valid public key.")}}ecPair;getAddressP2PKH(){return e.payments.p2pkh({pubkey:this.ecPair.publicKey,network:this.provider.getNetwork()}).address}getAddressBech32(){return K(this.ecPair.publicKey,this.provider.getNetwork())}async getUTXOs(){return this.provider.getUTXOs(this.getAddressBech32(),!0)}async getBalances(){return this.provider.getBalances(this.getAddressBech32())}async getUtxoBalance(){return this.provider.getUtxoBalance(this.getAddressBech32())}connect(e){this.provider=e}getProvider(){return this.provider}getPublicKey(){return this.ecPair.publicKey}createTransferTx(e,t,s,r){return V(e,this.getAddressBech32(),t,s,r,this.provider.getNetwork())}}class te extends ee{keypair;constructor(t,s){const r=e.ECPair.fromPrivateKey(t);super(r.publicKey,s),this.keypair=r}static async fromMnemonic(e,t,s,r=q.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await u.mnemonicToSeed(e),a=m.fromSeed(n),i=R(t,r,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new te(o.privateKey,s)}signTx(e,t){const s=E(e,t,this.provider.getNetwork());return Promise.resolve(this.signPsbt(s))}static fromEthersWallet(e,t){const s=e.privateKey;if(!s)throw new Error("Unable to get private key from ethers wallet.");const r=Buffer.from(s.substring(2),"hex");return new te(r,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}const se=e.networks;var re=(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))(re||{});const ne=e=>{switch(e){case"C":return h.EVM;case"X":return h.AVM;case"P":return h.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:ae,AddressMaps:ie}=h.utils,oe=async({tx:e,fromAddressBytes:t,provider:s,credentials:r,utxos:n})=>{const a=ae(e);let i=ie.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>h.pvmSerial.isCreateChainTx(e)||h.pvmSerial.isAddSubnetValidatorTx(e)||h.pvmSerial.isRemoveSubnetValidatorTx(e)||h.pvmSerial.isTransformSubnetTx(e)||h.pvmSerial.isTransferSubnetOwnershipTx(e)||h.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:s})=>{const r=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),a=h.OutputOwners.fromNative(n.controlKeys.map((e=>h.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,s)=>(r.includes(s)&&e.push([t,s]),e)),[]);return s.push(new h.utils.AddressMap(a)),s})({tx:e,provider:s,addressMaps:i});return new h.UnsignedTx(e,n,t,r)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else h.pvmSerial.isDisableL1ValidatorTx(e)&&(i=await async function(e,t,s){try{const{deactivationOwner:r}=await s.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),a=r.addresses.reduce(((e,t,s)=>(n.includes(s)&&e.push([t,s]),e)),[]);return e.push(new h.utils.AddressMap(a)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(i,e,s));return new h.UnsignedTx(e,n,i,r)},{bufferToHex:de,packTx:ue}=h.utils,{publicKeyBytesToAddress:ce,recoverPublicKey:le}=h.secp256k1,pe=new h.Signature(new Uint8Array(Array(65).fill(0))),he=(e,t)=>{const s=Math.max(...e);if(!isFinite(s))throw new Error("Error while adding placeholder signatures for the provided indices.");const r=new Array(s+1).fill(pe);if(!t)return r;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return r;const o=ue(n.getTx()),d=w.sha256(o),u=pe.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=le(d,e.toBytes()),s={toHex:()=>de(ce(t))},i=n.addressMaps.getSigIndicesForAddress(s,!1)??[];for(const t of i)t[0]===a&&(r[t[1]]=e)}return r};function ge(e){return h.utils.bufferToHex(h.utils.addChecksum(e.toBytes()))}const{getManagerForVM:me,hexToBuffer:fe,unpackWithManager:xe}=h.utils,ve=async({transactionHex:e,chainAlias:t,provider:s,utxos:r})=>{const n=ne(t);if(n===h.EVM)throw new Error("EVM transactions are not supported");const a=fe(e),i=xe(n,a),o=await(async({tx:e,txBytes:t,provider:s,vm:r,utxos:n})=>{try{const a=me(r).unpack(t,h.avaxSerial.SignedTx),i=await oe({tx:e,utxos:n,provider:s,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new h.Credential(he(e,{unsignedTx:i,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new h.Credential(he(e))))}})({tx:i,txBytes:a,provider:s,vm:n,utxos:r});return oe({tx:i,provider:s,credentials:o,utxos:r})},{parseBech32:ye,format:we}=h.utils,{publicKeyBytesToAddress:be}=h.secp256k1;class Ae{constructor(e,t,s){this.baseUrl=e,this.context=t,this.fetchOptions=s}getContext(){return this.context}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return h.networkIDs.getHRP(this.getNetworkID())}getApiX(){const e=new h.avm.AVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiP(){const e=new h.pvm.PVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApiC(){const e=new h.evm.EVMApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getInfo(){const e=new h.info.InfoApi(this.baseUrl);return this.fetchOptions&&e.setFetchOptions(this.fetchOptions),e}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,s){const r=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(r,"hex"),i=be(a);return we(s,this.getHrp(),i)}getAddressFromBuffer(e,t){return we(t,this.getHrp(),e)}formatAddress(e,t){const[,s]=ye(e);return we(t,this.getHrp(),s)}getApiByVM(e){switch(e){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(e){switch(e){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(e){const t=e.unsignedTx.getVM(),s=ge(e);return this.issueTxHex(s,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,s=6e4){const r=this.getApiByVM(t),n=Date.now();return new Promise(((t,a)=>{const i=async()=>{let o;switch(s&&n+s<Date.now()&&a(new Error("Timeout")),o=r instanceof h.evm.EVMApi?await r.getAtomicTxStatus(e):await r.getTxStatus({txID:e,includeReason:!0}),o.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{i()}),1e3)}};i()}))}}const Te={weights:h.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},Ie={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:Te},Se={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:Te},Pe={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:Te};class Be extends Ae{constructor(e,t,s){super(e,t,s)}static async fromBaseURL(e){const t=await h.Context.getContextFromURI(e);try{return new Be(e,t)}catch{return new Be(e,t)}}static getDefaultMainnetProvider(){return new Be(A.AVALANCHE_XP_NETWORK.rpcUrl,Ie)}static getDefaultFujiProvider(){return new Be(A.AVALANCHE_XP_TEST_NETWORK.rpcUrl,Se)}static getDefaultDevnetProvider(){return new Be(A.AVALANCHE_P_DEV_NETWORK.rpcUrl,Pe)}}const{bytesCompare:Ce,parseBech32:ke}=h.utils,Ee=(e,t)=>"P"===t,De=(e,t,s)=>{const r=Ee(0,t)?e.amount:e.asset?.amount;return new h.TransferOutput(new h.BigIntPr(BigInt(r)),h.OutputOwners.fromNative(e.addresses.map((e=>ke(e)[1])).sort(Ce),BigInt(s??0),e.threshold))},Me=(e,t)=>{const s=((e,t)=>{const s=t===b.Network.FUJI,{cBlockchainID:r,xBlockchainID:n,pBlockchainID:a}=s?Se:Ie;if(r===e)return"C";if(n===e)return"X";if(a===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),r=Ee(0,s)?e.txHash:e.creationTxHash,n=Ee(0,s)?e.assetId:e.asset?.assetId;return new h.Utxo(h.avaxSerial.UTXOID.fromNative(r,Number(e.outputIndex)),h.Id.fromString(n),((e,t)=>Ee(0,t)?e.stakeableLocktime?new h.pvmSerial.StakeableLockOut(new h.BigIntPr(BigInt(e.stakeableLocktime??0)),De(e,t,e.platformLocktime??0)):De(e,t,e.platformLocktime):De(e,t,e.locktime))(e,s))},{unpackWithManager:Ve,parse:Ke,bufferToHex:Oe,AddressMaps:Ue,AddressMap:Ne}=h.utils;function _e(e){const t=Buffer.from(e,"utf8"),s=Buffer.alloc(4);s.writeUInt32BE(t.length,0);const r=Buffer.from(`Avalanche Signed Message:\n${s}${e}`,"utf8");return T("sha256").update(r).digest()}const Le=1024,Xe=1024;async function Fe(e,t,s){const r=e.slice(0,Le),n=e.slice(Le),a=await He(t,{...s,addresses:r});if(n.length){const r=await Fe(n,t,{...s,addresses:e});return a.merge(r)}return a}async function He(e,t){if(t.addresses.length>Le)throw new Error(`Can not get UTXOs for more than ${Le} addresses.`);const{endIndex:s,utxos:r}=await e.getUTXOs(t),n=new h.utils.UtxoSet(r);if(r.length>=Xe){const r=await He(e,{...t,startIndex:s});return n.merge(r)}return n}function qe(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:Re}=h.utils;async function $e(e,t){const s=e.slice(0,256),r=e.slice(256),n=await t.getStake({addresses:s});if(r.length){const e=await $e(r,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:We,hexToBuffer:je,unpackWithManager:Je}=h.utils;function ze(e,t=!0){try{if(t){const[t]=h.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else h.utils.parseBech32(e);return!0}catch(e){return!1}}const Ge=e=>{if([Ie.xBlockchainID,Se.xBlockchainID,Pe.xBlockchainID].includes(e))return"AVM";if([Ie.pBlockchainID,Se.pBlockchainID,Pe.pBlockchainID].includes(e))return"PVM";if([Ie.cBlockchainID,Se.cBlockchainID,Pe.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},Ye=(e,t)=>e.reduce(((e,s)=>s.assetId.toString()!==t?e:e+s.output.amount()),BigInt(0)),Qe=(e,t)=>e.reduce(((e,s)=>s.assetId.toString()!==t?e:e+s.input.amount()),BigInt(0));var Ze={parseCreateSubnetTx:e=>h.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:s})=>({type:re.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(s.getHrp())}`)),...t}):null,parseCreateChainTx:e=>h.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:re.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>h.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:re.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>h.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:re.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>h.pvmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.evmSerial.isImportTx(e)?h.evmSerial.isImportTx(e)?({feeData:t,assetId:s})=>({type:re.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:Qe(e.importedInputs,s),...t}):({feeData:t,assetId:s})=>({type:re.Import,chain:e.getVM(),source:Ge(e.sourceChain.value()),amount:Qe(e.ins,s),...t}):null,parseExportTx:e=>h.pvmSerial.isExportTx(e)||h.avmSerial.isExportTx(e)||h.evmSerial.isExportTx(e)?h.evmSerial.isExportTx(e)?({feeData:t,assetId:s})=>({type:re.Export,chain:e.getVM(),destination:Ge(e.destinationChain.toString()),amount:Ye(e.exportedOutputs,s),...t}):({feeData:t,assetId:s})=>({type:re.Export,chain:e.getVM(),destination:Ge(e.destination.value()),amount:Ye(e.outs,s),...t}):null,parseBaseTx:e=>h.avmSerial.isAvmBaseTx(e)||h.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:s,provider:r})=>{const n=e.baseTx,a=await(async(e,t)=>{const s=e.baseTx,r=new Set;if(s.outputs.forEach((e=>{r.add(e.assetId.value())})),h.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...r.values()].map((e=>t.getApiX().getAssetDescription(e))));return s.outputs.reduce(((s,n)=>{if(n.output instanceof h.TransferOutput){const a=n.assetId.value(),i=[...r.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...s,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return s}),[])}return s.outputs.reduce(((e,s)=>{if(s.output instanceof h.TransferOutput){const r=s.assetId.value(),n=s.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:r,amount:s.output.amount(),locktime:s.output.getLocktime(),threshold:BigInt(s.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===r}]}return e}),[])})(e,r),i=qe(),o=a.filter((e=>!(1===e.owners.length&&e.owners[0]===s&&e.locktime<=i)));return{type:re.Base,chain:e.getVM(),outputs:o,memo:I(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!h.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,s;return h.pvmSerial.isSigner(e.signer)&&(s=h.utils.bufferToHex(e.signer.proof.publicKey),t=h.utils.bufferToHex(e.signer.proof.signature)),({feeData:r})=>({type:re.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:s,signature:t,...r})},parseAddPermissionlessDelegatorTx:e=>h.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:re.AddPermissionlessDelegator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),stakeOuts:e.stake,delegatorRewardsOwner:e.getDelegatorRewardsOwner(),...t}):null,parseTransferSubnetOwnershipTx:e=>h.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:s})=>({type:re.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(s.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>h.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:s})=>{const r=s.getHrp(),n=e=>`P-${e.toString(r)}`;return{type:re.ConvertSubnetToL1,chain:e.getVM(),managerAddress:`0x${e.address.toString("hex")}`,validators:e.validators.map((e=>({nodeId:h.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>h.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:re.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>h.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:re.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>h.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:re.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>h.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:re.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:et,getOutputAmounts:tt,getInputAmounts:st,validateBurnedAmount:rt}=h.utils;function nt(e,t,s){return[...e].sort(((e,r)=>{for(let n=0;n<t.length;n++){const a=t[n];if(e[a]>r[a])return"asc"===s?1:-1;if(e[a]<r[a])return"asc"===s?-1:1}return 0}))}function at(e){const t=qe(),s=e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),r=s.filter((e=>e.stakeableLocktime<=t)),n=s.filter((e=>e.stakeableLocktime>t)),a=nt(r,["amount"],"desc"),i=nt(n,["stakeableLocktime","amount"],"desc"),[o,...d]=a;return[...o?[o]:[],...i,...d].map((e=>e.utxo))}function it(e,t){return nt(e.map((e=>({utxo:e,...h.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const ot=e=>it(e,!0),dt=e=>it(e,!1);const{getUtxoInfo:ut}=h.utils;var ct=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(ct||{});const lt="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",pt="11111111111111111111111111111111LpoYY",ht=(e,t)=>e.reduce(((e,t)=>e+ut(t).amount),BigInt(0))-t,gt={BaseP:{sortFunction:ot,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext();return e.baseTX({utxoSet:new h.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[r.avaxAssetID]:ht(t,r.baseTxFee)},feeState:s})}},ConsolidateP:{sortFunction:dt,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext();return e.consolidateP({utxoSet:new h.utils.UtxoSet(t),amount:ht(t,r.baseTxFee),feeState:s})}},AddPermissionlessValidator:{sortFunction:at,unsignedTxBuilder:(e,t,s)=>e.addPermissionlessValidator({utxoSet:new h.utils.UtxoSet(t),nodeId:lt,start:qe(),end:qe()+BigInt(1e3),weight:ht(t,e.getProvider().getContext().baseTxFee),subnetId:pt,shares:5,feeState:s,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(h.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(h.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:at,unsignedTxBuilder:(e,t,s)=>e.addPermissionlessDelegator({utxoSet:new h.utils.UtxoSet(t),nodeId:lt,start:qe(),end:qe()+BigInt(1e3),weight:ht(t,e.getProvider().getContext().baseTxFee),subnetId:pt,feeState:s})},ExportP:{sortFunction:ot,unsignedTxBuilder:(e,t,s)=>{const r=e.getProvider().getContext(),n=function({numberIns:e=1},t){const s=h.Common.createDimensions({bandwidth:161*e+254,dbRead:e,dbWrite:2+e,compute:200*e});return h.Common.dimensionsToGas(s,t)}({numberIns:t.length},r.platformFeeConfig.weights),a=s?n*s.price:r.baseTxFee;return e.exportP({amount:ht(t,a),utxoSet:new h.utils.UtxoSet(t),destination:"X",feeState:s})}},ImportP:{sortFunction:ot,unsignedTxBuilder:(e,t,s)=>e.importP({utxoSet:new h.utils.UtxoSet(t),sourceChain:"X",feeState:s})}};function mt(e){return S.validateString(e,!0)&&6===e.split("/").length}function ft(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:xt,hexToBuffer:vt}=h.utils;class yt{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Fe(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return $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 s=this.provider.getApi(e),r=this.provider.getChainID(t);return Fe(this.getAddresses(e),s,{sourceChain:r,addresses:[]})}exportX(e,t,s,r){r=r||this.getCurrentAddress(s);const n=xt(r)[2],a=this.provider.getAvaxID(),i=h.TransferableOutput.fromNative(a,e,[n]),o=it(t.getUTXOs(),!0),d=this.provider.getChainID(s),u=this.getAddresses("X").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("X"))[2];return h.avm.newExportTx(this.provider.getContext(),d,u,o,[i],{threshold:1,changeAddresses:[c]})}importP({utxoSet:e,sourceChain:t,toAddress:s,threshold:r,feeState:n,locktime:a}){const i=this.provider.getChainID(t),o=this.getAddresses("P").map((e=>xt(e)[2]));xt(this.getChangeAddress("P"))[2],s=s||this.getCurrentAddress("P");const d=xt(s)[2],u=e.getUTXOs();return ft(n),h.pvm.newImportTx({fromAddressesBytes:o,utxos:u,toAddressesBytes:[d],sourceChainId:i,threshold:r,feeState:n,locktime:a},this.provider.getContext())}importX(e,t,s){const r=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>xt(e)[2])),a=xt(this.getChangeAddress("X"))[2];s=s||this.getCurrentAddress("X");const i=xt(s)[2];return h.avm.newImportTx(this.provider.getContext(),r,e.getUTXOs(),[i],n,{changeAddresses:[a]})}importC(e,s,r,n,a){const i=this.provider.getChainID(s),o=this.getAddresses("C").map((e=>xt(e)[2]));a=a||this.getAddressEVM();const d=Buffer.from(t.strip0x(a),"hex");return h.evm.newImportTxFromBaseFee(this.provider.getContext(),d,o,e.getUTXOs(),i,r,n)}exportC(e,t,s,r,n){const a=vt(this.getAddressEVM()),i=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const o=xt(n)[2],d=r/BigInt(1e9);return h.evm.newExportTxFromBaseFee(this.provider.getContext(),d,e,i,a,[o],s)}exportP({amount:e,utxoSet:t,destination:s,feeState:r,toAddress:n}){n=n||this.getCurrentAddress(s);const a=xt(n)[2],i=this.provider.getAvaxID(),o=h.TransferableOutput.fromNative(i,e,[a]),d=it(t.getUTXOs(),!0),u=this.provider.getChainID(s),c=this.getAddresses("P").map((e=>xt(e)[2])),l=xt(this.getChangeAddress("P"))[2];return ft(r),h.pvm.newExportTx({changeAddressesBytes:[l],fromAddressesBytes:c,utxos:d,outputs:[o],destinationChainId:u,feeState:r},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:s,toAddress:r,options:n}){const a=dt(e.getUTXOs());r=r??this.getCurrentAddress("P");const i=xt(r)[2],o=this.provider.getContext(),d=[h.TransferableOutput.fromNative(o.avaxAssetID,t,[i])],u=this.getAddresses("P").map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c];return ft(s),h.pvm.newBaseTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:a,outputs:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:s},o)}baseTX({utxoSet:e,chain:t,toAddress:s,amountsPerAsset:r,feeState:n,options:a,fromAddresses:i}){const[o,d,u]=xt(s);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${s}"`);const c=Object.entries(r).map((([e,t])=>h.TransferableOutput.fromNative(e,t,[u]))),l=it(e.getUTXOs(),!0),p=(i??this.getAddresses(t)).map((e=>xt(e)[2])),g=xt(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return"X"===t?h.avm.newBaseTx(this.provider.getContext(),p,l,c,a):(ft(n),h.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:p,utxos:l,outputs:c,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:s,subnetAuth:r,feeState:n,address:a,validators:i,options:o,fromAddresses:d}){const u=(d??this.getAddresses("P")).map((e=>xt(e)[2])),c=xt(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c],p=i.map((({nodeId:e,pubKey:t,signature:s,balance:r,weight:n,deactivationOwner:a,remainingBalanceOwner:i})=>{const o=new h.pvmSerial.ProofOfPossession(Uint8Array.from(h.utils.hexToBuffer(t)),Uint8Array.from(h.utils.hexToBuffer(s))),d=h.PChainOwner.fromNative(i.addresses.map((e=>xt(e)[2])),i.threshold??1),u=h.PChainOwner.fromNative(a.addresses.map((e=>xt(e)[2])),a.threshold??1);return h.L1Validator.fromNative(e,n,r,o,d,u)}));return h.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:p,fromAddressesBytes:u,address:xt(a)[2],chainId:t,subnetId:s,subnetAuth:r,feeState:n,utxos:it(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:s,message:r,feeState:n,fromAddresses:a,options:i}){const o=(a??this.getAddresses("P")).map((e=>xt(e)[2])),d=xt(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[d];return h.pvm.newRegisterL1ValidatorTx({utxos:it(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(h.utils.hexToBuffer(s)),changeAddressesBytes:u,feeState:n,fromAddressesBytes:o,memo:i?.memo,message:Uint8Array.from(h.utils.hexToBuffer(r)),minIssuanceTime:i?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:s,options:r,fromAddresses:n}){const a=(n??this.getAddresses("P")).map((e=>xt(e)[2])),i=xt(this.getChangeAddress("P"))[2],o=r?.changeAddresses??[i];return h.pvm.newSetL1ValidatorWeightTx({utxos:it(e.getUTXOs(),!0),changeAddressesBytes:o,feeState:t,fromAddressesBytes:a,memo:r?.memo,message:Uint8Array.from(h.utils.hexToBuffer(s)),minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:s,fromAddresses:r,disableAuth:n,validationId:a}){const i=(r??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return h.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:a,utxos:it(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:s,fromAddresses:r,balance:n,validationId:a}){const i=(r??this.getAddresses("P")).map((e=>xt(e)[2])),o=xt(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return h.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:a,utxos:it(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:s,vmID:r,fxIds:n,genesisData:a,subnetAuth:i,feeState:o,options:d,fromAddresses:u}){const c=it(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],g=d?.changeAddresses??[p];return ft(o),h.pvm.newCreateChainTx({chainName:s,feeState:o,fromAddressesBytes:l,fxIds:n,genesisData:a,subnetAuth:i,subnetId:t,utxos:c,vmId:r,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:s,fromAddresses:r,options:n,threshold:a,locktime:i}){const o=it(e.getUTXOs(),!0),d=(r??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=n?.changeAddresses??[u],l=t.map((e=>xt(e)[2]));return ft(s),h.pvm.newCreateSubnetTx({fromAddressesBytes:d,changeAddressesBytes:c,utxos:o,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:s,threshold:a,locktime:i,subnetOwners:l},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:s,end:r,weight:n,subnetId:a,subnetAuth:i,feeState:o,fromAddresses:d,options:u}){const c=it(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>xt(e)[2])),p=xt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[p];return ft(o),h.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:l,utxos:c,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,nodeId:t,start:s,end:r,weight:n,subnetId:a,subnetAuth:i,feeState:o},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:s,end:r,weight:n,subnetId:a,shares:i,feeState:o,fromAddresses:d,rewardAddresses:u,delegatorRewardAddresses:c,publicKey:l,signature:p,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=at(e.getUTXOs()),y=(d??this.getAddresses("P")).map((e=>xt(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),b=(c??[this.getCurrentAddress("P")]).map((e=>xt(e)[2]));if(!(a!==h.networkIDs.PrimaryNetworkID.toString()||l&&p))throw new Error("Must provide public key and signature for primary subnet.");const A=xt(this.getChangeAddress("P"))[2],T=g?.changeAddresses??[A];return ft(o),h.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:y,delegatorRewardsOwner:b,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:T,nodeId:t,start:s,end:r,weight:n,subnetId:a,shares:i,feeState:o,publicKey:l,rewardAddresses:w,signature:p,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:s,end:r,weight:n,subnetId:a,fromAddresses:i,rewardAddresses:o,options:d,locktime:u,feeState:c,threshold:l,stakingAssetId:p}){const g=at(e.getUTXOs()),m=(i??this.getAddresses("P")).map((e=>xt(e)[2])),f=(o??[this.getCurrentAddress("P")]).map((e=>xt(e)[2])),x=xt(this.getChangeAddress("P"))[2],v=d?.changeAddresses??[x];return ft(c),h.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:d?.minIssuanceTime,memo:d?.memo,changeAddressesBytes:v,nodeId:t,start:s,end:r,weight:n,subnetId:a,rewardAddresses:f,locktime:u,stakingAssetId:p,threshold:l,feeState:c},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:s,subnetAuth:r,fromAddresses:n,feeState:a,options:i}){const o=it(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>xt(e)[2])),u=xt(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[u];return ft(a),h.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:c,fromAddressesBytes:d,utxos:o,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:t,subnetId:s,subnetAuth:r,feeState:a},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:s,subnetOwners:r,feeState:n,fromAddresses:a,options:i,threshold:o,locktime:d}){const u=it(e.getUTXOs(),!0),c=(a??this.getAddresses("P")).map((e=>xt(e)[2])),l=xt(this.getChangeAddress("P"))[2],p=i?.changeAddresses??[l],g=r.map((e=>xt(e)[2]));return ft(n),h.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:p,fromAddressesBytes:c,utxos:u,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:t,subnetAuth:s,subnetOwners:g,feeState:n,threshold:o,locktime:d},this.provider.getContext())}}class wt extends yt{constructor(e,t,s){if(super(s),this.pubkeyXP=e,this.pubkeyC=t,33!==t.length||33!==e.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(e,s,r){const a=t.strip0x(n.SigningKey.computePublicKey(e,!0)),i=t.strip0x(n.SigningKey.computePublicKey(s,!0)),o=Buffer.from(a,"hex"),d=Buffer.from(i,"hex");return new wt(o,d,r)}static fromMnemonic(e,t,s,r){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!mt(s)||!mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=u.mnemonicToSeedSync(e),a=m.fromSeed(n),i=a.derivePath(s),o=a.derivePath(t);return wt.fromPublicKey(o.publicKey,i.publicKey,r)}getAddress(e){const t="C"===e?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(t,e)}getAddressEVM(){return n.computeAddress(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(e){return[this.getAddress(e)]}getChangeAddress(e){return this.getAddress(e)}getCurrentAddress(e){return this.getAddress(e)}}const bt={type:"zondax",getApp:e=>new P(e),async getVersion(e){const t=this.getApp(e);return(await t.getAppInfo()).appVersion},async getAddress(e,t,s={show:!1,hrp:"avax"}){const r=this.getApp(e);return{publicKey:(await r.getAddressAndPubKey(t.toString(),s.show,s.hrp)).publicKey}},async getXPUB(e,t){const s=this.getApp(e),r=await s.getExtendedPubKey(t,!1);return{pubKey:r.publicKey,chainCode:r.chain_code}},async signHash(e,t,s,r){const n=this.getApp(e),a=r.map((e=>e.toString(!0))),i=await n.signHash(s.toString(),a,t),o=i.signatures||new Map;return{hash:i.hash||Buffer.from(""),signatures:o}},async signTx(e,t,s,r,n){const a=this.getApp(e),i=r.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await a.sign(s.toString(),i,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function At(e){return!(await bt.getVersion(e)>="0.6.0")}const{parse:Tt}=h.utils;class It extends yt{constructor(e,t,s){super(s),this.avmXpub=e,this.accountNode=m.fromBase58(e),this.evmWallet=new wt(t,t,s)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=u.mnemonicToSeedSync(e),r=m.fromSeed(s),n=r.derivePath("m/44'/9000'/0'").neutered(),a=r.derivePath(R(0,q.BIP44,"EVM")).neutered();return new It(n.toBase58(),a.publicKey,t)}setExternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.externalIndex=e}setInternalIndex(e){if(e<0)throw new Error("Index must be >= 0");this.internalIndex=e}getPubKeyAtIndex(e,t=!1){if(e<0)throw new Error("Index must be >= 0");const s=`${t?1:0}/${e}`,r=this.pubkeyCache[s];if(r)return r;const{publicKey:n}=this.accountNode.derivePath(s);return this.pubkeyCache[s]=n,n}getAddressAtIndex(e,t=!1,s){const r=this.getPubKeyAtIndex(e,t);return this.provider.getAddress(r,s)}getExternalAddresses(e){const t=[];for(let s=0;s<=this.externalIndex;s++)t.push(this.getAddressAtIndex(s,!1,e));return t}getInternalAddresses(e){const t=[];for(let s=0;s<=this.internalIndex;s++)t.push(this.getAddressAtIndex(s,!0,e));return t}getAddresses(e){return"C"===e?[this.getCurrentAddress("C")]:"P"===e?[...this.getExternalAddresses(e)]:[...this.getInternalAddresses(e),...this.getExternalAddresses(e)]}getChangeAddress(e){return"C"===e?this.evmWallet.getAddress("C"):"P"===e?this.getAddressAtIndex(this.externalIndex,!1,"P"):this.getAddressAtIndex(this.internalIndex,!0,e)}getCurrentAddress(e){return"C"===e?this.evmWallet.getAddress("C"):this.getAddressAtIndex(this.externalIndex,!1,e)}incrementIndex(e){e?this.externalIndex++:this.internalIndex++}getAddressEVM(){return this.evmWallet.getAddressEVM()}getActiveIndices(){return{external:this.externalIndex,internal:this.internalIndex}}getInternalRawAddresses(){return this.getInternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(Tt(e)[2])))}getRawAddressC(){return Buffer.from(Tt(this.getCurrentAddress("C"))[2])}}const{isTransferOut:St,isStakeableLockOut:Pt}=h.utils;function Bt(e){const t=e.output;return St(t)||Pt(t)?t.getOwners():[]}function Ct(e){const t=e.getTx();return h.avmSerial.isExportTx(t)||h.pvmSerial.isExportTx(t)?new Set(t.outs.map(Bt).flat()):h.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(Bt).flat()):new Set((t.baseTx?.outputs??[]).map(Bt).flat())}const{parse:kt}=h.utils;class Et extends It{constructor(e,t,s){super(e,t,s)}getAdditionalAddressesByIndices(e,t,s){return"C"===s?[]:e.map((e=>{const r=this.getAddressAtIndex(e,t,s),[,,n]=kt(r);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,s){if(await At(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const r=O(e),a=await bt.getXPUB(e,Et.getAccountPath("X")),i=m.fromPublicKey(a.pubKey,a.chainCode),o=R(0,q.BIP44,"EVM"),d=await r.getAddress(o,!1),u=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),c=Buffer.from(t.strip0x(u),"hex");return new Et(i.toBase58(),c,s)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,s){const r=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...r,...s??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:s,internalIndices:r}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(s??[],!1,i),u=this.getAdditionalAddressesByIndices(r??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>S.fromString(e))),l=[...Ct(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>S.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:p})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],s=S.fromString(Et.getAccountPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,s,e.signers,t)).signatures.values()]}}const{strip0x:Dt}=h.utils;class Mt extends It{constructor(e,t,s){const r=m.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(Dt(a.compressedPublicKey),"hex");super(r.toBase58(),i,s),this.evmPrivKey=t,this.accountNode=m.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const s=u.mnemonicToSeedSync(e),r=m.fromSeed(s),n=r.derivePath("m/44'/9000'/0'"),a=r.derivePath(R(0,q.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new Mt(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const s=this.accountNode.derivePath(`0/${e}`);if(!s.privateKey)throw new Error("Unable to get private key.");t.push(s.privateKey)}const s=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const s=this.accountNode.derivePath(`0/${t}`);if(!s.privateKey)throw new Error("Unable to get private key.");e.push(s.privateKey)}return e}),[]);return[...t,...s]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const s=this.accountNode.derivePath(`1/${e}`);if(!s.privateKey)throw new Error("Unable to get private key.");t.push(s.privateKey)}const s=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const s=this.accountNode.derivePath(`1/${t}`);if(!s.privateKey)throw new Error("Unable to get private key.");e.push(s.privateKey)}return e}),[]);return[...t,...s]}getSigningKeys(e){const{tx:t,externalIndices:s,internalIndices:r}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(r),...this.getExternalPrivateKeys(s)]:"PVM"===n?this.getExternalPrivateKeys(s):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:Vt,sign:Kt,signHash:Ot}=h.secp256k1,{addChecksum:Ut}=h.utils;class Nt extends wt{privKeyXP;privKeyC;constructor(e,t,s){super(Buffer.from(Vt(e)),Buffer.from(Vt(t)),s),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,s,r){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!mt(s)||!mt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=u.mnemonicToSeedSync(e),a=m.fromSeed(n),i=a.derivePath(t),o=a.derivePath(s);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Nt(i.privateKey,o.privateKey,r)}async signMessage(e){const t=_e(e.message),s=this.getSigningKey(e.chain);return Buffer.from(Ut(await Ot(t,s)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await h.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await Kt(e.buffer,t))]}}const{strip0x:_t}=h.utils;class Lt extends wt{constructor(e,t,s,r,a){const i=h.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),o=h.utils.strip0x(n.SigningKey.computePublicKey(s,!0));if(super(Buffer.from(i,"hex"),Buffer.from(o,"hex"),a),this.pathXP=t,this.pathC=r,!mt(t)||!mt(r))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,s,a){if(await At(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!mt(t)||!mt(s))throw new Error("Invalid path configuration.");const i=new r(e),o=await i.getAddress(s,!1),d=await i.getAddress(t,!1),u=Buffer.from(_t(o.publicKey),"hex"),c=Buffer.from(_t(d.publicKey),"hex"),l=Buffer.from(_t(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(_t(n.SigningKey.computePublicKey(c,!0)),"hex");return new Lt(p,t,l,s,a)}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=S.fromString(this.getAccountPath(e.chain)),s=S.fromString(this.getPartialSignerPath(e.chain)),r=_e(e.message),n=(await bt.signHash(e.transport,r,t,[s])).signatures.get(s.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,s=t.getVM(),r=Buffer.from(t.toBytes()),n="EVM"===s?"C":"X";return(await this.signTxBuffer({buffer:r,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=S.fromString(this.getAccountPath(e.chain)),s=S.fromString(this.getPartialSignerPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,t,[s],[s])).signatures.values()]}}const{parse:Xt}=h.utils;var Ft=Object.freeze({__proto__:null,AbstractProvider:Ae,AddressWallet:class extends yt{constructor(e,t,s,r,a){if(super(a),this.addressC=e,this.addressCoreEth=t,this.xpAddresses=s,this.xpChangeAddress=r,s.length<1)throw new Error("Must have at least 1 xp address.");if(!n.isAddress(e))throw new Error("Not a valid C-Chain (EVM) address");if(s.some((e=>!ze(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!ze(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(r)}setChangeAddress(e){if(!ze(e,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=e}getAddressEVM(){return this.addressC}getAddresses(e){return("C"===e?[this.addressCoreEth]:this.xpAddresses).map((t=>this.provider.formatAddress(t,e)))}getChangeAddress(e){const t="C"===e?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(t,e)}getCurrentAddress(e){const t="C"===e?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(t,e)}},DevnetContext:Pe,FujiContext:Se,JsonRpcProvider:Be,LedgerSigner:Lt,LedgerWallet:Et,MainnetContext:Ie,MnemonicWallet:Mt,MnemonicWalletVoid:It,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,s){this.activeAccountIndex=e,this.provider=t,s&&(this.accountNode=m.fromBase58(s))}accountNode;reSerializeTx(e,t){return e instanceof h.EVMUnsignedTx||"C"===t?h.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):h.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:s}=this.accountNode.derivePath(e),r=this.provider.getAddress(s,t);return Buffer.from(Xt(r)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:s,internalIndices:r}=e,n=this.getChainAlias(t),a=`0/${this.activeAccountIndex}`,i=new Map;if("C"===n||!this.accountNode)return i;const o=(s??[]).map((e=>`0/${e}`)),d=(r??[]).map((e=>`1/${e}`)),u=[a,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&i.set(t,e)}return i}getAddressBipPaths(e,t){return 0===t.size?[S.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,s)=>{const r=t.get(Buffer.from(s).toString("hex"));return r&&e.push(S.fromString(r)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),s=this.reSerializeTx(e.tx,t),r=Buffer.from(s.toBytes()),n=this.getAddressPathMap(e),a=this.getAddressBipPaths(s.getAddresses(),n),i=this.getAddressBipPaths([...Ct(s)],n);return(await this.signTxBuffer({buffer:r,chain:t,transport:e.transport,signers:a,change:i})).forEach((e=>{s.addSignature(e)})),s}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],s=S.fromString(this.getAccountPath(e.chain));return[...(await bt.signTx(e.transport,e.buffer,s,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||S.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const s=_e(e.message),r=(await bt.signHash(e.transport,s,S.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!r)throw new Error("Failed to sign message.");return r}},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 s=u.mnemonicToSeedSync(e),r=m.fromSeed(s);this.accountNodeXP=r.derivePath("m/44'/9000'/0'");const n=r.derivePath(R(t,q.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,s)=>{const r=this.accountNodeXP.derivePath(`${t?1:0}/${s}`);if(!r.privateKey)throw new Error("Unable to get private key.");return e.push(r.privateKey),e}),[])}getSigningKeys(e,t,s){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const r=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!r.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(s,!0);return[r.privateKey,...n,...e]}if("PVM"===e)return[r.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:s,internalIndices:r}=e,n=t.getVM(),a=this.getSigningKeys(n,s,r);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await h.addTxSignatures({unsignedTx:t,privateKeys:a}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const s=_e(e.message),r=await h.secp256k1.signHash(s,t.privateKey);return Buffer.from(r)}},SizeSupportedTx:ct,StaticSigner:Nt,TxType:re,WalletAbstract:yt,WalletVoid:wt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:s,provider:r,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await ve({transactionHex:e,chainAlias:s,provider:r,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const i=a.getCredentials(),o=a.getSigIndices().reduce(((e,t,s)=>{const r=t.map((e=>{const t=i[s]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${s}, ${e}]`);return t}));return e.push(new h.Credential(r)),e}),[]),d=new h.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,o);return{signedTxHex:ge(new h.avaxSerial.SignedTx(a.getTx(),o)),hasAllSignatures:d.hasAllSignatures()}},convertGlacierUtxo:Me,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:s,credentials:r,utxos:n})=>{const a=Ve(s,e),i=Ke(t)[2],o=Oe(i);if(h.evmSerial.isExportTx(a))return new h.EVMUnsignedTx(a,[],new Ue([Ne.fromJSON([[o,0]])]),r);if(h.evmSerial.isImportTx(a)){const e=Ue.fromTransferableInputs(a.importedInputs,n,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new h.UnsignedTx(a,n,e,r)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:oe,digestMessage:_e,emptySignature:pe,getAddressFromXpub:function(e,t,s,r,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=m.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return s.getAddress(i,r)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return m.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const s=e.getAssetDict()[t],r={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!s)return r;const n=s.getUTXOs(),a=qe();return n.forEach((e=>{const t=Re(e);r[t.threshold>1?"multisig":t.locktime>a?"locked":t.stakeableLocktime>a?"lockedStakeable":"available"]+=t.amount})),r.total=r.locked+r.lockedStakeable+r.multisig+r.available,r},getLedgerProvider:async function(e){return bt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:s,limit:r=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=gt[s],o=qe(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:r}=ut(e);return t<o&&(r<o||("AddPermissionlessDelegator"===s||"AddPermissionlessValidator"===s))}))),u=function(e,t,s){let r=0,n=e.length-1;if(t(e)<=s)return n;let a=-1;for(;r<=n;){const i=Math.floor((r+n)/2);t(e.slice(0,i+1))<=s?(a=i,r=i+1):n=i-1}return a}(d,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*ut(t).threshold)),0);return 6+e.toBytes().length+t}(i(e,t,n))}catch(e){return console.log("Unable to estimate size of utxos",{e:e,utxos:t.map(ut)}),r+1}}),r);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:He,getPchainUnixNow:async function(e){const t=await e.getApiP().getTimestamp(),s=new Date(t.timestamp),r=Math.floor(s.getTime()/1e3);return BigInt(r)},getStakeForAddresses:$e,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,s={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{s[h.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),s.total=s.lockedStaked+s.unlockedStaked,s},getUTXOsForAddresses:Fe,getUnixNow:qe,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:s,url:r,token:n,headers:a})=>{const i=ne(t),o=je(e),d=Je(i,o);if(h.evmSerial.isExportTx(d))return[];const u=(e=>{if(h.evmSerial.isImportTx(e)||h.avmSerial.isImportTx(e)||h.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case h.EVM:return b.BlockchainId.C_CHAIN;case h.AVM:return b.BlockchainId.X_CHAIN;case h.PVM:return b.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(d),c=We(d),l=new b.Glacier({BASE:r,TOKEN:n,HEADERS:a}),p=[...new Set(c.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(p.map((e=>l.primaryNetworkTransactions.getTxByHash({blockchainId:u,network:s,txHash:e}))));return c.reduce(((e,t)=>{const r=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!r)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=r.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=Me(n,s);return e.push(a),e}),[])},getVmByChainAlias:ne,getXpubFromMnemonic:function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=u.mnemonicToSeedSync(e);return m.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:ze,isConvertSubnetToL1Tx:function(e){return"convert_subnet_to_l1"===e.type},isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isDisableL1ValidatorTx:function(e){return"disable_l1_validator"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isIncreaseL1ValidatorBalance:function(e){return"increase_l1_validator_balance"===e.type},isObsidianApp:At,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,s,{feeTolerance:r=50,baseFee:n}={}){try{const a=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(Ze)){const s=t(e);if(null!==s)return s}throw new Error("no parser found for tx")})(i),d=et(i,a),u=tt(i),c=st(i).get(a.avaxAssetID)??BigInt(0),l=d.get(a.avaxAssetID)??BigInt(0),p=u.get(a.avaxAssetID)??BigInt(0);let g=n;void 0===g&&(g=0n,h.evmSerial.isImportExportTx(i)?(g=await t.getApiC().getBaseFee()/BigInt(1e9),0n===g&&(g=1n)):"PVM"===i.vm&&(g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0)))));const{isValid:m,txFee:f}=rt({unsignedTx:e,context:a,burnedAmount:l,baseFee:g,feeTolerance:r});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f,baseFee:g},assetId:a.avaxAssetID,provider:t,currentAddress:s})}catch(e){return{type:re.Unknown}}},populateCredential:he,signedTxToHex:ge,sortUTXOsByAmount:it,sortUTXOsByAmountAscending:dt,sortUTXOsByAmountDescending:ot,sortUTXOsStaking:at,verifyDerivationPath:mt});exports.Avalanche=Ft,exports.BitcoinLedgerWallet=class extends ee{constructor(e,t,s,r,n){super(e,s),this.derivationPath=t,this.transport=r,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const s=function(e){return new v.AppClient(e)}(this.transport),r=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await s.getMasterFingerprint(),i=Q(e,t,n,Buffer.from(a,"hex"),r,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await s.signPsbt(i,o,d),c=Z(i,n,r,this.derivationPath);if(u.forEach((e=>{const[t,s]=e;c.updateInput(t,{partialSig:[{signature:s.signature,pubkey:s.pubkey}]})})),!c.validateSignaturesOfAllInputs())throw new Error("Failed to validate signatures");return c.finalizeAllInputs(),c.extractTransaction()}},exports.BitcoinProvider=class extends k{constructor(e=!0,s,r,n,a){super(),this.isMainnet=e,this.extraParams=a;const i=s?{headers:{"api-key":s}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#i=new t.HttpClient(r||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#o=new t.HttpClient(n||d,i)}#i;#o;async#d(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#o.post("",e,{},this.extraParams))))).flat():this.#o.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#i.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,s){const r=await this.#i.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!r?.length)return{confirmed:[],unconfirmed:[]};const n=r.map(this._parseUtxo),a=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return a(n);return a(await this.getScriptsForUtxos(n,s))}async getAddressFromScript(e){const t=await this.#o.post("",{jsonrpc:"2.0",id:`decode-script-${e}`,method:"decodescript",params:[e]},{},this.extraParams);if(t.result)return t.result.address;throw new Error(`Unable to resolve address for script: ${e}. ${t.error.message}`)}async getScriptsForUtxos(e,t){const[s,r]=e.reduce((([e,t],s)=>s.script?[[...e,s],t]:[e,[...t,s]]),[[],[]]),n=r.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),a=n.length?(await this.#d(n,t)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...s,...r.map(((e,t)=>({...e,script:a[t]?.result?.scriptPubKey.hex})))]}_parseUtxo(e){return{...e,txHash:e.txid,index:e.vout,value:Number(e.value),blockHeight:e.height,script:e.script,confirmations:e.confirmations}}async getBalances(e){const t=await this.#i.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.#o.post("",{jsonrpc:"2.0",id:"nownodes",method:"getblockcount",params:[]},{},this.extraParams)).result}async getFeeRates(e){const t={jsonrpc:"2.0",method:"estimatesmartfee"},s=await this.#d([{...t,id:"1",params:[1]},{...t,id:"2",params:[3]},{...t,id:"3",params:[6]}],e).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(s[0]/1024)||1,medium:Math.ceil(s[1]/1024)||1,low:Math.ceil(s[2]/1024)||1}}getNetwork(){return this.isMainnet?e.networks.bitcoin:e.networks.testnet}async issueRawTx(e){return await this.#o.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#i.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.#i.post(`/api/v2/address/${e}`,{},{},this.extraParams),s=t.txids?.slice(0,25)??[];return await Promise.allSettled(s.map((async t=>{try{const s=await this.#i.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const s=t.vin.filter((t=>t.addresses?.includes(e))),r=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),a=t.vout.filter((t=>!t.addresses?.includes(e))),i=s.reduce(((e,t)=>e+BigInt(t.value)),0n),o=r.reduce(((e,t)=>e+BigInt(t.value)),0n),d=i>o;let u=o-i;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=a.map((e=>e.addresses||[])).flat(),p=d?l:c,h=p.filter(((e,t)=>p.indexOf(e)===t)),g=r.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:h,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,s)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:s=1,pollInterval:r=500}={}){try{return await this.getTransaction(e)}catch(n){if(s>=t)throw n;return await new Promise((e=>setTimeout(e,r))),this.waitForTx(e,{maxAttempts:t,attempt:s+1,pollInterval:r})}}},exports.BitcoinProviderAbstract=k,exports.BitcoinWallet=te,exports.BitcoinWalletAbstract=ee,exports.BitcoinWalletVoid=class extends ee{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.BtcNetworks=se,exports.DerivationPath=q,exports.ETH_ACCOUNT_PATH=H,exports.ETH_COIN_PATH=F,exports.JsonRpcBatchInternal=z,exports.LedgerSigner=Y,exports.SolanaLedgerSigner=class{#u;#c;constructor(e,t){this.#u=L(e,!1),this.#c=t}async signTx(e,t){const s=await U(e,t),{signatures:r,messageBytes:n,...i}=a.compileTransaction(s),o=new d(this.#c),{address:u}=await o.getAddress(this.#u),c=a.address(l.base58.encode(Uint8Array.from(u)));if(!this.#r(c,r))return e;const{signature:p}=await o.signTransaction(this.#u,Buffer.from(n)),h=l.base58.encode(Uint8Array.from(p));return a.assertIsSignature(h),a.getBase64EncodedWireTransaction({...i,messageBytes:n,signatures:{...r,[c]:l.base58.decode(h)}})}#r(e,t){return e in t&&!t[e]}},exports.SolanaSigner=X,exports.addEncodedSigToPsbt=function(e,t,s,r){const n=[{pubkey:t,signature:e}];s.updateInput(r,{partialSig:n})},exports.compileSolanaTx=e=>a.compileTransaction(e),exports.createPSBTV2=Q,exports.createPsbt=E,exports.createTransferTx=V,exports.createWalletPolicy=function(e,t,s,r){const n=new v.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${s}`);return new v.WalletPolicy(r,"wpkh(@0/**)",n.keys)},exports.deserializeTransactionMessage=U,exports.formatAddressForNetworkBech32=function(t,s){const r=e.address.fromBech32(t);return e.address.toBech32(r.data,r.version,s.bech32)},exports.getAddressDerivationPath=R,exports.getAddressFromXPub=function(e,t){const s=G(e,t);return n.computeAddress(`0x${s.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const s=m.fromBase58(e).derivePath(`0/${t}`);if(!s.privateKey)throw new Error("Unable to derive private key.");return s.privateKey},exports.getAddressPublicKeyFromXPub=G,exports.getAppEth=O,exports.getBech32Address=K,exports.getBech32AddressFromXPub=function(e,t,s){return K(G(e,t),s)},exports.getBtcAddressFromPubKey=function(e,s){const r=t.strip0x(n.SigningKey.computePublicKey(e,!0));return K(Buffer.from(r,"hex"),s)},exports.getEvmAddressFromPubKey=function(e){return n.computeAddress(`0x${e.toString("hex")}`)},exports.getLedgerAppInfo=async function(e){const t=await e.send(176,1,0,0),s=t.readUInt8(1),r=t.readUInt8(2+s),n=t.subarray(2,2+s),a=t.subarray(2+s+1,2+s+1+r);return{applicationName:n.toString("ascii"),version:a.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,s){const r=O(e),n=await r.getAddress(s??H,t,!0),a=new g;return a.publicKey=B.Buffer.from(n.publicKey,"hex"),a.chainCode=B.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,s,r){const n=C(e);if(!n)return 0;const{fee:a}=D(t,s,n,r,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,s,r="EVM"){const n=O(e),a=R(t,s,r),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(h.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getSolanaDerivationPath=L,exports.getSolanaProvider=({isTestnet:e,rpcUrl:t})=>{const s=a.createSolanaRpc(e?a.devnet(t):a.mainnet(t));return new Proxy(s,{get:(e,t,s)=>t===N||("then"===t||"catch"===t||"finally"===t?e:Reflect.get(e,t,s))})},exports.getSolanaPublicKeyFromLedger=async(e,t)=>{const s=new d(t),{address:r}=await s.getAddress(L(e,!1));return r},exports.getTransferTxDetails=function(e,t,s,r,n){const a=D(e,t,s,r,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,s){if(!(t>=0&&t%1==0))throw new Error("Account index must be an integer greater than or equal to 0.");return n.HDNodeWallet.fromMnemonic(n.Mnemonic.fromPhrase(e),R(t,s,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!u.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await u.mnemonicToSeed(e);return m.fromSeed(t).derivePath(H).neutered().toBase58()},exports.isERC20Transfer=j,exports.isNativeTxn=W,exports.isSolanaProvider=e=>!(!e||"object"!=typeof e)&&!0===e[N],exports.maybeGetAssociatedTokenAccount=_,exports.omitUndefinedKeys=function(e){return Object.keys(e).reduce(((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t)),{})},exports.onBalanceChange=async(e,t,s,r)=>{const n=new Set(e.map((e=>e.toLowerCase()))),a=new Set(t.map((e=>e.toLowerCase()))),i=async e=>{const t=await s.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&a.has(e.to.toLowerCase())&&j(e,n)?r(e,{type:"erc20",contractAddress:e.to}):W(e,n)&&r(e,{type:"native"})}))},o=await s.on("block",i);return{unsubscribe:()=>o.off("block",i)}},exports.openLedgerApp=async function(e,t){try{return(await e.send(224,216,0,0,Buffer.from(t,"ascii"))).equals(Buffer.from([144,0]))}catch(e){return!1}},exports.psbt2ToPsbt0=Z,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=D,exports.serializeSolanaTx=e=>a.getBase64EncodedWireTransaction(e),exports.transferSol=async({from:e,to:t,amount:s,provider:r})=>{const{value:n}=await r.getLatestBlockhash().send(),o=[i.getTransferSolInstruction({source:a.createNoopSigner(a.address(e)),destination:a.address(t),amount:s})];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:s,amount:r,decimals:n,provider:i})=>{const{address:d}=await _({mint:a.address(s),owner:a.address(e),provider:i}),{address:u,exists:c}=await _({mint:a.address(s),owner:a.address(t),provider:i}),l=[];c||l.push(o.getCreateAssociatedTokenIdempotentInstruction({payer:a.createNoopSigner(a.address(e)),mint:a.address(s),owner:a.address(t),ata:u})),l.push(o.getTransferCheckedInstruction({amount:r,authority:a.createNoopSigner(a.address(e)),decimals:n,mint:a.address(s),destination:u,source:d}));const{value:p}=await i.getLatestBlockhash().send();return a.pipe(a.createTransactionMessage({version:0}),(e=>a.setTransactionMessageLifetimeUsingBlockhash(p,e)),(t=>a.setTransactionMessageFeePayer(a.address(e),t)),(e=>a.appendTransactionMessageInstructions(l,e)))};
package/dist/index.d.ts CHANGED
@@ -2,7 +2,6 @@ import * as bitcoinjs_lib from 'bitcoinjs-lib';
2
2
  import { Network, Psbt, ECPairInterface, Transaction as Transaction$1, networks } from 'bitcoinjs-lib';
3
3
  import Eth from '@ledgerhq/hw-app-eth';
4
4
  import Transport from '@ledgerhq/hw-transport';
5
- import * as ethers from 'ethers';
6
5
  import { Provider, VoidSigner, HDNodeWallet, TransactionResponse, JsonRpcProvider as JsonRpcProvider$1, FetchRequest, Network as Network$1, Contract, AbstractSigner, BytesLike, TransactionRequest, TypedDataDomain, TypedDataField } from 'ethers';
7
6
  import * as _avalabs_avalanchejs from '@avalabs/avalanchejs';
8
7
  import { VM, OutputOwners, TransferableOutput, Common, pvmSerial, Context, avm, pvm, evm, info, avaxSerial, utils, UnsignedTx, EVMUnsignedTx, Utxo, TransferOutput, Credential, Signature } from '@avalabs/avalanchejs';
@@ -775,12 +774,8 @@ declare function isTransferSubnetOwnershipTx(tx: Tx): tx is TransferSubnetOwners
775
774
  declare class AbstractProvider {
776
775
  protected baseUrl: string;
777
776
  protected context: Context.Context;
778
- evmRpc: JsonRpcProvider$1;
779
- constructor(baseUrl: string, context: Context.Context);
780
- /**
781
- * @link https://docs.ethers.io/v5/api/providers/provider/#Provider-getFeeData
782
- */
783
- getEvmFeeData(): Promise<ethers.FeeData>;
777
+ fetchOptions?: RequestInit | undefined;
778
+ constructor(baseUrl: string, context: Context.Context, fetchOptions?: RequestInit | undefined);
784
779
  getContext(): Context.Context;
785
780
  getChainID(chainAlias: ChainIDAlias): string;
786
781
  getNetworkID(): number;
@@ -809,7 +804,7 @@ declare class AbstractProvider {
809
804
  }
810
805
 
811
806
  declare class JsonRpcProvider extends AbstractProvider {
812
- constructor(baseUrl: string, context: Context.Context);
807
+ constructor(baseUrl: string, context: Context.Context, fetchOptions?: RequestInit);
813
808
  static fromBaseURL(url: string): Promise<JsonRpcProvider>;
814
809
  static getDefaultMainnetProvider(): JsonRpcProvider;
815
810
  static getDefaultFujiProvider(): JsonRpcProvider;
@@ -1047,10 +1042,6 @@ declare abstract class WalletAbstract {
1047
1042
  * @param source What is the source chain of the atomic UTXOs
1048
1043
  */
1049
1044
  getAtomicUTXOs(chain: ChainIDAlias, source: ChainIDAlias): Promise<utils.UtxoSet>;
1050
- /**
1051
- * Get the nonce of this wallet's C chain address
1052
- */
1053
- getNonce(): Promise<number>;
1054
1045
  exportX(amount: bigint, utxoSet: utils.UtxoSet, destination: 'P' | 'C', toAddress?: string): Common.UnsignedTx;
1055
1046
  importP({ utxoSet, sourceChain, toAddress, threshold, feeState, locktime, }: ImportP): Common.UnsignedTx;
1056
1047
  importX(utxos: utils.UtxoSet, sourceChain: 'P' | 'C', toAddress?: string): Common.UnsignedTx;
@@ -1655,7 +1646,7 @@ declare function getAssetBalance(utxoSet: utils.UtxoSet, assetID: string): GetAv
1655
1646
  /**
1656
1647
  * Get the current p-chain timestamp in unix
1657
1648
  */
1658
- declare function getPchainUnixNow(isTestnet: boolean): Promise<bigint>;
1649
+ declare function getPchainUnixNow(provider: AbstractProvider): Promise<bigint>;
1659
1650
 
1660
1651
  interface GetStakedAvaxBalanceDict {
1661
1652
  /**
@@ -1,18 +1,12 @@
1
1
  import * as _avalabs_avalanchejs_dist_vms_common from '@avalabs/avalanchejs/dist/vms/common';
2
- import * as ethers from 'ethers';
3
- import { JsonRpcProvider } from 'ethers';
4
2
  import { Context, avm, pvm, evm, info, VM, avaxSerial } from '@avalabs/avalanchejs';
5
3
  import { ChainIDAlias } from '../models.js';
6
4
 
7
5
  declare class AbstractProvider {
8
6
  protected baseUrl: string;
9
7
  protected context: Context.Context;
10
- evmRpc: JsonRpcProvider;
11
- constructor(baseUrl: string, context: Context.Context);
12
- /**
13
- * @link https://docs.ethers.io/v5/api/providers/provider/#Provider-getFeeData
14
- */
15
- getEvmFeeData(): Promise<ethers.FeeData>;
8
+ fetchOptions?: RequestInit | undefined;
9
+ constructor(baseUrl: string, context: Context.Context, fetchOptions?: RequestInit | undefined);
16
10
  getContext(): Context.Context;
17
11
  getChainID(chainAlias: ChainIDAlias): string;
18
12
  getNetworkID(): number;
@@ -1 +1 @@
1
- import{utils as t,secp256k1 as e,networkIDs as s,avm as r,pvm as i,evm as n,info as c}from"@avalabs/avalanchejs";import{strip0x as a}from"@avalabs/core-utils-sdk";import{signedTxToHex as o}from"../utils/signedTxToHex.js";import{JsonRpcProvider as u,SigningKey as h}from"ethers";const{parseBech32:p,format:g}=t,{publicKeyBytesToAddress:A}=e;class x{constructor(t,e){this.baseUrl=t,this.context=e;const s=`${t}/ext/bc/C/rpc`;this.evmRpc=new u(s)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}getChainID(t){switch(t){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 s.getHRP(this.getNetworkID())}getApiX(){return new r.AVMApi(this.baseUrl)}getApiP(){return new i.PVMApi(this.baseUrl)}getApiC(){return new n.EVMApi(this.baseUrl)}getInfo(){return new c.InfoApi(this.baseUrl)}getApi(t){switch(t){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(t,e){const s=a(h.computePublicKey(t,!0)),r=Buffer.from(s,"hex"),i=A(r);return g(e,this.getHrp(),i)}getAddressFromBuffer(t,e){return g(e,this.getHrp(),t)}formatAddress(t,e){const[,s]=p(t);return g(e,this.getHrp(),s)}getApiByVM(t){switch(t){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(t){switch(t){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(t){const e=t.unsignedTx.getVM(),s=o(t);return this.issueTxHex(s,e)}async issueTxHex(t,e){return this.getApiByVM(e).issueTx({tx:t})}async waitForTransaction(t,e,s=6e4){const r=this.getApiByVM(e),i=Date.now();return new Promise(((e,c)=>{const a=async()=>{let o;switch(s&&i+s<Date.now()&&c(new Error("Timeout")),o=r instanceof n.EVMApi?await r.getAtomicTxStatus(t):await r.getTxStatus({txID:t,includeReason:!0}),o.status){case"Accepted":case"Committed":return void e({success:!0});case"Dropped":case"Rejected":return void e({success:!1});default:setTimeout((()=>{a()}),1e3)}};a()}))}}export{x as AbstractProvider};
1
+ import{utils as t,secp256k1 as e,networkIDs as s,avm as i,pvm as r,evm as n,info as c}from"@avalabs/avalanchejs";import{strip0x as o}from"@avalabs/core-utils-sdk";import{signedTxToHex as h}from"../utils/signedTxToHex.js";import{SigningKey as a}from"ethers";const{parseBech32:p,format:u}=t,{publicKeyBytesToAddress:g}=e;class A{constructor(t,e,s){this.baseUrl=t,this.context=e,this.fetchOptions=s}getContext(){return this.context}getChainID(t){switch(t){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 s.getHRP(this.getNetworkID())}getApiX(){const t=new i.AVMApi(this.baseUrl);return this.fetchOptions&&t.setFetchOptions(this.fetchOptions),t}getApiP(){const t=new r.PVMApi(this.baseUrl);return this.fetchOptions&&t.setFetchOptions(this.fetchOptions),t}getApiC(){const t=new n.EVMApi(this.baseUrl);return this.fetchOptions&&t.setFetchOptions(this.fetchOptions),t}getInfo(){const t=new c.InfoApi(this.baseUrl);return this.fetchOptions&&t.setFetchOptions(this.fetchOptions),t}getApi(t){switch(t){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(t,e){const s=o(a.computePublicKey(t,!0)),i=Buffer.from(s,"hex"),r=g(i);return u(e,this.getHrp(),r)}getAddressFromBuffer(t,e){return u(e,this.getHrp(),t)}formatAddress(t,e){const[,s]=p(t);return u(e,this.getHrp(),s)}getApiByVM(t){switch(t){case"AVM":return this.getApiX();case"PVM":return this.getApiP();case"EVM":return this.getApiC()}}getApiByChainID(t){switch(t){case this.context.xBlockchainID:return this.getApiX();case this.context.pBlockchainID:return this.getApiP();case this.context.cBlockchainID:return this.getApiC()}}async issueTx(t){const e=t.unsignedTx.getVM(),s=h(t);return this.issueTxHex(s,e)}async issueTxHex(t,e){return this.getApiByVM(e).issueTx({tx:t})}async waitForTransaction(t,e,s=6e4){const i=this.getApiByVM(e),r=Date.now();return new Promise(((e,c)=>{const o=async()=>{let h;switch(s&&r+s<Date.now()&&c(new Error("Timeout")),h=i instanceof n.EVMApi?await i.getAtomicTxStatus(t):await i.getTxStatus({txID:t,includeReason:!0}),h.status){case"Accepted":case"Committed":return void e({success:!0});case"Dropped":case"Rejected":return void e({success:!1});default:setTimeout((()=>{o()}),1e3)}};o()}))}}export{A as AbstractProvider};
@@ -2,7 +2,7 @@ import { AbstractProvider } from './AbstractProvider.js';
2
2
  import { Context } from '@avalabs/avalanchejs';
3
3
 
4
4
  declare class JsonRpcProvider extends AbstractProvider {
5
- constructor(baseUrl: string, context: Context.Context);
5
+ constructor(baseUrl: string, context: Context.Context, fetchOptions?: RequestInit);
6
6
  static fromBaseURL(url: string): Promise<JsonRpcProvider>;
7
7
  static getDefaultMainnetProvider(): JsonRpcProvider;
8
8
  static getDefaultFujiProvider(): JsonRpcProvider;
@@ -1 +1 @@
1
- import{AbstractProvider as r}from"./AbstractProvider.js";import{Context as t,info as e}from"@avalabs/avalanchejs";import{MainnetContext as a,FujiContext as n,DevnetContext as o}from"./constants.js";import{AVALANCHE_XP_NETWORK as s,AVALANCHE_XP_TEST_NETWORK as c,AVALANCHE_P_DEV_NETWORK as i}from"@avalabs/core-chains-sdk";class p extends r{constructor(r,t){super(r,t)}static async fromBaseURL(r){const a=await t.getContextFromURI(r);try{await new e.InfoApi(r).getUpgradesInfo();return new p(r,a)}catch{return new p(r,a)}}static getDefaultMainnetProvider(){return new p(s.rpcUrl,a)}static getDefaultFujiProvider(){return new p(c.rpcUrl,n)}static getDefaultDevnetProvider(){return new p(i.rpcUrl,o)}}export{p as JsonRpcProvider};
1
+ import{AbstractProvider as r}from"./AbstractProvider.js";import{Context as t}from"@avalabs/avalanchejs";import{MainnetContext as e,FujiContext as a,DevnetContext as n}from"./constants.js";import{AVALANCHE_XP_NETWORK as s,AVALANCHE_XP_TEST_NETWORK as o,AVALANCHE_P_DEV_NETWORK as c}from"@avalabs/core-chains-sdk";class i extends r{constructor(r,t,e){super(r,t,e)}static async fromBaseURL(r){const e=await t.getContextFromURI(r);try{return new i(r,e)}catch{return new i(r,e)}}static getDefaultMainnetProvider(){return new i(s.rpcUrl,e)}static getDefaultFujiProvider(){return new i(o.rpcUrl,a)}static getDefaultDevnetProvider(){return new i(c.rpcUrl,n)}}export{i as JsonRpcProvider};
@@ -1,6 +1,8 @@
1
+ import { AbstractProvider } from '../providers/AbstractProvider.js';
2
+
1
3
  /**
2
4
  * Get the current p-chain timestamp in unix
3
5
  */
4
- declare function getPchainUnixNow(isTestnet: boolean): Promise<bigint>;
6
+ declare function getPchainUnixNow(provider: AbstractProvider): Promise<bigint>;
5
7
 
6
8
  export { getPchainUnixNow };
@@ -1 +1 @@
1
- import{AVALANCHE_XP_TEST_NETWORK as a,AVALANCHE_XP_NETWORK as t}from"@avalabs/core-chains-sdk";import{pvm as e}from"@avalabs/avalanchejs";async function r(r){const i=r?a.rpcUrl:t.rpcUrl,n=await new e.PVMApi(i).getTimestamp(),o=new Date(n.timestamp),m=Math.floor(o.getTime()/1e3);return BigInt(m)}export{r as getPchainUnixNow};
1
+ async function t(t){const e=await t.getApiP().getTimestamp(),a=new Date(e.timestamp),i=Math.floor(a.getTime()/1e3);return BigInt(i)}export{t as getPchainUnixNow};
@@ -1 +1 @@
1
- import{WalletAbstract as s}from"./WalletAbstract.js";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"create-hash";import"bip32";import"@avalabs/avalanchejs";import"../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import"../utils/getUtxosByTxFromGlacier.js";import"bip39";import{isBech32Address as e}from"../utils/isBech32Address.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import"bip32-path";import{isAddress as r}from"ethers";class t extends s{constructor(s,t,a,i,d){if(super(d),this.addressC=s,this.addressCoreEth=t,this.xpAddresses=a,this.xpChangeAddress=i,a.length<1)throw new Error("Must have at least 1 xp address.");if(!r(s))throw new Error("Not a valid C-Chain (EVM) address");if(a.some((s=>!e(s,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!e(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(i)}setChangeAddress(s){if(!e(s,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=s}getAddressEVM(){return this.addressC}getAddresses(s){return("C"===s?[this.addressCoreEth]:this.xpAddresses).map((e=>this.provider.formatAddress(e,s)))}getChangeAddress(s){const e="C"===s?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(e,s)}getCurrentAddress(s){const e="C"===s?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(e,s)}}export{t as AddressWallet};
1
+ import{WalletAbstract as s}from"./WalletAbstract.js";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"create-hash";import"bip32";import"@avalabs/avalanchejs";import"../utils/getAssetBalance.js";import"../utils/getUtxosByTxFromGlacier.js";import"bip39";import{isBech32Address as e}from"../utils/isBech32Address.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import"bip32-path";import{isAddress as r}from"ethers";class t extends s{constructor(s,t,i,a,d){if(super(d),this.addressC=s,this.addressCoreEth=t,this.xpAddresses=i,this.xpChangeAddress=a,i.length<1)throw new Error("Must have at least 1 xp address.");if(!r(s))throw new Error("Not a valid C-Chain (EVM) address");if(i.some((s=>!e(s,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!e(t,!1))throw new Error("Given CoreEth address must be valid avalanche bech32 addresses without the chain alias prefix");this.setChangeAddress(a)}setChangeAddress(s){if(!e(s,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=s}getAddressEVM(){return this.addressC}getAddresses(s){return("C"===s?[this.addressCoreEth]:this.xpAddresses).map((e=>this.provider.formatAddress(e,s)))}getChangeAddress(s){const e="C"===s?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(e,s)}getCurrentAddress(s){const e="C"===s?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(e,s)}}export{t as AddressWallet};
@@ -1 +1 @@
1
- import{addTxSignatures as e,secp256k1 as t}from"@avalabs/avalanchejs";import{fromSeed as i}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import"@ledgerhq/hw-app-eth";import"ethers";import{getAddressDerivationPath as n}from"../../utils/getAddressDerivationPath.js";import"hdkey";import{DerivationPath as o}from"../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../utils/digestMessage.js";import"../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import"bip32-path";class c{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!r(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const a=s(e),c=i(a);this.accountNodeXP=c.derivePath("m/44'/9000'/0'");const d=c.derivePath(n(t,o.BIP44,"EVM"));this.signerNodeEVM=d,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,i)=>{const r=this.accountNodeXP.derivePath(`${t?1:0}/${i}`);if(!r.privateKey)throw new Error("Unable to get private key.");return e.push(r.privateKey),e}),[])}getSigningKeys(e,t,i){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const r=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!r.privateKey)throw new Error("Unable to derive X/P private key.");const s=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(i,!0);return[r.privateKey,...s,...e]}if("PVM"===e)return[r.privateKey,...s]}async signTx(t){const{tx:i,externalIndices:r,internalIndices:s}=t,n=i.getVM(),o=this.getSigningKeys(n,r,s);if(!o?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await e({unsignedTx:i,privateKeys:o}),t.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const i=this.getActiveAccountNode(e.chain);if(!i.privateKey)throw Error("Unable to sign message, key not found.");const r=a(e.message),s=await t.signHash(r,i.privateKey);return Buffer.from(s)}}export{c as SimpleSigner};
1
+ import{addTxSignatures as e,secp256k1 as t}from"@avalabs/avalanchejs";import{fromSeed as i}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import"@ledgerhq/hw-app-eth";import"ethers";import{getAddressDerivationPath as n}from"../../utils/getAddressDerivationPath.js";import"hdkey";import{DerivationPath as o}from"../../EVM/constants.js";import"bitcoinjs-lib";import"@avalabs/core-utils-sdk";import"@ledgerhq/hw-transport";import"@metamask/eth-sig-util";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../utils/digestMessage.js";import"../utils/getAssetBalance.js";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import"bip32-path";class c{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!r(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const a=s(e),c=i(a);this.accountNodeXP=c.derivePath("m/44'/9000'/0'");const d=c.derivePath(n(t,o.BIP44,"EVM"));this.signerNodeEVM=d,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,i)=>{const r=this.accountNodeXP.derivePath(`${t?1:0}/${i}`);if(!r.privateKey)throw new Error("Unable to get private key.");return e.push(r.privateKey),e}),[])}getSigningKeys(e,t,i){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const r=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!r.privateKey)throw new Error("Unable to derive X/P private key.");const s=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(i,!0);return[r.privateKey,...s,...e]}if("PVM"===e)return[r.privateKey,...s]}async signTx(t){const{tx:i,externalIndices:r,internalIndices:s}=t,n=i.getVM(),o=this.getSigningKeys(n,r,s);if(!o?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await e({unsignedTx:i,privateKeys:o}),t.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const i=this.getActiveAccountNode(e.chain);if(!i.privateKey)throw Error("Unable to sign message, key not found.");const r=a(e.message),s=await t.signHash(r,i.privateKey);return Buffer.from(s)}}export{c as SimpleSigner};
@@ -1 +1 @@
1
- import{WalletVoid as i}from"./WalletVoid.js";import{secp256k1 as e,utils as t,addTxSignatures as r}from"@avalabs/avalanchejs";import{validateMnemonic as s,mnemonicToSeedSync as a}from"bip39";import{fromSeed as n}from"bip32";import{digestMessage as o}from"../utils/digestMessage.js";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import{verifyDerivationPath as p}from"../utils/verifyDerivationPath.js";const{getPublicKey:m,sign:l,signHash:v}=e,{addChecksum:c}=t;class u extends i{privKeyXP;privKeyC;constructor(i,e,t){super(Buffer.from(m(i)),Buffer.from(m(e)),t),this.privKeyXP=i,this.privKeyC=e}static fromMnemonic(i,e,t,r){if(!s(i))throw new Error("Invalid mnemonic phrase.");if(!p(t)||!p(e))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const o=a(i),m=n(o),l=m.derivePath(e),v=m.derivePath(t);if(!l.privateKey||!v.privateKey)throw new Error("Failed to generate private keys.");return new u(l.privateKey,v.privateKey,r)}async signMessage(i){const e=o(i.message),t=this.getSigningKey(i.chain);return Buffer.from(c(await v(e,t)))}getSigningKey(i){return"C"===i?this.privKeyC:this.privKeyXP}async signTx(i){return await r({unsignedTx:i.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),i.tx}async signTxBuffer(i){const e=this.getSigningKey(i.chain);return[Buffer.from(await l(i.buffer,e))]}}export{u as StaticSigner};
1
+ import{WalletVoid as i}from"./WalletVoid.js";import{secp256k1 as e,utils as t,addTxSignatures as r}from"@avalabs/avalanchejs";import{validateMnemonic as s,mnemonicToSeedSync as a}from"bip39";import{fromSeed as n}from"bip32";import{digestMessage as o}from"../utils/digestMessage.js";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"../utils/getAssetBalance.js";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import{verifyDerivationPath as p}from"../utils/verifyDerivationPath.js";const{getPublicKey:m,sign:l,signHash:u}=e,{addChecksum:v}=t;class c extends i{privKeyXP;privKeyC;constructor(i,e,t){super(Buffer.from(m(i)),Buffer.from(m(e)),t),this.privKeyXP=i,this.privKeyC=e}static fromMnemonic(i,e,t,r){if(!s(i))throw new Error("Invalid mnemonic phrase.");if(!p(t)||!p(e))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const o=a(i),m=n(o),l=m.derivePath(e),u=m.derivePath(t);if(!l.privateKey||!u.privateKey)throw new Error("Failed to generate private keys.");return new c(l.privateKey,u.privateKey,r)}async signMessage(i){const e=o(i.message),t=this.getSigningKey(i.chain);return Buffer.from(v(await u(e,t)))}getSigningKey(i){return"C"===i?this.privKeyC:this.privKeyXP}async signTx(i){return await r({unsignedTx:i.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),i.tx}async signTxBuffer(i){const e=this.getSigningKey(i.chain);return[Buffer.from(await l(i.buffer,e))]}}export{c as StaticSigner};
@@ -49,10 +49,6 @@ declare abstract class WalletAbstract {
49
49
  * @param source What is the source chain of the atomic UTXOs
50
50
  */
51
51
  getAtomicUTXOs(chain: ChainIDAlias, source: ChainIDAlias): Promise<utils.UtxoSet>;
52
- /**
53
- * Get the nonce of this wallet's C chain address
54
- */
55
- getNonce(): Promise<number>;
56
52
  exportX(amount: bigint, utxoSet: utils.UtxoSet, destination: 'P' | 'C', toAddress?: string): Common.UnsignedTx;
57
53
  importP({ utxoSet, sourceChain, toAddress, threshold, feeState, locktime, }: ImportP): Common.UnsignedTx;
58
54
  importX(utxos: utils.UtxoSet, sourceChain: 'P' | 'C', toAddress?: string): Common.UnsignedTx;
@@ -1 +1 @@
1
- import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"create-hash";import"bip32";import{getUTXOsForAddresses as e}from"../utils/getAllUTXOs.js";import"../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import{utils as s,TransferableOutput as t,avm as r,pvm as d,evm as n,pvmSerial as o,PChainOwner as i,L1Validator as a,networkIDs as m}from"@avalabs/avalanchejs";import{getStakeForAddresses as h}from"../utils/getStakeForAddresses.js";import"../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import{sortUTXOsByAmount as g,sortUTXOsByAmountAscending as u,sortUTXOsStaking as A}from"../utils/sortUTXOs.js";import"../utils/txSizeLimits.js";import"bip32-path";import{strip0x as c}from"@avalabs/core-utils-sdk";import{assertFeeStateProvided as p}from"../../utils/assertFeeStateProvided.js";const{parse:f,hexToBuffer:x}=s;class l{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(s){const t=this.provider.getApi(s);return e(this.getAddresses(s),t)}async getStake(){const e=this.provider.getApiP();return h(this.getAddresses("P"),e)}async getAtomicUTXOs(s,t){if(s===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(s),d=this.provider.getChainID(t);return e(this.getAddresses(s),r,{sourceChain:d,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(e,s,d,n){n=n||this.getCurrentAddress(d);const o=f(n)[2],i=this.provider.getAvaxID(),a=t.fromNative(i,e,[o]),m=g(s.getUTXOs(),!0),h=this.provider.getChainID(d),u=this.getAddresses("X").map((e=>f(e)[2])),A=f(this.getChangeAddress("X"))[2];return r.newExportTx(this.provider.getContext(),h,u,m,[a],{threshold:1,changeAddresses:[A]})}importP({utxoSet:e,sourceChain:s,toAddress:t,threshold:r,feeState:n,locktime:o}){const i=this.provider.getChainID(s),a=this.getAddresses("P").map((e=>f(e)[2]));f(this.getChangeAddress("P"))[2],t=t||this.getCurrentAddress("P");const m=f(t)[2],h=e.getUTXOs();return p(n),d.newImportTx({fromAddressesBytes:a,utxos:h,toAddressesBytes:[m],sourceChainId:i,threshold:r,feeState:n,locktime:o},this.provider.getContext())}importX(e,s,t){const d=this.provider.getChainID(s),n=this.getAddresses("X").map((e=>f(e)[2])),o=f(this.getChangeAddress("X"))[2];t=t||this.getCurrentAddress("X");const i=f(t)[2];return r.newImportTx(this.provider.getContext(),d,e.getUTXOs(),[i],n,{changeAddresses:[o]})}importC(e,s,t,r,d){const o=this.provider.getChainID(s),i=this.getAddresses("C").map((e=>f(e)[2]));d=d||this.getAddressEVM();const a=Buffer.from(c(d),"hex");return n.newImportTxFromBaseFee(this.provider.getContext(),a,i,e.getUTXOs(),o,t,r)}exportC(e,s,t,r,d){const o=x(this.getAddressEVM()),i=this.provider.getChainID(s);d=d||this.getCurrentAddress(s);const a=f(d)[2],m=r/BigInt(1e9);return n.newExportTxFromBaseFee(this.provider.getContext(),m,e,i,o,[a],t)}exportP({amount:e,utxoSet:s,destination:r,feeState:n,toAddress:o}){o=o||this.getCurrentAddress(r);const i=f(o)[2],a=this.provider.getAvaxID(),m=t.fromNative(a,e,[i]),h=g(s.getUTXOs(),!0),u=this.provider.getChainID(r),A=this.getAddresses("P").map((e=>f(e)[2])),c=f(this.getChangeAddress("P"))[2];return p(n),d.newExportTx({changeAddressesBytes:[c],fromAddressesBytes:A,utxos:h,outputs:[m],destinationChainId:u,feeState:n},this.provider.getContext())}consolidateP({utxoSet:e,amount:s,feeState:r,toAddress:n,options:o}){const i=u(e.getUTXOs());n=n??this.getCurrentAddress("P");const a=f(n)[2],m=this.provider.getContext(),h=[t.fromNative(m.avaxAssetID,s,[a])],g=this.getAddresses("P").map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[A];return p(r),d.newBaseTx({changeAddressesBytes:c,fromAddressesBytes:g,utxos:i,outputs:h,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,feeState:r},m)}baseTX({utxoSet:e,chain:s,toAddress:n,amountsPerAsset:o,feeState:i,options:a,fromAddresses:m}){const[h,u,A]=f(n);if(h!==s||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${n}"`);const c=Object.entries(o).map((([e,s])=>t.fromNative(e,s,[A]))),x=g(e.getUTXOs(),!0),l=(m??this.getAddresses(s)).map((e=>f(e)[2])),T=f(this.getChangeAddress("P"))[2],I=a?.changeAddresses??[T];return"X"===s?r.newBaseTx(this.provider.getContext(),l,x,c,a):(p(i),d.newBaseTx({changeAddressesBytes:I,fromAddressesBytes:l,utxos:x,outputs:c,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:i},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:n,feeState:m,address:h,validators:u,options:A,fromAddresses:c}){const p=(c??this.getAddresses("P")).map((e=>f(e)[2])),x=f(this.getChangeAddress("P"))[2],l=A?.changeAddresses??[x],T=u.map((({nodeId:e,pubKey:t,signature:r,balance:d,weight:n,deactivationOwner:m,remainingBalanceOwner:h})=>{const g=new o.ProofOfPossession(Uint8Array.from(s.hexToBuffer(t)),Uint8Array.from(s.hexToBuffer(r))),u=i.fromNative(h.addresses.map((e=>f(e)[2])),h.threshold??1),A=i.fromNative(m.addresses.map((e=>f(e)[2])),m.threshold??1);return a.fromNative(e,n,d,g,u,A)}));return d.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:T,fromAddressesBytes:p,address:f(h)[2],chainId:t,subnetId:r,subnetAuth:n,feeState:m,utxos:g(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:n,feeState:o,fromAddresses:i,options:a}){const m=(i??this.getAddresses("P")).map((e=>f(e)[2])),h=f(this.getChangeAddress("P"))[2],u=a?.changeAddresses??[h];return d.newRegisterL1ValidatorTx({utxos:g(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(s.hexToBuffer(r)),changeAddressesBytes:u,feeState:o,fromAddressesBytes:m,memo:a?.memo,message:Uint8Array.from(s.hexToBuffer(n)),minIssuanceTime:a?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:n,fromAddresses:o}){const i=(o??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],m=n?.changeAddresses??[a];return d.newSetL1ValidatorWeightTx({utxos:g(e.getUTXOs(),!0),changeAddressesBytes:m,feeState:t,fromAddressesBytes:i,memo:n?.memo,message:Uint8Array.from(s.hexToBuffer(r)),minIssuanceTime:n?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:s,options:t,fromAddresses:r,disableAuth:n,validationId:o}){const i=(r??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],m=t?.changeAddresses??[a];return d.newDisableL1ValidatorTx({disableAuth:n,validationId:o,utxos:g(e.getUTXOs(),!0),changeAddressesBytes:m,feeState:s,fromAddressesBytes:i,memo:t?.memo,minIssuanceTime:t?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:s,options:t,fromAddresses:r,balance:n,validationId:o}){const i=(r??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],m=t?.changeAddresses??[a];return d.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:o,utxos:g(e.getUTXOs(),!0),changeAddressesBytes:m,feeState:s,fromAddressesBytes:i,memo:t?.memo,minIssuanceTime:t?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:s,chainName:t,vmID:r,fxIds:n,genesisData:o,subnetAuth:i,feeState:a,options:m,fromAddresses:h}){const u=g(e.getUTXOs(),!0),A=(h??this.getAddresses("P")).map((e=>f(e)[2])),c=f(this.getChangeAddress("P"))[2],x=m?.changeAddresses??[c];return p(a),d.newCreateChainTx({chainName:t,feeState:a,fromAddressesBytes:A,fxIds:n,genesisData:o,subnetAuth:i,subnetId:s,utxos:u,vmId:r,changeAddressesBytes:x},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:s,feeState:t,fromAddresses:r,options:n,threshold:o,locktime:i}){const a=g(e.getUTXOs(),!0),m=(r??this.getAddresses("P")).map((e=>f(e)[2])),h=f(this.getChangeAddress("P"))[2],u=n?.changeAddresses??[h],A=s.map((e=>f(e)[2]));return p(t),d.newCreateSubnetTx({fromAddressesBytes:m,changeAddressesBytes:u,utxos:a,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:t,threshold:o,locktime:i,subnetOwners:A},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:s,start:t,end:r,weight:n,subnetId:o,subnetAuth:i,feeState:a,fromAddresses:m,options:h}){const u=g(e.getUTXOs(),!0),A=(m??this.getAddresses("P")).map((e=>f(e)[2])),c=f(this.getChangeAddress("P"))[2],x=h?.changeAddresses??[c];return p(a),d.newAddSubnetValidatorTx({changeAddressesBytes:x,fromAddressesBytes:A,utxos:u,minIssuanceTime:h?.minIssuanceTime,memo:h?.memo,nodeId:s,start:t,end:r,weight:n,subnetId:o,subnetAuth:i,feeState:a},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:s,start:t,end:r,weight:n,subnetId:o,shares:i,feeState:a,fromAddresses:h,rewardAddresses:g,delegatorRewardAddresses:u,publicKey:c,signature:x,options:l,threshold:T,locktime:I,stakingAssetId:v}){const C=A(e.getUTXOs()),S=(h??this.getAddresses("P")).map((e=>f(e)[2])),b=(g??[this.getCurrentAddress("P")]).map((e=>f(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>f(e)[2]));if(!(o!==m.PrimaryNetworkID.toString()||c&&x))throw new Error("Must provide public key and signature for primary subnet.");const P=f(this.getChangeAddress("P"))[2],B=l?.changeAddresses??[P];return p(a),d.newAddPermissionlessValidatorTx({fromAddressesBytes:S,delegatorRewardsOwner:w,utxos:C,minIssuanceTime:l?.minIssuanceTime,memo:l?.memo,changeAddressesBytes:B,nodeId:s,start:t,end:r,weight:n,subnetId:o,shares:i,feeState:a,publicKey:c,rewardAddresses:b,signature:x,locktime:I,threshold:T,stakingAssetId:v},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:s,start:t,end:r,weight:n,subnetId:o,fromAddresses:i,rewardAddresses:a,options:m,locktime:h,feeState:g,threshold:u,stakingAssetId:c}){const x=A(e.getUTXOs()),l=(i??this.getAddresses("P")).map((e=>f(e)[2])),T=(a??[this.getCurrentAddress("P")]).map((e=>f(e)[2])),I=f(this.getChangeAddress("P"))[2],v=m?.changeAddresses??[I];return p(g),d.newAddPermissionlessDelegatorTx({fromAddressesBytes:l,utxos:x,minIssuanceTime:m?.minIssuanceTime,memo:m?.memo,changeAddressesBytes:v,nodeId:s,start:t,end:r,weight:n,subnetId:o,rewardAddresses:T,locktime:h,stakingAssetId:c,threshold:u,feeState:g},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:s,subnetId:t,subnetAuth:r,fromAddresses:n,feeState:o,options:i}){const a=g(e.getUTXOs(),!0),m=(n??this.getAddresses("P")).map((e=>f(e)[2])),h=f(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[h];return p(o),d.newRemoveSubnetValidatorTx({changeAddressesBytes:u,fromAddressesBytes:m,utxos:a,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:s,subnetId:t,subnetAuth:r,feeState:o},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:s,subnetAuth:t,subnetOwners:r,feeState:n,fromAddresses:o,options:i,threshold:a,locktime:m}){const h=g(e.getUTXOs(),!0),u=(o??this.getAddresses("P")).map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[A],x=r.map((e=>f(e)[2]));return p(n),d.newTransferSubnetOwnershipTx({changeAddressesBytes:c,fromAddressesBytes:u,utxos:h,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:s,subnetAuth:t,subnetOwners:x,feeState:n,threshold:a,locktime:m},this.provider.getContext())}}export{l as WalletAbstract};
1
+ import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"create-hash";import"bip32";import{getUTXOsForAddresses as e}from"../utils/getAllUTXOs.js";import"../utils/getAssetBalance.js";import{utils as s,TransferableOutput as t,avm as r,pvm as d,evm as n,pvmSerial as o,PChainOwner as i,L1Validator as a,networkIDs as m}from"@avalabs/avalanchejs";import{getStakeForAddresses as h}from"../utils/getStakeForAddresses.js";import"../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import{sortUTXOsByAmount as g,sortUTXOsByAmountAscending as u,sortUTXOsStaking as A}from"../utils/sortUTXOs.js";import"../utils/txSizeLimits.js";import"bip32-path";import{strip0x as c}from"@avalabs/core-utils-sdk";import{assertFeeStateProvided as p}from"../../utils/assertFeeStateProvided.js";const{parse:f,hexToBuffer:x}=s;class l{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(s){const t=this.provider.getApi(s);return e(this.getAddresses(s),t)}async getStake(){const e=this.provider.getApiP();return h(this.getAddresses("P"),e)}async getAtomicUTXOs(s,t){if(s===t)throw new Error("Chain can not be the same as source chain.");const r=this.provider.getApi(s),d=this.provider.getChainID(t);return e(this.getAddresses(s),r,{sourceChain:d,addresses:[]})}exportX(e,s,d,n){n=n||this.getCurrentAddress(d);const o=f(n)[2],i=this.provider.getAvaxID(),a=t.fromNative(i,e,[o]),m=g(s.getUTXOs(),!0),h=this.provider.getChainID(d),u=this.getAddresses("X").map((e=>f(e)[2])),A=f(this.getChangeAddress("X"))[2];return r.newExportTx(this.provider.getContext(),h,u,m,[a],{threshold:1,changeAddresses:[A]})}importP({utxoSet:e,sourceChain:s,toAddress:t,threshold:r,feeState:n,locktime:o}){const i=this.provider.getChainID(s),a=this.getAddresses("P").map((e=>f(e)[2]));f(this.getChangeAddress("P"))[2],t=t||this.getCurrentAddress("P");const m=f(t)[2],h=e.getUTXOs();return p(n),d.newImportTx({fromAddressesBytes:a,utxos:h,toAddressesBytes:[m],sourceChainId:i,threshold:r,feeState:n,locktime:o},this.provider.getContext())}importX(e,s,t){const d=this.provider.getChainID(s),n=this.getAddresses("X").map((e=>f(e)[2])),o=f(this.getChangeAddress("X"))[2];t=t||this.getCurrentAddress("X");const i=f(t)[2];return r.newImportTx(this.provider.getContext(),d,e.getUTXOs(),[i],n,{changeAddresses:[o]})}importC(e,s,t,r,d){const o=this.provider.getChainID(s),i=this.getAddresses("C").map((e=>f(e)[2]));d=d||this.getAddressEVM();const a=Buffer.from(c(d),"hex");return n.newImportTxFromBaseFee(this.provider.getContext(),a,i,e.getUTXOs(),o,t,r)}exportC(e,s,t,r,d){const o=x(this.getAddressEVM()),i=this.provider.getChainID(s);d=d||this.getCurrentAddress(s);const a=f(d)[2],m=r/BigInt(1e9);return n.newExportTxFromBaseFee(this.provider.getContext(),m,e,i,o,[a],t)}exportP({amount:e,utxoSet:s,destination:r,feeState:n,toAddress:o}){o=o||this.getCurrentAddress(r);const i=f(o)[2],a=this.provider.getAvaxID(),m=t.fromNative(a,e,[i]),h=g(s.getUTXOs(),!0),u=this.provider.getChainID(r),A=this.getAddresses("P").map((e=>f(e)[2])),c=f(this.getChangeAddress("P"))[2];return p(n),d.newExportTx({changeAddressesBytes:[c],fromAddressesBytes:A,utxos:h,outputs:[m],destinationChainId:u,feeState:n},this.provider.getContext())}consolidateP({utxoSet:e,amount:s,feeState:r,toAddress:n,options:o}){const i=u(e.getUTXOs());n=n??this.getCurrentAddress("P");const a=f(n)[2],m=this.provider.getContext(),h=[t.fromNative(m.avaxAssetID,s,[a])],g=this.getAddresses("P").map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[A];return p(r),d.newBaseTx({changeAddressesBytes:c,fromAddressesBytes:g,utxos:i,outputs:h,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,feeState:r},m)}baseTX({utxoSet:e,chain:s,toAddress:n,amountsPerAsset:o,feeState:i,options:a,fromAddresses:m}){const[h,u,A]=f(n);if(h!==s||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${n}"`);const c=Object.entries(o).map((([e,s])=>t.fromNative(e,s,[A]))),x=g(e.getUTXOs(),!0),l=(m??this.getAddresses(s)).map((e=>f(e)[2])),T=f(this.getChangeAddress("P"))[2],I=a?.changeAddresses??[T];return"X"===s?r.newBaseTx(this.provider.getContext(),l,x,c,a):(p(i),d.newBaseTx({changeAddressesBytes:I,fromAddressesBytes:l,utxos:x,outputs:c,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:i},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:n,feeState:m,address:h,validators:u,options:A,fromAddresses:c}){const p=(c??this.getAddresses("P")).map((e=>f(e)[2])),x=f(this.getChangeAddress("P"))[2],l=A?.changeAddresses??[x],T=u.map((({nodeId:e,pubKey:t,signature:r,balance:d,weight:n,deactivationOwner:m,remainingBalanceOwner:h})=>{const g=new o.ProofOfPossession(Uint8Array.from(s.hexToBuffer(t)),Uint8Array.from(s.hexToBuffer(r))),u=i.fromNative(h.addresses.map((e=>f(e)[2])),h.threshold??1),A=i.fromNative(m.addresses.map((e=>f(e)[2])),m.threshold??1);return a.fromNative(e,n,d,g,u,A)}));return d.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:T,fromAddressesBytes:p,address:f(h)[2],chainId:t,subnetId:r,subnetAuth:n,feeState:m,utxos:g(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:n,feeState:o,fromAddresses:i,options:a}){const m=(i??this.getAddresses("P")).map((e=>f(e)[2])),h=f(this.getChangeAddress("P"))[2],u=a?.changeAddresses??[h];return d.newRegisterL1ValidatorTx({utxos:g(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(s.hexToBuffer(r)),changeAddressesBytes:u,feeState:o,fromAddressesBytes:m,memo:a?.memo,message:Uint8Array.from(s.hexToBuffer(n)),minIssuanceTime:a?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:n,fromAddresses:o}){const i=(o??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],m=n?.changeAddresses??[a];return d.newSetL1ValidatorWeightTx({utxos:g(e.getUTXOs(),!0),changeAddressesBytes:m,feeState:t,fromAddressesBytes:i,memo:n?.memo,message:Uint8Array.from(s.hexToBuffer(r)),minIssuanceTime:n?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:s,options:t,fromAddresses:r,disableAuth:n,validationId:o}){const i=(r??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],m=t?.changeAddresses??[a];return d.newDisableL1ValidatorTx({disableAuth:n,validationId:o,utxos:g(e.getUTXOs(),!0),changeAddressesBytes:m,feeState:s,fromAddressesBytes:i,memo:t?.memo,minIssuanceTime:t?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:s,options:t,fromAddresses:r,balance:n,validationId:o}){const i=(r??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],m=t?.changeAddresses??[a];return d.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:o,utxos:g(e.getUTXOs(),!0),changeAddressesBytes:m,feeState:s,fromAddressesBytes:i,memo:t?.memo,minIssuanceTime:t?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:s,chainName:t,vmID:r,fxIds:n,genesisData:o,subnetAuth:i,feeState:a,options:m,fromAddresses:h}){const u=g(e.getUTXOs(),!0),A=(h??this.getAddresses("P")).map((e=>f(e)[2])),c=f(this.getChangeAddress("P"))[2],x=m?.changeAddresses??[c];return p(a),d.newCreateChainTx({chainName:t,feeState:a,fromAddressesBytes:A,fxIds:n,genesisData:o,subnetAuth:i,subnetId:s,utxos:u,vmId:r,changeAddressesBytes:x},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:s,feeState:t,fromAddresses:r,options:n,threshold:o,locktime:i}){const a=g(e.getUTXOs(),!0),m=(r??this.getAddresses("P")).map((e=>f(e)[2])),h=f(this.getChangeAddress("P"))[2],u=n?.changeAddresses??[h],A=s.map((e=>f(e)[2]));return p(t),d.newCreateSubnetTx({fromAddressesBytes:m,changeAddressesBytes:u,utxos:a,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:t,threshold:o,locktime:i,subnetOwners:A},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:s,start:t,end:r,weight:n,subnetId:o,subnetAuth:i,feeState:a,fromAddresses:m,options:h}){const u=g(e.getUTXOs(),!0),A=(m??this.getAddresses("P")).map((e=>f(e)[2])),c=f(this.getChangeAddress("P"))[2],x=h?.changeAddresses??[c];return p(a),d.newAddSubnetValidatorTx({changeAddressesBytes:x,fromAddressesBytes:A,utxos:u,minIssuanceTime:h?.minIssuanceTime,memo:h?.memo,nodeId:s,start:t,end:r,weight:n,subnetId:o,subnetAuth:i,feeState:a},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:s,start:t,end:r,weight:n,subnetId:o,shares:i,feeState:a,fromAddresses:h,rewardAddresses:g,delegatorRewardAddresses:u,publicKey:c,signature:x,options:l,threshold:T,locktime:I,stakingAssetId:v}){const C=A(e.getUTXOs()),S=(h??this.getAddresses("P")).map((e=>f(e)[2])),b=(g??[this.getCurrentAddress("P")]).map((e=>f(e)[2])),P=(u??[this.getCurrentAddress("P")]).map((e=>f(e)[2]));if(!(o!==m.PrimaryNetworkID.toString()||c&&x))throw new Error("Must provide public key and signature for primary subnet.");const w=f(this.getChangeAddress("P"))[2],B=l?.changeAddresses??[w];return p(a),d.newAddPermissionlessValidatorTx({fromAddressesBytes:S,delegatorRewardsOwner:P,utxos:C,minIssuanceTime:l?.minIssuanceTime,memo:l?.memo,changeAddressesBytes:B,nodeId:s,start:t,end:r,weight:n,subnetId:o,shares:i,feeState:a,publicKey:c,rewardAddresses:b,signature:x,locktime:I,threshold:T,stakingAssetId:v},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:s,start:t,end:r,weight:n,subnetId:o,fromAddresses:i,rewardAddresses:a,options:m,locktime:h,feeState:g,threshold:u,stakingAssetId:c}){const x=A(e.getUTXOs()),l=(i??this.getAddresses("P")).map((e=>f(e)[2])),T=(a??[this.getCurrentAddress("P")]).map((e=>f(e)[2])),I=f(this.getChangeAddress("P"))[2],v=m?.changeAddresses??[I];return p(g),d.newAddPermissionlessDelegatorTx({fromAddressesBytes:l,utxos:x,minIssuanceTime:m?.minIssuanceTime,memo:m?.memo,changeAddressesBytes:v,nodeId:s,start:t,end:r,weight:n,subnetId:o,rewardAddresses:T,locktime:h,stakingAssetId:c,threshold:u,feeState:g},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:s,subnetId:t,subnetAuth:r,fromAddresses:n,feeState:o,options:i}){const a=g(e.getUTXOs(),!0),m=(n??this.getAddresses("P")).map((e=>f(e)[2])),h=f(this.getChangeAddress("P"))[2],u=i?.changeAddresses??[h];return p(o),d.newRemoveSubnetValidatorTx({changeAddressesBytes:u,fromAddressesBytes:m,utxos:a,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:s,subnetId:t,subnetAuth:r,feeState:o},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:s,subnetAuth:t,subnetOwners:r,feeState:n,fromAddresses:o,options:i,threshold:a,locktime:m}){const h=g(e.getUTXOs(),!0),u=(o??this.getAddresses("P")).map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2],c=i?.changeAddresses??[A],x=r.map((e=>f(e)[2]));return p(n),d.newTransferSubnetOwnershipTx({changeAddressesBytes:c,fromAddressesBytes:u,utxos:h,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:s,subnetAuth:t,subnetOwners:x,feeState:n,threshold:a,locktime:m},this.provider.getContext())}}export{l as WalletAbstract};
@@ -1 +1 @@
1
- import{WalletAbstract as t}from"./WalletAbstract.js";import{fromSeed as e}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import{strip0x as i}from"@avalabs/core-utils-sdk";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"create-hash";import"@avalabs/avalanchejs";import"../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import{verifyDerivationPath as o}from"../utils/verifyDerivationPath.js";import{SigningKey as a,computeAddress as n}from"ethers";class u extends t{constructor(t,e,r){if(super(r),this.pubkeyXP=t,this.pubkeyC=e,33!==e.length||33!==t.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(t,e,r){const s=i(a.computePublicKey(t,!0)),o=i(a.computePublicKey(e,!0)),n=Buffer.from(s,"hex"),l=Buffer.from(o,"hex");return new u(n,l,r)}static fromMnemonic(t,i,a,n){if(!r(t))throw new Error("Invalid mnemonic phrase.");if(!o(a)||!o(i))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const l=s(t),m=e(l),p=m.derivePath(a),c=m.derivePath(i);return u.fromPublicKey(c.publicKey,p.publicKey,n)}getAddress(t){const e="C"===t?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(e,t)}getAddressEVM(){return n(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(t){return[this.getAddress(t)]}getChangeAddress(t){return this.getAddress(t)}getCurrentAddress(t){return this.getAddress(t)}}export{u as WalletVoid};
1
+ import{WalletAbstract as t}from"./WalletAbstract.js";import{fromSeed as e}from"bip32";import{validateMnemonic as r,mnemonicToSeedSync as s}from"bip39";import{strip0x as i}from"@avalabs/core-utils-sdk";import"../utils/addSignaturesToAvalancheTx.js";import"../utils/convertGlacierUtxo.js";import"../utils/createAvalancheEvmUnsignedTx.js";import"../utils/createAvalancheUnsignedTx.js";import"create-hash";import"@avalabs/avalanchejs";import"../utils/getAssetBalance.js";import"../utils/getUtxosByTxFromGlacier.js";import"../utils/parseAvalancheTx.js";import"../utils/populateCredential.js";import"../utils/txSizeLimits.js";import{verifyDerivationPath as o}from"../utils/verifyDerivationPath.js";import{SigningKey as a,computeAddress as n}from"ethers";class u extends t{constructor(t,e,r){if(super(r),this.pubkeyXP=t,this.pubkeyC=e,33!==e.length||33!==t.length)throw new Error("Public key must be 33 byte compressed public key")}static fromPublicKey(t,e,r){const s=i(a.computePublicKey(t,!0)),o=i(a.computePublicKey(e,!0)),n=Buffer.from(s,"hex"),l=Buffer.from(o,"hex");return new u(n,l,r)}static fromMnemonic(t,i,a,n){if(!r(t))throw new Error("Invalid mnemonic phrase.");if(!o(a)||!o(i))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const l=s(t),m=e(l),p=m.derivePath(a),c=m.derivePath(i);return u.fromPublicKey(c.publicKey,p.publicKey,n)}getAddress(t){const e="C"===t?this.pubkeyC:this.pubkeyXP;return this.provider.getAddress(e,t)}getAddressEVM(){return n(`0x${this.pubkeyC.toString("hex")}`)}getAddresses(t){return[this.getAddress(t)]}getChangeAddress(t){return this.getAddress(t)}getCurrentAddress(t){return this.getAddress(t)}}export{u as WalletVoid};
@@ -1 +1 @@
1
- import{WalletVoid as t}from"../WalletVoid.js";import{isObsidianApp as r}from"./isObsidianApp.js";import{ZondaxProvider as e}from"./ZondaxProvider.js";import i from"bip32-path";import s from"@ledgerhq/hw-app-eth";import{utils as o}from"@avalabs/avalanchejs";import"../../utils/addSignaturesToAvalancheTx.js";import"../../utils/convertGlacierUtxo.js";import"../../utils/createAvalancheEvmUnsignedTx.js";import"../../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../../utils/digestMessage.js";import"bip32";import"../../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import"../../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../../utils/parseAvalancheTx.js";import"../../utils/populateCredential.js";import"../../utils/txSizeLimits.js";import{verifyDerivationPath as n}from"../../utils/verifyDerivationPath.js";import{SigningKey as p}from"ethers";const{strip0x:h}=o;class u extends t{constructor(t,r,e,i,s){const a=o.strip0x(p.computePublicKey(t,!0)),h=o.strip0x(p.computePublicKey(e,!0));if(super(Buffer.from(a,"hex"),Buffer.from(h,"hex"),s),this.pathXP=r,this.pathC=i,!n(r)||!n(i))throw new Error("Invalid path configuration.")}static async fromTransport(t,e,i,o){if(await r(t))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!n(e)||!n(i))throw new Error("Invalid path configuration.");const a=new s(t),c=await a.getAddress(i,!1),f=await a.getAddress(e,!1),m=Buffer.from(h(c.publicKey),"hex"),g=Buffer.from(h(f.publicKey),"hex"),l=Buffer.from(h(p.computePublicKey(m,!0)),"hex"),d=Buffer.from(h(p.computePublicKey(g,!0)),"hex");return new u(d,e,l,i,o)}async signMessage(t){if(!t.transport||!t.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const r=i.fromString(this.getAccountPath(t.chain)),s=i.fromString(this.getPartialSignerPath(t.chain)),o=a(t.message),n=(await e.signHash(t.transport,o,r,[s])).signatures.get(s.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}getFullSignerPath(t){return"C"===t?this.pathC:this.pathXP}getPartialSignerPath(t){return this.getFullSignerPath(t).split("/").slice(4).join("/")}getAccountPath(t){return this.getFullSignerPath(t).split("/").slice(0,4).join("/")}async signTx(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=t.tx,e=r.getVM(),i=Buffer.from(r.toBytes()),s="EVM"===e?"C":"X";return(await this.signTxBuffer({buffer:i,chain:s,transport:t.transport})).forEach((t=>{r.addSignature(t)})),r}async signTxBuffer(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=i.fromString(this.getAccountPath(t.chain)),s=i.fromString(this.getPartialSignerPath(t.chain));return[...(await e.signTx(t.transport,t.buffer,r,[s],[s])).signatures.values()]}}export{u as LedgerSigner};
1
+ import{WalletVoid as t}from"../WalletVoid.js";import{isObsidianApp as r}from"./isObsidianApp.js";import{ZondaxProvider as e}from"./ZondaxProvider.js";import i from"bip32-path";import s from"@ledgerhq/hw-app-eth";import{utils as o}from"@avalabs/avalanchejs";import"../../utils/addSignaturesToAvalancheTx.js";import"../../utils/convertGlacierUtxo.js";import"../../utils/createAvalancheEvmUnsignedTx.js";import"../../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../../utils/digestMessage.js";import"bip32";import"../../utils/getAssetBalance.js";import"../../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../../utils/parseAvalancheTx.js";import"../../utils/populateCredential.js";import"../../utils/txSizeLimits.js";import{verifyDerivationPath as n}from"../../utils/verifyDerivationPath.js";import{SigningKey as p}from"ethers";const{strip0x:u}=o;class h extends t{constructor(t,r,e,i,s){const a=o.strip0x(p.computePublicKey(t,!0)),u=o.strip0x(p.computePublicKey(e,!0));if(super(Buffer.from(a,"hex"),Buffer.from(u,"hex"),s),this.pathXP=r,this.pathC=i,!n(r)||!n(i))throw new Error("Invalid path configuration.")}static async fromTransport(t,e,i,o){if(await r(t))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!n(e)||!n(i))throw new Error("Invalid path configuration.");const a=new s(t),f=await a.getAddress(i,!1),g=await a.getAddress(e,!1),m=Buffer.from(u(f.publicKey),"hex"),c=Buffer.from(u(g.publicKey),"hex"),l=Buffer.from(u(p.computePublicKey(m,!0)),"hex"),d=Buffer.from(u(p.computePublicKey(c,!0)),"hex");return new h(d,e,l,i,o)}async signMessage(t){if(!t.transport||!t.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const r=i.fromString(this.getAccountPath(t.chain)),s=i.fromString(this.getPartialSignerPath(t.chain)),o=a(t.message),n=(await e.signHash(t.transport,o,r,[s])).signatures.get(s.toString(!0));if(!n)throw new Error("Failed to sign message.");return n}getFullSignerPath(t){return"C"===t?this.pathC:this.pathXP}getPartialSignerPath(t){return this.getFullSignerPath(t).split("/").slice(4).join("/")}getAccountPath(t){return this.getFullSignerPath(t).split("/").slice(0,4).join("/")}async signTx(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=t.tx,e=r.getVM(),i=Buffer.from(r.toBytes()),s="EVM"===e?"C":"X";return(await this.signTxBuffer({buffer:i,chain:s,transport:t.transport})).forEach((t=>{r.addSignature(t)})),r}async signTxBuffer(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=i.fromString(this.getAccountPath(t.chain)),s=i.fromString(this.getPartialSignerPath(t.chain));return[...(await e.signTx(t.transport,t.buffer,r,[s],[s])).signatures.values()]}}export{h as LedgerSigner};
@@ -1 +1 @@
1
- import{utils as t,EVMUnsignedTx as r,UnsignedTx as e}from"@avalabs/avalanchejs";import s from"bip32-path";import{getTxOutputAddresses as i}from"../../utils/getTxOutputAddresses.js";import{ZondaxProvider as n}from"./ZondaxProvider.js";import{fromBase58 as o}from"bip32";import"../../utils/addSignaturesToAvalancheTx.js";import"../../utils/convertGlacierUtxo.js";import"../../utils/createAvalancheEvmUnsignedTx.js";import"../../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../../utils/digestMessage.js";import"../../utils/getAssetBalance.js";import"@avalabs/core-chains-sdk";import"../../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../../utils/parseAvalancheTx.js";import"../../utils/populateCredential.js";import"../../utils/txSizeLimits.js";const{parse:c}=t;class g{constructor(t,r,e){this.activeAccountIndex=t,this.provider=r,e&&(this.accountNode=o(e))}accountNode;reSerializeTx(t,s){return t instanceof r||"C"===s?r.fromJSON(JSON.stringify(t.toJSON())):e.fromJSON(JSON.stringify(t.toJSON()))}getChainAlias(t){return"EVM"===t.getVM()?"C":"X"}getAccountPath(t){switch(t){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(t,r){if(!this.accountNode)return null;const{publicKey:e}=this.accountNode.derivePath(t),s=this.provider.getAddress(e,r);return Buffer.from(c(s)[2]).toString("hex")}getAddressPathMap(t){const{tx:r,externalIndices:e,internalIndices:s}=t,i=this.getChainAlias(r),n=`0/${this.activeAccountIndex}`,o=new Map;if("C"===i||!this.accountNode)return o;const a=[n,...(e??[]).map((t=>`0/${t}`)),...(s??[]).map((t=>`1/${t}`))];for(const t of a){const r=this.getAddressOfPath(t,i);r&&o.set(r,t)}return o}getAddressBipPaths(t,r){return 0===r.size?[s.fromString(`0/${this.activeAccountIndex}`)]:t.reduce(((t,e)=>{const i=r.get(Buffer.from(e).toString("hex"));return i&&t.push(s.fromString(i)),t}),[])}async signTx(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=this.getChainAlias(t.tx),e=this.reSerializeTx(t.tx,r),s=Buffer.from(e.toBytes()),n=this.getAddressPathMap(t),o=this.getAddressBipPaths(e.getAddresses(),n),a=this.getAddressBipPaths([...i(e)],n);return(await this.signTxBuffer({buffer:s,chain:r,transport:t.transport,signers:o,change:a})).forEach((t=>{e.addSignature(t)})),e}async signTxBuffer(t){if(!t.transport)throw new Error("Ledger transport not provided");if(!t.signers)throw new Error("Signers not provided");const r=t.change||[],e=s.fromString(this.getAccountPath(t.chain));return[...(await n.signTx(t.transport,t.buffer,e,t.signers,r)).signatures.values()]}async signMessage(t){if(!t.transport||!t.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const r=t.signer||s.fromString(`0/${this.activeAccountIndex}`);if(2!=r.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const e=a(t.message),i=(await n.signHash(t.transport,e,s.fromString(this.getAccountPath(t.chain)),[r])).signatures.get(r.toString(!0));if(!i)throw new Error("Failed to sign message.");return i}}export{g as SimpleLedgerSigner};
1
+ import{utils as t,EVMUnsignedTx as r,UnsignedTx as e}from"@avalabs/avalanchejs";import s from"bip32-path";import{getTxOutputAddresses as i}from"../../utils/getTxOutputAddresses.js";import{ZondaxProvider as n}from"./ZondaxProvider.js";import{fromBase58 as o}from"bip32";import"../../utils/addSignaturesToAvalancheTx.js";import"../../utils/convertGlacierUtxo.js";import"../../utils/createAvalancheEvmUnsignedTx.js";import"../../utils/createAvalancheUnsignedTx.js";import{digestMessage as a}from"../../utils/digestMessage.js";import"../../utils/getAssetBalance.js";import"../../utils/getUtxosByTxFromGlacier.js";import"bip39";import"../../utils/parseAvalancheTx.js";import"../../utils/populateCredential.js";import"../../utils/txSizeLimits.js";const{parse:c}=t;class g{constructor(t,r,e){this.activeAccountIndex=t,this.provider=r,e&&(this.accountNode=o(e))}accountNode;reSerializeTx(t,s){return t instanceof r||"C"===s?r.fromJSON(JSON.stringify(t.toJSON())):e.fromJSON(JSON.stringify(t.toJSON()))}getChainAlias(t){return"EVM"===t.getVM()?"C":"X"}getAccountPath(t){switch(t){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(t,r){if(!this.accountNode)return null;const{publicKey:e}=this.accountNode.derivePath(t),s=this.provider.getAddress(e,r);return Buffer.from(c(s)[2]).toString("hex")}getAddressPathMap(t){const{tx:r,externalIndices:e,internalIndices:s}=t,i=this.getChainAlias(r),n=`0/${this.activeAccountIndex}`,o=new Map;if("C"===i||!this.accountNode)return o;const a=[n,...(e??[]).map((t=>`0/${t}`)),...(s??[]).map((t=>`1/${t}`))];for(const t of a){const r=this.getAddressOfPath(t,i);r&&o.set(r,t)}return o}getAddressBipPaths(t,r){return 0===r.size?[s.fromString(`0/${this.activeAccountIndex}`)]:t.reduce(((t,e)=>{const i=r.get(Buffer.from(e).toString("hex"));return i&&t.push(s.fromString(i)),t}),[])}async signTx(t){if(!t.transport)throw new Error("Ledger transport not provided");const r=this.getChainAlias(t.tx),e=this.reSerializeTx(t.tx,r),s=Buffer.from(e.toBytes()),n=this.getAddressPathMap(t),o=this.getAddressBipPaths(e.getAddresses(),n),a=this.getAddressBipPaths([...i(e)],n);return(await this.signTxBuffer({buffer:s,chain:r,transport:t.transport,signers:o,change:a})).forEach((t=>{e.addSignature(t)})),e}async signTxBuffer(t){if(!t.transport)throw new Error("Ledger transport not provided");if(!t.signers)throw new Error("Signers not provided");const r=t.change||[],e=s.fromString(this.getAccountPath(t.chain));return[...(await n.signTx(t.transport,t.buffer,e,t.signers,r)).signatures.values()]}async signMessage(t){if(!t.transport||!t.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const r=t.signer||s.fromString(`0/${this.activeAccountIndex}`);if(2!=r.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const e=a(t.message),i=(await n.signHash(t.transport,e,s.fromString(this.getAccountPath(t.chain)),[r])).signatures.get(r.toString(!0));if(!i)throw new Error("Failed to sign message.");return i}}export{g as SimpleLedgerSigner};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avalabs/core-wallets-sdk",
3
- "version": "3.1.0-alpha.64",
3
+ "version": "3.1.0-alpha.66",
4
4
  "license": "Limited Ecosystem License",
5
5
  "private": false,
6
6
  "type": "module",
@@ -70,5 +70,5 @@
70
70
  "peerDependencies": {
71
71
  "ethers": "^6.7.1"
72
72
  },
73
- "gitHead": "60b74b2b13b28e541cb699da1a6ebd42a7f084d3"
73
+ "gitHead": "707b84c0994ff0cc6e7ae4716b9c1325dd885981"
74
74
  }