@avalabs/core-wallets-sdk 3.1.0-alpha.31 → 3.1.0-alpha.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -14,10 +14,8 @@ import { Bip32Path } from 'bip32-path';
14
14
  import AppZondax, { ResponseBase } from '@avalabs/hw-app-avalanche';
15
15
  import { BIP32Interface } from 'bip32';
16
16
  import { GetUpgradesInfoResponse } from '@avalabs/avalanchejs/dist/info/model';
17
- import * as _avalabs_avalanchejs_dist_vms_pvm from '@avalabs/avalanchejs/dist/vms/pvm';
18
17
  import { Utxo as Utxo$1, PChainUtxo, Network as Network$2 } from '@avalabs/glacier-sdk';
19
18
  import * as _avalabs_avalanchejs_dist_serializable_common_types from '@avalabs/avalanchejs/dist/serializable/common/types';
20
- import { WalletAbstract as WalletAbstract$1 } from 'Avalanche/wallets';
21
19
 
22
20
  /**
23
21
  * Custom Bitcoin UTXO interface.
@@ -826,24 +824,7 @@ declare const MainnetContext: Context.Context;
826
824
  * Avalanche Fuji testnet context
827
825
  */
828
826
  declare const FujiContext: Context.Context;
829
- declare const DevnetContext: {
830
- addPrimaryNetworkDelegatorFee: bigint;
831
- addPrimaryNetworkValidatorFee: bigint;
832
- addSubnetDelegatorFee: bigint;
833
- addSubnetValidatorFee: bigint;
834
- avaxAssetID: string;
835
- baseTxFee: bigint;
836
- cBlockchainID: string;
837
- createAssetTxFee: bigint;
838
- createBlockchainTxFee: bigint;
839
- createSubnetTxFee: bigint;
840
- hrp: string;
841
- networkID: number;
842
- pBlockchainID: string;
843
- transformSubnetTxFee: bigint;
844
- xBlockchainID: string;
845
- platformFeeConfig: _avalabs_avalanchejs_dist_vms_pvm.FeeConfig;
846
- };
827
+ declare const DevnetContext: Context.Context;
847
828
 
848
829
  type BaseTx = {
849
830
  utxoSet: utils.UtxoSet;
@@ -1099,12 +1080,6 @@ declare abstract class WalletAbstract {
1099
1080
  * @param toAddress
1100
1081
  */
1101
1082
  exportP({ amount, utxoSet, destination, feeState, toAddress }: ExportP): Common.UnsignedTx;
1102
- addValidator(utxos: utils.UtxoSet, nodeId: string, stakeAmount: bigint, startDate: bigint, endDate: bigint, delegationFee: number, config?: {
1103
- rewardAddress?: string;
1104
- }): Common.UnsignedTx;
1105
- addDelegator(utxos: utils.UtxoSet, nodeId: string, stakeAmount: bigint, startDate: bigint, endDate: bigint, config?: {
1106
- rewardAddress?: string;
1107
- }): Common.UnsignedTx;
1108
1083
  consolidateP({ utxoSet, amount, feeState, toAddress, options, }: ConsolidateP): Common.UnsignedTx;
1109
1084
  baseTX({ utxoSet, chain, toAddress, amountsPerAsset, feeState, options, fromAddresses, }: BaseTx): Common.UnsignedTx;
1110
1085
  convertSubnetToL1({ utxoSet, chainId, subnetId, subnetAuth, feeState, address, validators, options, fromAddresses, }: ConvertSubnetToL1): Common.UnsignedTx;
@@ -1147,7 +1122,6 @@ declare abstract class WalletAbstract {
1147
1122
  addPermissionlessDelegator({ utxoSet, nodeId, start, end, weight, subnetId, fromAddresses, rewardAddresses, options, locktime, feeState, threshold, stakingAssetId, }: AddPermissionlessDelegator): Common.UnsignedTx;
1148
1123
  removeSubnetValidator({ utxoSet, nodeId, subnetId, subnetAuth, fromAddresses, feeState, options, }: RemoveSubnetValidator): Common.UnsignedTx;
1149
1124
  transferSubnetOwnershipTx({ utxoSet, subnetId, subnetAuth, subnetOwners, feeState, fromAddresses, options, threshold, locktime, }: TransferSubnetOwnershipTx): Common.UnsignedTx;
1150
- transformSubnetTx(utxoSet: utils.UtxoSet, subnetId: string, assetId: string, initialSupply: bigint, maximumSupply: bigint, minConsumptionRate: bigint, maxConsumptionRate: bigint, minValidatorStake: bigint, maxValidatorStake: bigint, minStakeDuration: number, maxStakeDuration: number, minDelegationFee: number, minDelegatorStake: bigint, maxValidatorWeightFactor: number, uptimeRequirement: number, subnetAuth: number[], fromAddresses?: string[], options?: Common.SpendOptions): Common.UnsignedTx;
1151
1125
  protected constructor(provider: AbstractProvider);
1152
1126
  }
1153
1127
 
@@ -1786,7 +1760,7 @@ declare const P_CHAIN_TX_SIZE_LIMIT = 65536;
1786
1760
  * @returns the largest prefix of sorted `utxos` before hitting the size limit. If no such prefix exists, then an empty array.
1787
1761
  */
1788
1762
  declare function getMaximumUtxoSet({ wallet, utxos, sizeSupportedTx, limit, feeState, }: {
1789
- wallet: WalletAbstract$1;
1763
+ wallet: WalletAbstract;
1790
1764
  utxos: Utxo[];
1791
1765
  sizeSupportedTx: SizeSupportedTx;
1792
1766
  limit?: number;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@avalabs/avalanchejs"),i=require("hdkey"),o=require("buffer"),d=require("@openzeppelin/contracts/build/contracts/ERC20.json"),u=require("bip32"),c=require("bip39"),l=require("@ledgerhq/hw-transport"),p=require("@metamask/eth-sig-util"),h=require("ledger-bitcoin"),g=require("@ledgerhq/hw-app-btc/lib/bip32"),m=require("@noble/hashes/sha256"),f=require("@avalabs/glacier-sdk"),x=require("@avalabs/core-chains-sdk"),v=require("create-hash"),w=require("xss"),A=require("bip32-path"),b=require("@avalabs/hw-app-avalanche");function y(e){return e.reduce(((e,t)=>e+t.value),0)}class I{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:y(r.confirmed),balanceUnconfirmed:y(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function T(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 S(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 B(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function P(e,t,r,s,n,a){const i=S(e,t,r,s,B(n));return i.inputs?{...i,psbt:T(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function C(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function E(e){return new s(e,"w0w")}const k="m/44'/60'",D=`${k}/0'`;var V=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(V||{});function M(e,t,r){if(e<0)throw new Error("Account index can not be less than 0.");const s="EVM"===r?"60":"9000";return t==V.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const O=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),U=(e,t)=>{const r=new n.Interface(d.abi).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var K=[{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 N extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#e="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#e.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#e,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,K,this._parentProvider),this._maxCalls=62)}#e;#t=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#e.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function _(e,t){return u.fromBase58(e).derivePath(`0/${t}`).publicKey}let F=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=M(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=E(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=E(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,a=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof l.TransportStatusError&&s.statusCode===l.StatusCodes.INS_NOT_SUPPORTED){const s=p.TypedDataUtils.hashStruct(i,r,t,p.SignTypedDataVersion.V4),a=p.TypedDataUtils.hashStruct("EIP712Domain",e,t,p.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 X(t,r,s,n,a,i){const o=new h.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,g.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function L(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 H{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 C(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 P(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class R extends H{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=V.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await c.mnemonicToSeed(e),a=u.fromSeed(n),i=M(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new R(o.privateKey,r)}signTx(e,t){const r=T(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 R(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}var $=(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))($||{});const q=e=>{switch(e){case"C":return a.EVM;case"X":return a.AVM;case"P":return a.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:W,AddressMaps:j}=a.utils,J=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const i=W(e);let o=j.fromTransferableInputs(i,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>a.pvmSerial.isCreateChainTx(e)||a.pvmSerial.isAddSubnetValidatorTx(e)||a.pvmSerial.isRemoveSubnetValidatorTx(e)||a.pvmSerial.isTransformSubnetTx(e)||a.pvmSerial.isTransferSubnetOwnershipTx(e)||a.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),i=a.OutputOwners.fromNative(n.controlKeys.map((e=>a.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new a.utils.AddressMap(i)),r})({tx:e,provider:r,addressMaps:o});return new a.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else a.pvmSerial.isDisableL1ValidatorTx(e)&&(o=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),i=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new a.utils.AddressMap(i)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(o,e,r));return new a.UnsignedTx(e,n,o,s)},{bufferToHex:z,packTx:Y}=a.utils,{publicKeyBytesToAddress:G,recoverPublicKey:Q}=a.secp256k1,Z=new a.Signature(new Uint8Array(Array(65).fill(0))),ee=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(Z);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=Y(n.getTx()),d=m.sha256(o),u=Z.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=Q(d,e.toBytes()),r={toHex:()=>z(G(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function te(e){return a.utils.bufferToHex(a.utils.addChecksum(e.toBytes()))}const{getManagerForVM:re,hexToBuffer:se,unpackWithManager:ne}=a.utils,ae=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=q(t);if(n===a.EVM)throw new Error("EVM transactions are not supported");const i=se(e),o=ne(n,i),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const i=re(s).unpack(t,a.avaxSerial.SignedTx),o=await J({tx:e,utxos:n,provider:r,credentials:i.getCredentials()});return e.getSigIndices().map(((e,t)=>new a.Credential(ee(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new a.Credential(ee(e))))}})({tx:o,txBytes:i,provider:r,vm:n,utxos:s});return J({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:ie,format:oe}=a.utils,{publicKeyBytesToAddress:de}=a.secp256k1;class ue{constructor(e,t,r){this.baseUrl=e,this.context=t,this.upgradesInfo=r;const s=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(s)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}isEtnaEnabled(){return!!this.upgradesInfo&&a.utils.isEtnaEnabled(this.upgradesInfo)}getUpgradesInfo(){return this.upgradesInfo}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return a.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new a.avm.AVMApi(this.baseUrl)}getApiP(){return new a.pvm.PVMApi(this.baseUrl)}getApiC(){return new a.evm.EVMApi(this.baseUrl)}getInfo(){return new a.info.InfoApi(this.baseUrl)}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=de(a);return oe(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return oe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ie(e);return oe(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=te(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,i)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&i(new Error("Timeout")),d=s instanceof a.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),d.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{o()}),1e3)}};o()}))}}const ce={weights:a.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},le={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e9),transformSubnetTxFee:BigInt(1e10),createBlockchainTxFee:BigInt(1e9),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:1,hrp:"avax",platformFeeConfig:ce},pe={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e8),transformSubnetTxFee:BigInt(1e9),createBlockchainTxFee:BigInt(1e8),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:5,hrp:"fuji",platformFeeConfig:ce},he={addPrimaryNetworkDelegatorFee:0n,addPrimaryNetworkValidatorFee:0n,addSubnetDelegatorFee:1000000n,addSubnetValidatorFee:1000000n,avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",createAssetTxFee:1000000n,createBlockchainTxFee:100000000n,createSubnetTxFee:100000000n,hrp:"custom",networkID:76,pBlockchainID:"11111111111111111111111111111111LpoYY",transformSubnetTxFee:100000000n,xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",platformFeeConfig:ce};class ge extends ue{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await a.Context.getContextFromURI(e);try{const r=await new a.info.InfoApi(e).getUpgradesInfo();return new ge(e,t,r)}catch{return new ge(e,t)}}static getDefaultMainnetProvider(e){return new ge(x.AVALANCHE_XP_NETWORK.rpcUrl,le,e)}static getDefaultFujiProvider(e){return new ge(x.AVALANCHE_XP_TEST_NETWORK.rpcUrl,pe,e)}static getDefaultDevnetProvider(e){return new ge(x.AVALANCHE_P_DEV_NETWORK.rpcUrl,he,e)}}const{bytesCompare:me,parseBech32:fe}=a.utils,xe=(e,t)=>"P"===t,ve=(e,t,r)=>{const s=xe(0,t)?e.amount:e.asset?.amount;return new a.TransferOutput(new a.BigIntPr(BigInt(s)),a.OutputOwners.fromNative(e.addresses.map((e=>fe(e)[1])).sort(me),BigInt(r??0),e.threshold))},we=(e,t)=>{const r=((e,t)=>{const r=t===f.Network.FUJI,s=t===f.Network.DEVNET,{cBlockchainID:n,xBlockchainID:a,pBlockchainID:i}=s?he:r?pe:le;if(n===e)return"C";if(a===e)return"X";if(i===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=xe(0,r)?e.txHash:e.creationTxHash,n=xe(0,r)?e.assetId:e.asset?.assetId;return new a.Utxo(a.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),a.Id.fromString(n),((e,t)=>xe(0,t)?e.stakeableLocktime?new a.pvmSerial.StakeableLockOut(new a.BigIntPr(BigInt(e.stakeableLocktime??0)),ve(e,t,e.platformLocktime??0)):ve(e,t,e.platformLocktime):ve(e,t,e.locktime))(e,r))},{unpackWithManager:Ae,parse:be,bufferToHex:ye,AddressMaps:Ie,AddressMap:Te}=a.utils;function Se(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return v("sha256").update(s).digest()}const Be=1024,Pe=1024;async function Ce(e,t,r){const s=e.slice(0,Be),n=e.slice(Be),a=await Ee(t,{...r,addresses:s});if(n.length){const s=await Ce(n,t,{...r,addresses:e});return a.merge(s)}return a}async function Ee(e,t){if(t.addresses.length>Be)throw new Error(`Can not get UTXOs for more than ${Be} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new a.utils.UtxoSet(s);if(s.length>=Pe){const s=await Ee(e,{...t,startIndex:r});return n.merge(s)}return n}function ke(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:De}=a.utils;async function Ve(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await Ve(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Me,hexToBuffer:Oe,unpackWithManager:Ue}=a.utils;function Ke(e,t=!0){try{if(t){const[t]=a.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else a.utils.parseBech32(e);return!0}catch(e){return!1}}const Ne=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),_e=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0)),Fe=e=>{if([le.xBlockchainID,pe.xBlockchainID,he.xBlockchainID].includes(e))return"AVM";if([le.pBlockchainID,pe.pBlockchainID,he.pBlockchainID].includes(e))return"PVM";if([le.cBlockchainID,pe.cBlockchainID,he.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")};var Xe={parseAddValidatorTx:e=>a.pvmSerial.isAddValidatorTx(e)?({feeData:t,assetId:r})=>({type:$.AddValidator,chain:e.getVM(),nodeID:e.validator.nodeId.value(),delegationFee:e.shares.value(),stake:Ne(e.stake,r),stakeOuts:e.stake,start:e.validator.startTime.value().toString(),end:e.validator.endTime.value().toString(),rewardOwner:e.getRewardsOwner(),...t}):null,parseAddDelegatorTx:e=>a.pvmSerial.isAddDelegatorTx(e)?({feeData:t,assetId:r})=>({type:$.AddDelegator,chain:e.getVM(),stake:Ne(e.stake,r),stakeOuts:e.stake,rewardOwner:e.getRewardsOwner(),nodeID:e.validator.nodeId.value(),start:e.validator.startTime.value().toString(),end:e.validator.endTime.value().toString(),...t}):null,parseCreateSubnetTx:e=>a.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:$.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>a.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:$.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>a.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:$.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>a.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:$.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>a.pvmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.evmSerial.isImportTx(e)?a.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:Fe(e.sourceChain.value()),amount:_e(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:Fe(e.sourceChain.value()),amount:_e(e.ins,r),...t}):null,parseExportTx:e=>a.pvmSerial.isExportTx(e)||a.avmSerial.isExportTx(e)||a.evmSerial.isExportTx(e)?a.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:Fe(e.destinationChain.toString()),amount:Ne(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:Fe(e.destination.value()),amount:Ne(e.outs,r),...t}):null,parseBaseTx:e=>a.avmSerial.isAvmBaseTx(e)||a.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,i=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),a.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof a.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof a.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),o=ke(),d=i.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:$.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!a.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return a.pvmSerial.isSigner(e.signer)&&(r=a.utils.bufferToHex(e.signer.proof.publicKey),t=a.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:$.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>a.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:$.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,parseTransformSubnetTx:e=>a.pvmSerial.isTransformSubnetTx(e)?({feeData:t})=>({type:$.TransformSubnet,chain:e.getVM(),subnetID:e.subnetID.toString(),assetID:e.assetId.toString(),initialSupply:e.initialSupply.value(),maximumSupply:e.maximumSupply.value(),minConsumptionRate:e.minConsumptionRate.value(),maxConsumptionRate:e.maxConsumptionRate.value(),minValidatorStake:e.minValidatorStake.value(),maxValidatorStake:e.maxValidatorStake.value(),minStakeDuration:e.minStakeDuration.value(),maxStakeDuration:e.maxStakeDuration.value(),minDelegationFee:e.minDelegationFee.value(),minDelegatorStake:e.minDelegatorStake.value(),maxValidatorWeightFactor:Number(e.maxValidatorWeightFactor.toJSON()),uptimeRequirement:e.uptimeRequirement.value(),...t}):null,parseTransferSubnetOwnershipTx:e=>a.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:$.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>a.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:$.ConvertSubnetToL1,chain:e.getVM(),managerAddress:n(a.Address.fromHex(e.address.toString("hex"))),validators:e.validators.map((e=>({nodeId:a.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>a.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:$.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>a.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:$.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>a.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:$.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>a.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:$.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:Le,getOutputAmounts:He,getInputAmounts:Re,validateBurnedAmount:$e}=a.utils;function qe(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 We(e){const t=ke(),r=e.map((e=>({utxo:e,...a.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),i=qe(s,["amount"],"desc"),o=qe(n,["stakeableLocktime","amount"],"desc"),[d,...u]=i;return[...d?[d]:[],...o,...u].map((e=>e.utxo))}function je(e,t){return qe(e.map((e=>({utxo:e,...a.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const Je=e=>je(e,!0),ze=e=>je(e,!1);const{getUtxoInfo:Ye}=a.utils;var Ge=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Ge||{});const Qe="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",Ze="11111111111111111111111111111111LpoYY",et=(e,t)=>e.reduce(((e,t)=>e+Ye(t).amount),BigInt(0))-t,tt={BaseP:{sortFunction:Je,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new a.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:et(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:ze,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new a.utils.UtxoSet(t),amount:et(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:We,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new a.utils.UtxoSet(t),nodeId:Qe,start:ke(),end:ke()+BigInt(1e3),weight:et(t,e.getProvider().getContext().baseTxFee),subnetId:Ze,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(a.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(a.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:We,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new a.utils.UtxoSet(t),nodeId:Qe,start:ke(),end:ke()+BigInt(1e3),weight:et(t,e.getProvider().getContext().baseTxFee),subnetId:Ze,feeState:r})},ExportP:{sortFunction:Je,unsignedTxBuilder:(e,t,r)=>e.exportP({amount:et(t,e.getProvider().getContext().baseTxFee),utxoSet:new a.utils.UtxoSet(t),destination:"X",feeState:r})},ImportP:{sortFunction:Je,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new a.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function rt(e){return A.validateString(e,!0)&&6===e.split("/").length}function st(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:nt,hexToBuffer:at}=a.utils,it=new Error("Tx type is not supported post-etna");class ot{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Ce(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Ve(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 Ce(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=nt(s)[2],i=this.provider.getAvaxID(),o=a.TransferableOutput.fromNative(i,e,[n]),d=je(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>nt(e)[2])),l=nt(this.getChangeAddress("X"))[2];return a.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:i}){const o=this.provider.getChainID(t),d=this.getAddresses("P").map((e=>nt(e)[2])),u=nt(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const c=nt(r)[2],l=e.getUTXOs();if(this.provider.isEtnaEnabled()){if(!n)throw new Error("feeState parameter is required post E-upgrade");return a.pvm.e.newImportTx({fromAddressesBytes:d,utxos:l,toAddressesBytes:[c],sourceChainId:o,threshold:s,feeState:n,locktime:i},this.provider.getContext())}return a.pvm.newImportTx(this.provider.getContext(),o,l,[c],d,{changeAddresses:[u]})}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>nt(e)[2])),i=nt(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=nt(r)[2];return a.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[i]})}importC(e,r,s,n,i){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>nt(e)[2]));i=i||this.getAddressEVM();const u=Buffer.from(t.strip0x(i),"hex");return a.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const i=at(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=nt(n)[2],u=s/BigInt(1e9);return a.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,i,[d],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const i=nt(n)[2],o=this.provider.getAvaxID(),d=a.TransferableOutput.fromNative(o,e,[i]),u=je(t.getUTXOs(),!0),c=this.provider.getChainID(r),l=this.getAddresses("P").map((e=>nt(e)[2])),p=nt(this.getChangeAddress("P"))[2];return this.provider.isEtnaEnabled()?(st(s),a.pvm.e.newExportTx({changeAddressesBytes:[p],fromAddressesBytes:l,utxos:u,outputs:[d],destinationChainId:c,feeState:s},this.provider.getContext())):a.pvm.newExportTx(this.provider.getContext(),c,l,u,[d],{changeAddresses:[p]})}addValidator(e,t,r,s,n,i,o){const d=We(e.getUTXOs()),u=this.getAddresses("P").map((e=>nt(e)[2])),c=o?.rewardAddress||this.getCurrentAddress("P"),l=nt(c)[2],p=nt(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw it;return a.pvm.newAddValidatorTx(this.provider.getContext(),d,u,t,s,n,r,[l],i,{changeAddresses:[p]})}addDelegator(e,t,r,s,n,i){const o=We(e.getUTXOs()),d=this.getAddresses("P").map((e=>nt(e)[2])),u=i?.rewardAddress||this.getCurrentAddress("P"),c=nt(u)[2],l=nt(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw it;return a.pvm.newAddDelegatorTx(this.provider.getContext(),o,d,t,s,n,r,[c],{changeAddresses:[l]})}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const i=ze(e.getUTXOs());s=s??this.getCurrentAddress("P");const o=nt(s)[2],d=this.provider.getContext(),u=[a.TransferableOutput.fromNative(d.avaxAssetID,t,[o])],c=this.getAddresses("P").map((e=>nt(e)[2])),l=nt(this.getChangeAddress("P"))[2],p=n?.changeAddresses??[l];return this.provider.isEtnaEnabled()?(st(r),a.pvm.e.newBaseTx({changeAddressesBytes:p,fromAddressesBytes:c,utxos:i,outputs:u,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},d)):a.pvm.newBaseTx(this.provider.getContext(),c,i,u,n)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:i,fromAddresses:o}){const[d,u,c]=nt(r);if(d!==t||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const l=Object.entries(s).map((([e,t])=>a.TransferableOutput.fromNative(e,t,[c]))),p=je(e.getUTXOs(),!0),h=(o??this.getAddresses(t)).map((e=>nt(e)[2])),g=nt(this.getChangeAddress("P"))[2],m=i?.changeAddresses??[g];return"X"===t?a.avm.newBaseTx(this.provider.getContext(),h,p,l,i):this.provider.isEtnaEnabled()?(st(n),a.pvm.e.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:h,utxos:p,outputs:l,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:n},this.provider.getContext())):a.pvm.newBaseTx(this.provider.getContext(),h,p,l,i)}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:i,validators:o,options:d,fromAddresses:u}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const c=(u??this.getAddresses("P")).map((e=>nt(e)[2])),l=nt(this.getChangeAddress("P"))[2],p=d?.changeAddresses??[l],h=o.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:i,remainingBalanceOwner:o})=>{const d=new a.pvmSerial.ProofOfPossession(Uint8Array.from(a.utils.hexToBuffer(t)),Uint8Array.from(a.utils.hexToBuffer(r))),u=a.PChainOwner.fromNative(o.addresses.map((e=>nt(e)[2])),o.threshold??1),c=a.PChainOwner.fromNative(i.addresses.map((e=>nt(e)[2])),i.threshold??1);return a.L1Validator.fromNative(e,n,s,d,u,c)}));return a.pvm.e.newConvertSubnetToL1Tx({changeAddressesBytes:p,validators:h,fromAddressesBytes:c,address:nt(i)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:je(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:i,options:o}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const d=(i??this.getAddresses("P")).map((e=>nt(e)[2])),u=nt(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[u];return a.pvm.e.newRegisterL1ValidatorTx({utxos:je(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(a.utils.hexToBuffer(r)),changeAddressesBytes:c,feeState:n,fromAddressesBytes:d,memo:o?.memo,message:Uint8Array.from(a.utils.hexToBuffer(s)),minIssuanceTime:o?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(n??this.getAddresses("P")).map((e=>nt(e)[2])),o=nt(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return a.pvm.e.newSetL1ValidatorWeightTx({utxos:je(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,message:Uint8Array.from(a.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const o=(s??this.getAddresses("P")).map((e=>nt(e)[2])),d=nt(this.getChangeAddress("P"))[2],u=r?.changeAddresses??[d];return a.pvm.e.newDisableL1ValidatorTx({disableAuth:n,validationId:i,utxos:je(e.getUTXOs(),!0),changeAddressesBytes:u,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const o=(s??this.getAddresses("P")).map((e=>nt(e)[2])),d=nt(this.getChangeAddress("P"))[2],u=r?.changeAddresses??[d];return a.pvm.e.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:i,utxos:je(e.getUTXOs(),!0),changeAddressesBytes:u,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:i,subnetAuth:o,feeState:d,options:u,fromAddresses:c}){const l=je(e.getUTXOs(),!0),p=(c??this.getAddresses("P")).map((e=>nt(e)[2])),h=nt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[h];return this.provider.isEtnaEnabled()?(st(d),a.pvm.e.newCreateChainTx({chainName:r,feeState:d,fromAddressesBytes:p,fxIds:n,genesisData:i,subnetAuth:o,subnetId:t,utxos:l,vmId:s,changeAddressesBytes:g},this.provider.getContext())):a.pvm.newCreateBlockchainTx(this.provider.getContext(),l,p,t,r,s,n,i,o,u)}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:i,locktime:o}){const d=je(e.getUTXOs(),!0),u=(s??this.getAddresses("P")).map((e=>nt(e)[2])),c=nt(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c],p=t.map((e=>nt(e)[2]));return this.provider.isEtnaEnabled()?(st(r),a.pvm.e.newCreateSubnetTx({fromAddressesBytes:u,changeAddressesBytes:l,utxos:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:i,locktime:o,subnetOwners:p},this.provider.getContext())):a.pvm.newCreateSubnetTx(this.provider.getContext(),d,u,p,n,i??1,o??BigInt(0))}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d,fromAddresses:u,options:c}){const l=je(e.getUTXOs(),!0),p=(u??this.getAddresses("P")).map((e=>nt(e)[2])),h=nt(this.getChangeAddress("P"))[2],g=c?.changeAddresses??[h];return this.provider.isEtnaEnabled()?(st(d),a.pvm.e.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:p,utxos:l,minIssuanceTime:c?.minIssuanceTime,memo:c?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d},this.provider.getContext())):a.pvm.newAddSubnetValidatorTx(this.provider.getContext(),l,p,t,r,s,n,i,o,c)}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,fromAddresses:u,rewardAddresses:c,delegatorRewardAddresses:l,publicKey:p,signature:h,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=We(e.getUTXOs()),w=(u??this.getAddresses("P")).map((e=>nt(e)[2])),A=(c??[this.getCurrentAddress("P")]).map((e=>nt(e)[2])),b=(l??[this.getCurrentAddress("P")]).map((e=>nt(e)[2]));if(!(i!==a.networkIDs.PrimaryNetworkID.toString()||p&&h))throw new Error("Must provide public key and signature for primary subnet.");const y=nt(this.getChangeAddress("P"))[2],I=g?.changeAddresses??[y];if(this.provider.isEtnaEnabled())return st(d),a.pvm.e.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:b,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:I,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,publicKey:p,rewardAddresses:A,signature:h,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext());const T={changeAddresses:[y],...g??{}};return a.pvm.newAddPermissionlessValidatorTx(this.provider.getContext(),v,w,t,i,r,s,n,A,b,o,T,void 0,void 0,p,h)}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,fromAddresses:o,rewardAddresses:d,options:u,locktime:c,feeState:l,threshold:p,stakingAssetId:h}){const g=We(e.getUTXOs()),m=(o??this.getAddresses("P")).map((e=>nt(e)[2])),f=(d??[this.getCurrentAddress("P")]).map((e=>nt(e)[2])),x=nt(this.getChangeAddress("P"))[2],v=u?.changeAddresses??[x];if(this.provider.isEtnaEnabled())return st(l),a.pvm.e.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,changeAddressesBytes:v,nodeId:t,start:r,end:s,weight:n,subnetId:i,rewardAddresses:f,locktime:c,stakingAssetId:h,threshold:p,feeState:l},this.provider.getContext());const w={changeAddresses:[x],...u??{}};return a.pvm.newAddPermissionlessDelegatorTx(this.provider.getContext(),g,m,t,i,r,s,n,f,w,void 0,void 0)}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:i,options:o}){const d=je(e.getUTXOs(),!0),u=(n??this.getAddresses("P")).map((e=>nt(e)[2])),c=nt(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c];return this.provider.isEtnaEnabled()?(st(i),a.pvm.e.newRemoveSubnetValidatorTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:d,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:i},this.provider.getContext())):a.pvm.newRemoveSubnetValidatorTx(this.provider.getContext(),d,u,t,r,s,o)}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:i,options:o,threshold:d,locktime:u}){const c=je(e.getUTXOs(),!0),l=(i??this.getAddresses("P")).map((e=>nt(e)[2])),p=nt(this.getChangeAddress("P"))[2],h=o?.changeAddresses??[p],g=s.map((e=>nt(e)[2]));return this.provider.isEtnaEnabled()?(st(n),a.pvm.e.newTransferSubnetOwnershipTx({changeAddressesBytes:h,fromAddressesBytes:l,utxos:c,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:d,locktime:u},this.provider.getContext())):a.pvm.newTransferSubnetOwnershipTx(this.provider.getContext(),c,l,t,r,g,o,d??1,u??BigInt(0))}transformSubnetTx(e,t,r,s,n,i,o,d,u,c,l,p,h,g,m,f,x,v){const w=je(e.getUTXOs(),!0),A=(x??this.getAddresses("P")).map((e=>nt(e)[2]));if(this.provider.isEtnaEnabled())throw it;return a.pvm.newTransformSubnetTx(this.provider.getContext(),w,A,t,r,s,n,i,o,d,u,c,l,p,h,g,m,f,v)}}class dt extends ot{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 dt(o,d,s)}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!rt(r)||!rt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return dt.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 ut={type:"zondax",getApp:e=>new b(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 ct(e){return!(await ut.getVersion(e)>="0.6.0")}const{parse:lt}=a.utils;class pt extends ot{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new dt(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath(M(0,V.BIP44,"EVM")).neutered();return new pt(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(lt(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(lt(e)[2])))}getRawAddressC(){return Buffer.from(lt(this.getCurrentAddress("C"))[2])}}const{isTransferOut:ht,isStakeableLockOut:gt}=a.utils;function mt(e){const t=e.output;return ht(t)||gt(t)?t.getOwners():[]}function ft(e){const t=e.getTx();return a.avmSerial.isExportTx(t)||a.pvmSerial.isExportTx(t)?new Set(t.outs.map(mt).flat()):a.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(mt).flat()):new Set((t.baseTx?.outputs??[]).map(mt).flat())}const{parse:xt}=a.utils;class vt extends pt{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]=xt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await ct(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=E(e),a=await ut.getXPUB(e,vt.getAccountPath("X")),i=u.fromPublicKey(a.pubKey,a.chainCode),o=M(0,V.BIP44,"EVM"),d=await s.getAddress(o,!1),c=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new vt(i.toBase58(),l,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>A.fromString(e))),l=[...ft(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>A.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=A.fromString(vt.getAccountPath(e.chain));return[...(await ut.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:wt}=a.utils;class At extends pt{constructor(e,t,r){const s=u.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(wt(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=u.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath(M(0,V.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new At(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:bt,sign:yt,signHash:It}=a.secp256k1,{addChecksum:Tt}=a.utils;class St extends dt{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(bt(e)),Buffer.from(bt(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!rt(r)||!rt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(t),o=a.derivePath(r);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new St(i.privateKey,o.privateKey,s)}async signMessage(e){const t=Se(e.message),r=this.getSigningKey(e.chain);return Buffer.from(Tt(await It(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await yt(e.buffer,t))]}}const{strip0x:Bt}=a.utils;class Pt extends dt{constructor(e,t,r,s,i){const o=a.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=a.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),i),this.pathXP=t,this.pathC=s,!rt(t)||!rt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await ct(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!rt(t)||!rt(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(Bt(o.publicKey),"hex"),c=Buffer.from(Bt(d.publicKey),"hex"),l=Buffer.from(Bt(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Bt(n.SigningKey.computePublicKey(c,!0)),"hex");return new Pt(p,t,l,r,a)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=A.fromString(this.getAccountPath(e.chain)),r=A.fromString(this.getPartialSignerPath(e.chain));return[...(await ut.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Ct}=a.utils;var Et=Object.freeze({__proto__:null,AbstractProvider:ue,AddressWallet:class extends ot{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=>!Ke(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!Ke(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(!Ke(e,!1))throw new Error("Given address must be valid avalanche bech32 addresses without the chain alias prefix");this.xpChangeAddress=e}getAddressEVM(){return this.addressC}getAddresses(e){return("C"===e?[this.addressCoreEth]:this.xpAddresses).map((t=>this.provider.formatAddress(t,e)))}getChangeAddress(e){const t="C"===e?this.addressCoreEth:this.xpChangeAddress;return this.provider.formatAddress(t,e)}getCurrentAddress(e){const t="C"===e?this.addressCoreEth:this.xpAddresses[0];return this.provider.formatAddress(t,e)}},DevnetContext:he,FujiContext:pe,JsonRpcProvider:ge,LedgerSigner:Pt,LedgerWallet:vt,MainnetContext:le,MnemonicWallet:At,MnemonicWalletVoid:pt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=u.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof a.EVMUnsignedTx||"C"===t?a.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):a.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Ct(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?[A.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(A.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([...ft(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=A.fromString(this.getAccountPath(e.chain));return[...(await ut.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||A.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=Se(e.message),s=(await ut.signHash(e.transport,r,A.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(M(t,V.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),i=this.getSigningKeys(n,r,s);if(!i?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await a.addTxSignatures({unsignedTx:t,privateKeys:i}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=Se(e.message),s=await a.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Ge,StaticSigner:St,TxType:$,WalletAbstract:ot,WalletVoid:dt,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const i=await ae({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>i.addSignature(e))));const o=i.getCredentials(),d=i.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=o[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new a.Credential(s)),e}),[]),u=new a.UnsignedTx(i.getTx(),i.getInputUtxos(),i.addressMaps,d);return{signedTxHex:te(new a.avaxSerial.SignedTx(i.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:we,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=Ae(r,e),i=be(t)[2],o=ye(i);if(a.evmSerial.isExportTx(n))return new a.EVMUnsignedTx(n,[],new Ie([Te.fromJSON([[o,0]])]));if(a.evmSerial.isImportTx(n)){const e=Ie.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new a.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:J,digestMessage:Se,emptySignature:Z,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=u.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(i,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return u.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=ke();return n.forEach((e=>{const t=De(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 ut},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=tt[r],o=ke(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=Ye(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*Ye(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(Ye)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:Ee,getPchainUnixNow:async function(e){const t=e?x.AVALANCHE_XP_TEST_NETWORK.rpcUrl:x.AVALANCHE_XP_NETWORK.rpcUrl,r=await new a.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:Ve,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[a.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Ce,getUnixNow:ke,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:i})=>{const o=q(t),d=Oe(e),u=Ue(o,d);if(a.evmSerial.isExportTx(u))return[];const c=(e=>{if(a.evmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case a.EVM:return f.BlockchainId.C_CHAIN;case a.AVM:return f.BlockchainId.X_CHAIN;case a.PVM:return f.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Me(u),p=new f.Glacier({BASE:s,TOKEN:n,HEADERS:i}),h=[...new Set(l.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(h.map((e=>p.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:r,txHash:e}))));return l.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=we(n,r);return e.push(a),e}),[])},getVmByChainAlias:q,getXpubFromMnemonic:function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=c.mnemonicToSeedSync(e);return u.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:Ke,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:ct,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50}={}){try{const n=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(Xe)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=Le(i,n),u=He(i),c=Re(i).get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0),p=u.get(n.avaxAssetID)??BigInt(0);let h,g=BigInt(0);a.evmSerial.isImportExportTx(i)?g=await t.getApiC().getBaseFee()/BigInt(1e9):"PVM"===i.vm&&(h=t.getUpgradesInfo(),g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0))));const{isValid:m,txFee:f}=$e({upgradesInfo:h,unsignedTx:e,context:n,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:p,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f},assetId:n.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:$.Unknown}}},populateCredential:ee,signedTxToHex:te,sortUTXOsByAmount:je,sortUTXOsByAmountAscending:ze,sortUTXOsByAmountDescending:Je,sortUTXOsStaking:We,verifyDerivationPath:rt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Et,exports.BitcoinLedgerWallet=class extends H{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 h(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=X(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=L(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 I{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.#r=new t.HttpClient(s||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#s=new t.HttpClient(n||d,i)}#r;#s;async#n(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#s.post("",e,{},this.extraParams))))).flat():this.#s.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#r.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,r){const s=await this.#r.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.#s.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.#n(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.#r.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.#s.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.#n([{...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.#s.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#r.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.#r.post(`/api/v2/address/${e}`,{},{},this.extraParams);return await Promise.allSettled(t.txids?.slice(0,25).map((async t=>{try{const r=await this.#r.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=I,exports.BitcoinWallet=R,exports.BitcoinWalletAbstract=H,exports.BitcoinWalletVoid=class extends H{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=V,exports.ETH_ACCOUNT_PATH=D,exports.ETH_COIN_PATH=k,exports.JsonRpcBatchInternal=N,exports.LedgerSigner=F,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.createPSBTV2=X,exports.createPsbt=T,exports.createTransferTx=P,exports.createWalletPolicy=function(e,t,r,s){const n=new h.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new h.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=M,exports.getAddressFromXPub=function(e,t){const r=_(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=u.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=_,exports.getAppEth=E,exports.getBech32Address=C,exports.getBech32AddressFromXPub=function(e,t,r){return C(_(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return C(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=E(e),n=await s.getAddress(r??D,t,!0),a=new i;return a.publicKey=o.Buffer.from(n.publicKey,"hex"),a.chainCode=o.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=y(e);if(!n)return 0;const{fee:a}=S(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=E(e),a=M(t,r,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(a.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getTransferTxDetails=function(e,t,r,s,n){const a=S(e,t,r,s,B(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),M(t,r,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await c.mnemonicToSeed(e);return u.fromSeed(t).derivePath(D).neutered().toBase58()},exports.isERC20Transfer=U,exports.isNativeTxn=O,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())&&U(e,n)?s(e,{type:"erc20",contractAddress:e.to}):O(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=L,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=S;
1
+ "use strict";var e=require("bitcoinjs-lib"),t=require("@avalabs/core-utils-sdk"),r=require("coinselect"),s=require("@ledgerhq/hw-app-eth"),n=require("ethers"),a=require("@avalabs/avalanchejs"),i=require("hdkey"),o=require("buffer"),d=require("@openzeppelin/contracts/build/contracts/ERC20.json"),u=require("bip32"),c=require("bip39"),l=require("@ledgerhq/hw-transport"),h=require("@metamask/eth-sig-util"),p=require("ledger-bitcoin"),g=require("@ledgerhq/hw-app-btc/lib/bip32"),m=require("@noble/hashes/sha256"),f=require("@avalabs/glacier-sdk"),x=require("@avalabs/core-chains-sdk"),v=require("create-hash"),w=require("xss"),A=require("bip32-path"),y=require("@avalabs/hw-app-avalanche");function b(e){return e.reduce(((e,t)=>e+t.value),0)}class I{async getUtxoBalance(e,t=!0){const r=await this.getUTXOs(e,t);return{balance:b(r.confirmed),balanceUnconfirmed:b(r.unconfirmed),utxos:r.confirmed,utxosUnconfirmed:r.unconfirmed}}}function T(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 S(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 P(e){const t=[];return e.filter((e=>{const r=e.txHash+e.index.toString();return!t.includes(r)&&(t.push(r),!0)}))}function B(e,t,r,s,n,a){const i=S(e,t,r,s,P(n));return i.inputs?{...i,psbt:T(i.inputs,i.outputs,a)}:(console.log("Unable to construct transaction, fee needed: ",i.fee),i)}function C(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function E(e){return new s(e,"w0w")}const k="m/44'/60'",V=`${k}/0'`;var D=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(D||{});function M(e,t,r){if(e<0)throw new Error("Account index can not be less than 0.");const s="EVM"===r?"60":"9000";return t==D.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const U=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),K=(e,t)=>{const r=new n.Interface(d.abi).parseTransaction({data:e.data,value:e.value});if(t.has(e.from.toLowerCase()))return!0;if("transfer"===r?.name)return t.has(r.args[0]?.toLowerCase());if("transferFrom"===r?.name){const e=t.has(r.args[0]?.toLowerCase()),s=t.has(r.args[1]?.toLowerCase());return e||s}return!1};var O=[{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 N extends n.JsonRpcProvider{url;constructor(e,t,r){super(t,r,{staticNetwork:r}),this.#e="string"==typeof t?new n.FetchRequest(t):void 0===t?new n.FetchRequest("http://localhost:8545"):t.clone(),this.url=this.#e.url,this._maxCalls="number"==typeof e?e:e.maxCalls,"number"!=typeof e&&e?.multiContractAddress&&(this._parentProvider=new n.JsonRpcProvider(this.#e,r,{staticNetwork:r}),this._multicallContract=new n.Contract(e.multiContractAddress,O,this._parentProvider),this._maxCalls=62)}#e;#t=1;_pendingBatchAggregator=null;_pendingBatch=[];_maxCalls;_parentProvider;_multicallContract;send(e,t){if("eth_call"!==e)return super.send(e,t);const r={method:e,params:t,id:this.#t++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const s={request:r,resolve:null,reject:null},n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return this._pendingBatch.push(s),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout(this.flush,10)),n}flush=()=>{const e=this._pendingBatch?.slice(0,this._maxCalls)??[];!this._pendingBatch||this._pendingBatch?.length<=this._maxCalls?(this._pendingBatch=null,this._pendingBatchAggregator=null):(this._pendingBatch.splice(0,this._maxCalls),setTimeout(this.flush,10));(this._multicallContract?this.batchSendMultiCall:this.batchSend)(e).then((t=>{e?.forEach(((e,r)=>{const s=t[r];if(s.error){const t=new Error(s.error.message);t.code=s.error.code,t.data=s.error.data,e.reject(t)}else e.resolve(s.result)}))})).catch((t=>{e?.forEach((e=>{e.reject(t)}))}))};batchSend=async e=>{const t=e?.map((e=>e.request));if(!this.url||!t)throw new Error("No url");const r=this.#e.clone();r.body=t;return(await r.send()).bodyJson};batchSendMultiCall=async e=>{const t=e.map((e=>({callData:e.request.params[0].data,target:e.request.params[0].to})));return(await this._multicallContract.aggregate(t))[1].map((e=>({result:e})))}}function _(e,t){return u.fromBase58(e).derivePath(`0/${t}`).publicKey}let X=class e extends n.AbstractSigner{type="default";path;provider=null;accountIndex;derivationSpec;transport;_eth;constructor(e=0,t,r,s){super(),this.path=M(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=E(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=E(e),this.transport=e}async getAddress(){const e=await this._eth.getAddress(this.path);return n.getAddress(e.address)}async signMessage(e){"string"==typeof e&&(e=n.toUtf8Bytes(e));const t=n.hexlify(e).substring(2),r=await this._eth.signPersonalMessage(this.path,t);return r.r="0x"+r.r,r.s="0x"+r.s,n.Signature.from(r).serialized}async signTransaction(e){const t=await this.populateTransaction(e);delete t.from;const r=n.Transaction.from(t),s=r.unsignedSerialized,a=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+a.v),r:"0x"+a.r,s:"0x"+a.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...a}=t,i=n.TypedDataEncoder.getPrimaryType(a);try{const s=await this._eth.signEIP712Message(this.path,{domain:{name:e.name||void 0,chainId:e.chainId?Number(e.chainId):void 0,version:e.version||void 0,verifyingContract:e.verifyingContract||void 0,salt:e.salt?.toString()||void 0},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],...t},primaryType:i,message:r});return s.r="0x"+s.r,s.s="0x"+s.s,n.Signature.from(s).serialized}catch(s){if(s instanceof l.TransportStatusError&&s.statusCode===l.StatusCodes.INS_NOT_SUPPORTED){const s=h.TypedDataUtils.hashStruct(i,r,t,h.SignTypedDataVersion.V4),a=h.TypedDataUtils.hashStruct("EIP712Domain",e,t,h.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,a.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function L(t,r,s,n,a,i){const o=new p.PsbtV2;return o.setGlobalPsbtVersion(2),o.setGlobalTxVersion(2),o.setGlobalInputCount(t.length),o.setGlobalOutputCount(r.length),t.forEach(((e,t)=>{if(!e.txHex)throw new Error("Input tx hex is not given");o.setInputPreviousTxId(t,Buffer.from(e.txHash,"hex").reverse()),o.setInputOutputIndex(t,e.index),o.setInputNonWitnessUtxo(t,Buffer.from(e.txHex,"hex")),o.setInputWitnessUtxo(t,e.value,Buffer.from(e.script,"hex")),o.setInputBip32Derivation(t,a,n,g.pathStringToArray(i))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function F(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 H{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 C(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 B(e,this.getAddressBech32(),t,r,s,this.provider.getNetwork())}}class R extends H{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=D.BIP44){if(t<0)throw new Error("Account index must be >= 0");if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const n=await c.mnemonicToSeed(e),a=u.fromSeed(n),i=M(t,s,"EVM"),o=a.derivePath(i);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new R(o.privateKey,r)}signTx(e,t){const r=T(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 R(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}var $=(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))($||{});const q=e=>{switch(e){case"C":return a.EVM;case"X":return a.AVM;case"P":return a.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}};const{getTransferableInputsByTx:W,AddressMaps:j}=a.utils,J=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const i=W(e);let o=j.fromTransferableInputs(i,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>a.pvmSerial.isCreateChainTx(e)||a.pvmSerial.isAddSubnetValidatorTx(e)||a.pvmSerial.isRemoveSubnetValidatorTx(e)||a.pvmSerial.isTransformSubnetTx(e)||a.pvmSerial.isTransferSubnetOwnershipTx(e)||a.pvmSerial.isConvertSubnetToL1Tx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=await t.getApiP().getSubnet({subnetID:e.getSubnetID().value()}),i=a.OutputOwners.fromNative(n.controlKeys.map((e=>a.utils.parse(e)[2])),BigInt(n.locktime),Number(n.threshold)).addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new a.utils.AddressMap(i)),r})({tx:e,provider:r,addressMaps:o});return new a.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}else a.pvmSerial.isDisableL1ValidatorTx(e)&&(o=await async function(e,t,r){try{const{deactivationOwner:s}=await r.getApiP().getL1Validator(t.validationId.toString()),n=t.getDisableAuth().values(),i=s.addresses.reduce(((e,t,r)=>(n.includes(r)&&e.push([t,r]),e)),[]);return e.push(new a.utils.AddressMap(i)),e}catch(e){throw new Error(`Error while preparing disableAuth data: ${e.message}`)}}(o,e,r));return new a.UnsignedTx(e,n,o,s)},{bufferToHex:z,packTx:Y}=a.utils,{publicKeyBytesToAddress:G,recoverPublicKey:Q}=a.secp256k1,Z=new a.Signature(new Uint8Array(Array(65).fill(0))),ee=(e,t)=>{const r=Math.max(...e);if(!isFinite(r))throw new Error("Error while adding placeholder signatures for the provided indices.");const s=new Array(r+1).fill(Z);if(!t)return s;const{unsignedTx:n,credentialIndex:a}=t,i=n.getCredentials()[a];if(!i)return s;const o=Y(n.getTx()),d=m.sha256(o),u=Z.toString();for(const e of i.toJSON()){if(e.toString()===u)continue;const t=Q(d,e.toBytes()),r={toHex:()=>z(G(t))},i=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of i)t[0]===a&&(s[t[1]]=e)}return s};function te(e){return a.utils.bufferToHex(a.utils.addChecksum(e.toBytes()))}const{getManagerForVM:re,hexToBuffer:se,unpackWithManager:ne}=a.utils,ae=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=q(t);if(n===a.EVM)throw new Error("EVM transactions are not supported");const i=se(e),o=ne(n,i),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const i=re(s).unpack(t,a.avaxSerial.SignedTx),o=await J({tx:e,utxos:n,provider:r,credentials:i.getCredentials()});return e.getSigIndices().map(((e,t)=>new a.Credential(ee(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new a.Credential(ee(e))))}})({tx:o,txBytes:i,provider:r,vm:n,utxos:s});return J({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:ie,format:oe}=a.utils,{publicKeyBytesToAddress:de}=a.secp256k1;class ue{constructor(e,t,r){this.baseUrl=e,this.context=t,this.upgradesInfo=r;const s=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(s)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}isEtnaEnabled(){return!!this.upgradesInfo&&a.utils.isEtnaEnabled(this.upgradesInfo)}getUpgradesInfo(){return this.upgradesInfo}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return a.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new a.avm.AVMApi(this.baseUrl)}getApiP(){return new a.pvm.PVMApi(this.baseUrl)}getApiC(){return new a.evm.EVMApi(this.baseUrl)}getInfo(){return new a.info.InfoApi(this.baseUrl)}getApi(e){switch(e){case"X":return this.getApiX();case"P":return this.getApiP();case"C":return this.getApiC()}}getAvaxID(){return this.getContext().avaxAssetID}getAddress(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=Buffer.from(s,"hex"),i=de(a);return oe(r,this.getHrp(),i)}getAddressFromBuffer(e,t){return oe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ie(e);return oe(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=te(e);return this.issueTxHex(r,t)}async issueTxHex(e,t){return this.getApiByVM(t).issueTx({tx:e})}async waitForTransaction(e,t,r=6e4){const s=this.getApiByVM(t),n=Date.now();return new Promise(((t,i)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&i(new Error("Timeout")),d=s instanceof a.evm.EVMApi?await s.getAtomicTxStatus(e):await s.getTxStatus({txID:e,includeReason:!0}),d.status){case"Accepted":case"Committed":return void t({success:!0});case"Dropped":case"Rejected":return void t({success:!1});default:setTimeout((()=>{o()}),1e3)}};o()}))}}const ce={weights:a.Common.createDimensions({bandwidth:1,dbRead:1e3,dbWrite:1e3,compute:4}),maxCapacity:BigInt(1e6),maxPerSecond:BigInt(1e5),targetPerSecond:BigInt(5e4),minPrice:BigInt(1),excessConversionConstant:BigInt(2164043)},le={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:ce},he={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:ce},pe={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:ce};class ge extends ue{constructor(e,t,r){super(e,t,r)}static async fromBaseURL(e){const t=await a.Context.getContextFromURI(e);try{const r=await new a.info.InfoApi(e).getUpgradesInfo();return new ge(e,t,r)}catch{return new ge(e,t)}}static getDefaultMainnetProvider(e){return new ge(x.AVALANCHE_XP_NETWORK.rpcUrl,le,e)}static getDefaultFujiProvider(e){return new ge(x.AVALANCHE_XP_TEST_NETWORK.rpcUrl,he,e)}static getDefaultDevnetProvider(e){return new ge(x.AVALANCHE_P_DEV_NETWORK.rpcUrl,pe,e)}}const{bytesCompare:me,parseBech32:fe}=a.utils,xe=(e,t)=>"P"===t,ve=(e,t,r)=>{const s=xe(0,t)?e.amount:e.asset?.amount;return new a.TransferOutput(new a.BigIntPr(BigInt(s)),a.OutputOwners.fromNative(e.addresses.map((e=>fe(e)[1])).sort(me),BigInt(r??0),e.threshold))},we=(e,t)=>{const r=((e,t)=>{const r=t===f.Network.FUJI,s=t===f.Network.DEVNET,{cBlockchainID:n,xBlockchainID:a,pBlockchainID:i}=s?pe:r?he:le;if(n===e)return"C";if(a===e)return"X";if(i===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=xe(0,r)?e.txHash:e.creationTxHash,n=xe(0,r)?e.assetId:e.asset?.assetId;return new a.Utxo(a.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),a.Id.fromString(n),((e,t)=>xe(0,t)?e.stakeableLocktime?new a.pvmSerial.StakeableLockOut(new a.BigIntPr(BigInt(e.stakeableLocktime??0)),ve(e,t,e.platformLocktime??0)):ve(e,t,e.platformLocktime):ve(e,t,e.locktime))(e,r))},{unpackWithManager:Ae,parse:ye,bufferToHex:be,AddressMaps:Ie,AddressMap:Te}=a.utils;function Se(e){const t=Buffer.from(e,"utf8"),r=Buffer.alloc(4);r.writeUInt32BE(t.length,0);const s=Buffer.from(`Avalanche Signed Message:\n${r}${e}`,"utf8");return v("sha256").update(s).digest()}const Pe=1024,Be=1024;async function Ce(e,t,r){const s=e.slice(0,Pe),n=e.slice(Pe),a=await Ee(t,{...r,addresses:s});if(n.length){const s=await Ce(n,t,{...r,addresses:e});return a.merge(s)}return a}async function Ee(e,t){if(t.addresses.length>Pe)throw new Error(`Can not get UTXOs for more than ${Pe} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new a.utils.UtxoSet(s);if(s.length>=Be){const s=await Ee(e,{...t,startIndex:r});return n.merge(s)}return n}function ke(){return BigInt(Math.floor(Date.now()/1e3))}const{getUtxoInfo:Ve}=a.utils;async function De(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await De(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Me,hexToBuffer:Ue,unpackWithManager:Ke}=a.utils;function Oe(e,t=!0){try{if(t){const[t]=a.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else a.utils.parseBech32(e);return!0}catch(e){return!1}}const Ne=e=>{if([le.xBlockchainID,he.xBlockchainID,pe.xBlockchainID].includes(e))return"AVM";if([le.pBlockchainID,he.pBlockchainID,pe.pBlockchainID].includes(e))return"PVM";if([le.cBlockchainID,he.cBlockchainID,pe.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")},_e=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.output.amount()),BigInt(0)),Xe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0));var Le={parseCreateSubnetTx:e=>a.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:$.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>a.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:$.CreateChain,chain:e.getVM(),subnetID:e.getSubnetID().value(),chainName:e.chainName.value(),chainID:e.getBlockchainId(),vmID:e.vmID.value(),fxIDs:e.fxIds.map((e=>e.value())),genesisData:e.genesisData.toString(),...t}):null,parseAddSubnetValidatorTx:e=>a.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:$.AddSubnetValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.getSubnetID().value(),...t}):null,parseRemoveSubnetValidatorTx:e=>a.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:$.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>a.pvmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.evmSerial.isImportTx(e)?a.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:Ne(e.sourceChain.value()),amount:Xe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Import,chain:e.getVM(),source:Ne(e.sourceChain.value()),amount:Xe(e.ins,r),...t}):null,parseExportTx:e=>a.pvmSerial.isExportTx(e)||a.avmSerial.isExportTx(e)||a.evmSerial.isExportTx(e)?a.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:Ne(e.destinationChain.toString()),amount:_e(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:$.Export,chain:e.getVM(),destination:Ne(e.destination.value()),amount:_e(e.outs,r),...t}):null,parseBaseTx:e=>a.avmSerial.isAvmBaseTx(e)||a.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,i=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),a.avmSerial.isAvmBaseTx(e)){const e=await Promise.all([...s.values()].map((e=>t.getApiX().getAssetDescription(e))));return r.outputs.reduce(((r,n)=>{if(n.output instanceof a.TransferOutput){const a=n.assetId.value(),i=[...s.values()].indexOf(a),o=e[i],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:a,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===a}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof a.TransferOutput){const s=r.assetId.value(),n=r.output.outputOwners.addrs.map((e=>`P-${e.toString(t.getContext().hrp)}`));return[...e,{assetId:s,amount:r.output.amount(),locktime:r.output.getLocktime(),threshold:BigInt(r.output.getThreshold()),owners:n,isAvax:t.getContext().avaxAssetID===s}]}return e}),[])})(e,s),o=ke(),d=i.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:$.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!a.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return a.pvmSerial.isSigner(e.signer)&&(r=a.utils.bufferToHex(e.signer.proof.publicKey),t=a.utils.bufferToHex(e.signer.proof.signature)),({feeData:s})=>({type:$.AddPermissionlessValidator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),delegationFee:e.shares.value(),stakeOuts:e.stake,rewardOwner:e.getValidatorRewardsOwner(),delegationRewardOwner:e.getDelegatorRewardsOwner(),signer:e.signer,publicKey:r,signature:t,...s})},parseAddPermissionlessDelegatorTx:e=>a.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t})=>({type:$.AddPermissionlessDelegator,chain:e.getVM(),stake:e.subnetValidator.validator.weight.value(),nodeID:e.subnetValidator.validator.nodeId.value(),start:e.subnetValidator.validator.startTime.value().toString(),end:e.subnetValidator.validator.endTime.value().toString(),subnetID:e.subnetValidator.subnetId.value(),stakeOuts:e.stake,delegatorRewardsOwner:e.getDelegatorRewardsOwner(),...t}):null,parseTransferSubnetOwnershipTx:e=>a.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:$.TransferSubnetOwnership,chain:e.getVM(),subnetID:e.subnetID.value(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseConvertSubnetTx:e=>a.pvmSerial.isConvertSubnetToL1Tx(e)?({feeData:t,provider:r})=>{const s=r.getHrp(),n=e=>`P-${e.toString(s)}`;return{type:$.ConvertSubnetToL1,chain:e.getVM(),managerAddress:n(a.Address.fromHex(e.address.toString("hex"))),validators:e.validators.map((e=>({nodeId:a.NodeId.fromHex(e.nodeId.toString("hex")).toString(),stake:e.weight.value(),balance:e.balance.value(),remainingBalanceOwners:e.remainingBalanceOwner.addresses.map(n),deactivationOwners:e.deactivationOwner.addresses.map(n)}))),chainID:e.chainID.value(),subnetID:e.subnetID.value(),...t}}:null,parseRegisterL1ValidatorTx:e=>a.pvmSerial.isRegisterL1ValidatorTx(e)?({feeData:t})=>({type:$.RegisterL1Validator,chain:e.getVM(),balance:e.balance.value(),...t}):null,parseIncreaseL1ValidatorBalanceTx:e=>a.pvmSerial.isIncreaseL1ValidatorBalanceTx(e)?({feeData:t})=>({type:$.IncreaseL1ValidatorBalance,chain:e.getVM(),balance:e.balance.value(),validationId:e.validationId.toString(),...t}):null,parseSetL1ValidatorWeightTx:e=>a.pvmSerial.isSetL1ValidatorWeightTx(e)?({feeData:t})=>({type:$.SetL1ValidatorWeight,chain:e.getVM(),...t}):null,parseDisableL1ValidatorTx:e=>a.pvmSerial.isDisableL1ValidatorTx(e)?({feeData:t})=>({type:$.DisableL1Validator,chain:e.getVM(),validationId:e.validationId.toString(),...t}):null};const{getBurnedAmountByTx:Fe,getOutputAmounts:He,getInputAmounts:Re,validateBurnedAmount:$e}=a.utils;function qe(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 We(e){const t=ke(),r=e.map((e=>({utxo:e,...a.utils.getUtxoInfo(e)}))),s=r.filter((e=>e.stakeableLocktime<=t)),n=r.filter((e=>e.stakeableLocktime>t)),i=qe(s,["amount"],"desc"),o=qe(n,["stakeableLocktime","amount"],"desc"),[d,...u]=i;return[...d?[d]:[],...o,...u].map((e=>e.utxo))}function je(e,t){return qe(e.map((e=>({utxo:e,...a.utils.getUtxoInfo(e)}))),["amount"],t?"desc":"asc").map((e=>e.utxo))}const Je=e=>je(e,!0),ze=e=>je(e,!1);const{getUtxoInfo:Ye}=a.utils;var Ge=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Ge||{});const Qe="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",Ze="11111111111111111111111111111111LpoYY",et=(e,t)=>e.reduce(((e,t)=>e+Ye(t).amount),BigInt(0))-t,tt={BaseP:{sortFunction:Je,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.baseTX({utxoSet:new a.utils.UtxoSet(t),chain:"P",toAddress:e.getCurrentAddress("P"),amountsPerAsset:{[s.avaxAssetID]:et(t,s.baseTxFee)},feeState:r})}},ConsolidateP:{sortFunction:ze,unsignedTxBuilder:(e,t,r)=>{const s=e.getProvider().getContext();return e.consolidateP({utxoSet:new a.utils.UtxoSet(t),amount:et(t,s.baseTxFee),feeState:r})}},AddPermissionlessValidator:{sortFunction:We,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessValidator({utxoSet:new a.utils.UtxoSet(t),nodeId:Qe,start:ke(),end:ke()+BigInt(1e3),weight:et(t,e.getProvider().getContext().baseTxFee),subnetId:Ze,shares:5,feeState:r,fromAddresses:void 0,rewardAddresses:void 0,delegatorRewardAddresses:void 0,publicKey:Buffer.from(a.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),signature:Buffer.from(a.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98"))})},AddPermissionlessDelegator:{sortFunction:We,unsignedTxBuilder:(e,t,r)=>e.addPermissionlessDelegator({utxoSet:new a.utils.UtxoSet(t),nodeId:Qe,start:ke(),end:ke()+BigInt(1e3),weight:et(t,e.getProvider().getContext().baseTxFee),subnetId:Ze,feeState:r})},ExportP:{sortFunction:Je,unsignedTxBuilder:(e,t,r)=>e.exportP({amount:et(t,e.getProvider().getContext().baseTxFee),utxoSet:new a.utils.UtxoSet(t),destination:"X",feeState:r})},ImportP:{sortFunction:Je,unsignedTxBuilder:(e,t,r)=>e.importP({utxoSet:new a.utils.UtxoSet(t),sourceChain:"X",feeState:r})}};function rt(e){return A.validateString(e,!0)&&6===e.split("/").length}function st(e){if("object"!=typeof e||!e)throw new Error("feeState parameter is required post E-upgrade")}const{parse:nt,hexToBuffer:at}=a.utils;class it{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const t=this.provider.getApi(e);return Ce(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return De(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 Ce(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=nt(s)[2],i=this.provider.getAvaxID(),o=a.TransferableOutput.fromNative(i,e,[n]),d=je(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>nt(e)[2])),l=nt(this.getChangeAddress("X"))[2];return a.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP({utxoSet:e,sourceChain:t,toAddress:r,threshold:s,feeState:n,locktime:i}){const o=this.provider.getChainID(t),d=this.getAddresses("P").map((e=>nt(e)[2]));nt(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const u=nt(r)[2],c=e.getUTXOs();return st(n),a.pvm.newImportTx({fromAddressesBytes:d,utxos:c,toAddressesBytes:[u],sourceChainId:o,threshold:s,feeState:n,locktime:i},this.provider.getContext())}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>nt(e)[2])),i=nt(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=nt(r)[2];return a.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[i]})}importC(e,r,s,n,i){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>nt(e)[2]));i=i||this.getAddressEVM();const u=Buffer.from(t.strip0x(i),"hex");return a.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const i=at(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=nt(n)[2],u=s/BigInt(1e9);return a.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,i,[d],r)}exportP({amount:e,utxoSet:t,destination:r,feeState:s,toAddress:n}){n=n||this.getCurrentAddress(r);const i=nt(n)[2],o=this.provider.getAvaxID(),d=a.TransferableOutput.fromNative(o,e,[i]),u=je(t.getUTXOs(),!0),c=this.provider.getChainID(r),l=this.getAddresses("P").map((e=>nt(e)[2])),h=nt(this.getChangeAddress("P"))[2];return st(s),a.pvm.newExportTx({changeAddressesBytes:[h],fromAddressesBytes:l,utxos:u,outputs:[d],destinationChainId:c,feeState:s},this.provider.getContext())}consolidateP({utxoSet:e,amount:t,feeState:r,toAddress:s,options:n}){const i=ze(e.getUTXOs());s=s??this.getCurrentAddress("P");const o=nt(s)[2],d=this.provider.getContext(),u=[a.TransferableOutput.fromNative(d.avaxAssetID,t,[o])],c=this.getAddresses("P").map((e=>nt(e)[2])),l=nt(this.getChangeAddress("P"))[2],h=n?.changeAddresses??[l];return st(r),a.pvm.newBaseTx({changeAddressesBytes:h,fromAddressesBytes:c,utxos:i,outputs:u,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r},d)}baseTX({utxoSet:e,chain:t,toAddress:r,amountsPerAsset:s,feeState:n,options:i,fromAddresses:o}){const[d,u,c]=nt(r);if(d!==t||u!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const l=Object.entries(s).map((([e,t])=>a.TransferableOutput.fromNative(e,t,[c]))),h=je(e.getUTXOs(),!0),p=(o??this.getAddresses(t)).map((e=>nt(e)[2])),g=nt(this.getChangeAddress("P"))[2],m=i?.changeAddresses??[g];return"X"===t?a.avm.newBaseTx(this.provider.getContext(),p,h,l,i):(st(n),a.pvm.newBaseTx({changeAddressesBytes:m,fromAddressesBytes:p,utxos:h,outputs:l,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,feeState:n},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:t,subnetId:r,subnetAuth:s,feeState:n,address:i,validators:o,options:d,fromAddresses:u}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const c=(u??this.getAddresses("P")).map((e=>nt(e)[2])),l=nt(this.getChangeAddress("P"))[2],h=d?.changeAddresses??[l],p=o.map((({nodeId:e,pubKey:t,signature:r,balance:s,weight:n,deactivationOwner:i,remainingBalanceOwner:o})=>{const d=new a.pvmSerial.ProofOfPossession(Uint8Array.from(a.utils.hexToBuffer(t)),Uint8Array.from(a.utils.hexToBuffer(r))),u=a.PChainOwner.fromNative(o.addresses.map((e=>nt(e)[2])),o.threshold??1),c=a.PChainOwner.fromNative(i.addresses.map((e=>nt(e)[2])),i.threshold??1);return a.L1Validator.fromNative(e,n,s,d,u,c)}));return a.pvm.newConvertSubnetToL1Tx({changeAddressesBytes:h,validators:p,fromAddressesBytes:c,address:nt(i)[2],chainId:t,subnetId:r,subnetAuth:s,feeState:n,utxos:je(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:t,signature:r,message:s,feeState:n,fromAddresses:i,options:o}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const d=(i??this.getAddresses("P")).map((e=>nt(e)[2])),u=nt(this.getChangeAddress("P"))[2],c=o?.changeAddresses??[u];return a.pvm.newRegisterL1ValidatorTx({utxos:je(e.getUTXOs(),!0),balance:t,blsSignature:Uint8Array.from(a.utils.hexToBuffer(r)),changeAddressesBytes:c,feeState:n,fromAddressesBytes:d,memo:o?.memo,message:Uint8Array.from(a.utils.hexToBuffer(s)),minIssuanceTime:o?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:t,message:r,options:s,fromAddresses:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(n??this.getAddresses("P")).map((e=>nt(e)[2])),o=nt(this.getChangeAddress("P"))[2],d=s?.changeAddresses??[o];return a.pvm.newSetL1ValidatorWeightTx({utxos:je(e.getUTXOs(),!0),changeAddressesBytes:d,feeState:t,fromAddressesBytes:i,memo:s?.memo,message:Uint8Array.from(a.utils.hexToBuffer(r)),minIssuanceTime:s?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:t,options:r,fromAddresses:s,disableAuth:n,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const o=(s??this.getAddresses("P")).map((e=>nt(e)[2])),d=nt(this.getChangeAddress("P"))[2],u=r?.changeAddresses??[d];return a.pvm.newDisableL1ValidatorTx({disableAuth:n,validationId:i,utxos:je(e.getUTXOs(),!0),changeAddressesBytes:u,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:t,options:r,fromAddresses:s,balance:n,validationId:i}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const o=(s??this.getAddresses("P")).map((e=>nt(e)[2])),d=nt(this.getChangeAddress("P"))[2],u=r?.changeAddresses??[d];return a.pvm.newIncreaseL1ValidatorBalanceTx({balance:n,validationId:i,utxos:je(e.getUTXOs(),!0),changeAddressesBytes:u,feeState:t,fromAddressesBytes:o,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:t,chainName:r,vmID:s,fxIds:n,genesisData:i,subnetAuth:o,feeState:d,options:u,fromAddresses:c}){const l=je(e.getUTXOs(),!0),h=(c??this.getAddresses("P")).map((e=>nt(e)[2])),p=nt(this.getChangeAddress("P"))[2],g=u?.changeAddresses??[p];return st(d),a.pvm.newCreateChainTx({chainName:r,feeState:d,fromAddressesBytes:h,fxIds:n,genesisData:i,subnetAuth:o,subnetId:t,utxos:l,vmId:s,changeAddressesBytes:g},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:t,feeState:r,fromAddresses:s,options:n,threshold:i,locktime:o}){const d=je(e.getUTXOs(),!0),u=(s??this.getAddresses("P")).map((e=>nt(e)[2])),c=nt(this.getChangeAddress("P"))[2],l=n?.changeAddresses??[c],h=t.map((e=>nt(e)[2]));return st(r),a.pvm.newCreateSubnetTx({fromAddressesBytes:u,changeAddressesBytes:l,utxos:d,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:r,threshold:i,locktime:o,subnetOwners:h},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d,fromAddresses:u,options:c}){const l=je(e.getUTXOs(),!0),h=(u??this.getAddresses("P")).map((e=>nt(e)[2])),p=nt(this.getChangeAddress("P"))[2],g=c?.changeAddresses??[p];return st(d),a.pvm.newAddSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:h,utxos:l,minIssuanceTime:c?.minIssuanceTime,memo:c?.memo,nodeId:t,start:r,end:s,weight:n,subnetId:i,subnetAuth:o,feeState:d},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,fromAddresses:u,rewardAddresses:c,delegatorRewardAddresses:l,publicKey:h,signature:p,options:g,threshold:m,locktime:f,stakingAssetId:x}){const v=We(e.getUTXOs()),w=(u??this.getAddresses("P")).map((e=>nt(e)[2])),A=(c??[this.getCurrentAddress("P")]).map((e=>nt(e)[2])),y=(l??[this.getCurrentAddress("P")]).map((e=>nt(e)[2]));if(!(i!==a.networkIDs.PrimaryNetworkID.toString()||h&&p))throw new Error("Must provide public key and signature for primary subnet.");const b=nt(this.getChangeAddress("P"))[2],I=g?.changeAddresses??[b];return st(d),a.pvm.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:y,utxos:v,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,changeAddressesBytes:I,nodeId:t,start:r,end:s,weight:n,subnetId:i,shares:o,feeState:d,publicKey:h,rewardAddresses:A,signature:p,locktime:f,threshold:m,stakingAssetId:x},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:t,start:r,end:s,weight:n,subnetId:i,fromAddresses:o,rewardAddresses:d,options:u,locktime:c,feeState:l,threshold:h,stakingAssetId:p}){const g=We(e.getUTXOs()),m=(o??this.getAddresses("P")).map((e=>nt(e)[2])),f=(d??[this.getCurrentAddress("P")]).map((e=>nt(e)[2])),x=nt(this.getChangeAddress("P"))[2],v=u?.changeAddresses??[x];return st(l),a.pvm.newAddPermissionlessDelegatorTx({fromAddressesBytes:m,utxos:g,minIssuanceTime:u?.minIssuanceTime,memo:u?.memo,changeAddressesBytes:v,nodeId:t,start:r,end:s,weight:n,subnetId:i,rewardAddresses:f,locktime:c,stakingAssetId:p,threshold:h,feeState:l},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:t,subnetId:r,subnetAuth:s,fromAddresses:n,feeState:i,options:o}){const d=je(e.getUTXOs(),!0),u=(n??this.getAddresses("P")).map((e=>nt(e)[2])),c=nt(this.getChangeAddress("P"))[2],l=o?.changeAddresses??[c];return st(i),a.pvm.newRemoveSubnetValidatorTx({changeAddressesBytes:l,fromAddressesBytes:u,utxos:d,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,nodeId:t,subnetId:r,subnetAuth:s,feeState:i},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:t,subnetAuth:r,subnetOwners:s,feeState:n,fromAddresses:i,options:o,threshold:d,locktime:u}){const c=je(e.getUTXOs(),!0),l=(i??this.getAddresses("P")).map((e=>nt(e)[2])),h=nt(this.getChangeAddress("P"))[2],p=o?.changeAddresses??[h],g=s.map((e=>nt(e)[2]));return st(n),a.pvm.newTransferSubnetOwnershipTx({changeAddressesBytes:p,fromAddressesBytes:l,utxos:c,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,subnetId:t,subnetAuth:r,subnetOwners:g,feeState:n,threshold:d,locktime:u},this.provider.getContext())}}class ot extends it{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 ot(o,d,s)}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!rt(r)||!rt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(r),o=a.derivePath(t);return ot.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 dt={type:"zondax",getApp:e=>new y(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 ut(e){return!(await dt.getVersion(e)>="0.6.0")}const{parse:ct}=a.utils;class lt extends it{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new ot(t,t,r)}accountNode;evmWallet;externalIndex=0;internalIndex=0;pubkeyCache={};static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'").neutered(),a=s.derivePath(M(0,D.BIP44,"EVM")).neutered();return new lt(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(ct(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(ct(e)[2])))}getRawAddressC(){return Buffer.from(ct(this.getCurrentAddress("C"))[2])}}const{isTransferOut:ht,isStakeableLockOut:pt}=a.utils;function gt(e){const t=e.output;return ht(t)||pt(t)?t.getOwners():[]}function mt(e){const t=e.getTx();return a.avmSerial.isExportTx(t)||a.pvmSerial.isExportTx(t)?new Set(t.outs.map(gt).flat()):a.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(gt).flat()):new Set((t.baseTx?.outputs??[]).map(gt).flat())}const{parse:ft}=a.utils;class xt extends lt{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]=ft(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await ut(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=E(e),a=await dt.getXPUB(e,xt.getAccountPath("X")),i=u.fromPublicKey(a.pubKey,a.chainCode),o=M(0,D.BIP44,"EVM"),d=await s.getAddress(o,!1),c=n.SigningKey.computePublicKey(Buffer.from(d.publicKey,"hex"),!0),l=Buffer.from(t.strip0x(c),"hex");return new xt(i.toBase58(),l,r)}static getAccountPath(e){switch(e){case"P":case"X":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}async signMessage(e){throw new Error("not implemented")}filterOwnedAddresses(e,t,r){const s=this.getInternalRawAddresses().map((e=>e.toString("hex"))),n=this.getExternalRawAddresses().map((e=>e.toString("hex"))),a=new Set([...s,...r??[]]),i=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(a.has(t)){const e=[...a].indexOf(t);o.add(`1/${e}`)}else if(i.has(t)){const e=[...i].indexOf(t);o.add(`0/${e}`)}})),o}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=Buffer.from(t.toBytes()),i="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,i),u=this.getAdditionalAddressesByIndices(s??[],!0,i),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>A.fromString(e))),l=[...mt(t)].map((e=>Buffer.from(e))),h=[...this.filterOwnedAddresses(l).values()].map((e=>A.fromString(e)));return(await this.signTxBuffer({buffer:a,chain:i,transport:e.transport,signers:c,change:h})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=A.fromString(xt.getAccountPath(e.chain));return[...(await dt.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:vt}=a.utils;class wt extends lt{constructor(e,t,r){const s=u.fromBase58(e).neutered(),a=new n.SigningKey(t),i=Buffer.from(vt(a.compressedPublicKey),"hex");super(s.toBase58(),i,r),this.evmPrivKey=t,this.accountNode=u.fromBase58(e)}accountNode;static fromMnemonic(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r),n=s.derivePath("m/44'/9000'/0'"),a=s.derivePath(M(0,D.BIP44,"EVM"));if(!a.privateKey)throw new Error("Unable to derive EVM private key.");return new wt(n.toBase58(),a.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:t}),e.tx}getExternalPrivateKeys(e){const t=[];for(let e=0;e<=this.externalIndex;e++){const r=this.accountNode.derivePath(`0/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.externalIndex){const r=this.accountNode.derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getInternalPrivateKeys(e){const t=[];for(let e=0;e<=this.internalIndex;e++){const r=this.accountNode.derivePath(`1/${e}`);if(!r.privateKey)throw new Error("Unable to get private key.");t.push(r.privateKey)}const r=(e??[]).reduce(((e,t)=>{if(t>this.internalIndex){const r=this.accountNode.derivePath(`1/${t}`);if(!r.privateKey)throw new Error("Unable to get private key.");e.push(r.privateKey)}return e}),[]);return[...t,...r]}getSigningKeys(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM();return"AVM"===n?[...this.getInternalPrivateKeys(s),...this.getExternalPrivateKeys(r)]:"PVM"===n?this.getExternalPrivateKeys(r):[this.evmPrivKey]}async signTxBuffer(e){throw new Error("not implemented")}async signMessage(e){throw new Error("not implemented")}}const{getPublicKey:At,sign:yt,signHash:bt}=a.secp256k1,{addChecksum:It}=a.utils;class Tt extends ot{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(At(e)),Buffer.from(At(t)),r),this.privKeyXP=e,this.privKeyC=t}static fromMnemonic(e,t,r,s){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(!rt(r)||!rt(t))throw new Error("Not valid derivation path. Make sure it is a valid BIP44 path starting with m/");const n=c.mnemonicToSeedSync(e),a=u.fromSeed(n),i=a.derivePath(t),o=a.derivePath(r);if(!i.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new Tt(i.privateKey,o.privateKey,s)}async signMessage(e){const t=Se(e.message),r=this.getSigningKey(e.chain);return Buffer.from(It(await bt(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await a.addTxSignatures({unsignedTx:e.tx,privateKeys:[this.privKeyC,this.privKeyXP]}),e.tx}async signTxBuffer(e){const t=this.getSigningKey(e.chain);return[Buffer.from(await yt(e.buffer,t))]}}const{strip0x:St}=a.utils;class Pt extends ot{constructor(e,t,r,s,i){const o=a.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=a.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),i),this.pathXP=t,this.pathC=s,!rt(t)||!rt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,a){if(await ut(e))throw new Error("Ledger app not supported. Must be version >= 0.6.0");if(!rt(t)||!rt(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(St(o.publicKey),"hex"),c=Buffer.from(St(d.publicKey),"hex"),l=Buffer.from(St(n.SigningKey.computePublicKey(u,!0)),"hex"),h=Buffer.from(St(n.SigningKey.computePublicKey(c,!0)),"hex");return new Pt(h,t,l,r,a)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=A.fromString(this.getAccountPath(e.chain)),r=A.fromString(this.getPartialSignerPath(e.chain));return[...(await dt.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Bt}=a.utils;var Ct=Object.freeze({__proto__:null,AbstractProvider:ue,AddressWallet:class extends it{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=>!Oe(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!Oe(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(!Oe(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:he,JsonRpcProvider:ge,LedgerSigner:Pt,LedgerWallet:xt,MainnetContext:le,MnemonicWallet:wt,MnemonicWalletVoid:lt,P_CHAIN_TX_SIZE_LIMIT:65536,SimpleLedgerSigner:class{constructor(e,t,r){this.activeAccountIndex=e,this.provider=t,r&&(this.accountNode=u.fromBase58(r))}accountNode;reSerializeTx(e,t){return e instanceof a.EVMUnsignedTx||"C"===t?a.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):a.UnsignedTx.fromJSON(JSON.stringify(e.toJSON()))}getChainAlias(e){return"EVM"===e.getVM()?"C":"X"}getAccountPath(e){switch(e){case"X":case"P":return"m/44'/9000'/0'";case"C":return"m/44'/60'/0'"}}getAddressOfPath(e,t){if(!this.accountNode)return null;const{publicKey:r}=this.accountNode.derivePath(e),s=this.provider.getAddress(r,t);return Buffer.from(Bt(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?[A.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(A.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([...mt(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=A.fromString(this.getAccountPath(e.chain));return[...(await dt.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||A.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=Se(e.message),s=(await dt.signHash(e.transport,r,A.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(M(t,D.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),i=this.getSigningKeys(n,r,s);if(!i?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await a.addTxSignatures({unsignedTx:t,privateKeys:i}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=Se(e.message),s=await a.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Ge,StaticSigner:Tt,TxType:$,WalletAbstract:it,WalletVoid:ot,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const i=await ae({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>i.addSignature(e))));const o=i.getCredentials(),d=i.getSigIndices().reduce(((e,t,r)=>{const s=t.map((e=>{const t=o[r]?.toJSON()[e];if(!t)throw new Error(`Failed to sign [${r}, ${e}]`);return t}));return e.push(new a.Credential(s)),e}),[]),u=new a.UnsignedTx(i.getTx(),i.getInputUtxos(),i.addressMaps,d);return{signedTxHex:te(new a.avaxSerial.SignedTx(i.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:we,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=Ae(r,e),i=ye(t)[2],o=be(i);if(a.evmSerial.isExportTx(n))return new a.EVMUnsignedTx(n,[],new Ie([Te.fromJSON([[o,0]])]));if(a.evmSerial.isImportTx(n)){const e=Ie.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[i]);return new a.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:J,digestMessage:Se,emptySignature:Z,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const a=n?"1":"0",i=u.fromBase58(e).derivePath(`${a}/${t}`).publicKey;return r.getAddress(i,s)},getAddressPublicKeyFromXpub:function(e,t){if(t<0)throw new Error("Account index must be >= 0");return u.fromBase58(e).derivePath(`0/${t}`).publicKey},getAssetBalance:function(e,t){const r=e.getAssetDict()[t],s={locked:BigInt(0),available:BigInt(0),multisig:BigInt(0),lockedStakeable:BigInt(0),total:BigInt(0)};if(!r)return s;const n=r.getUTXOs(),a=ke();return n.forEach((e=>{const t=Ve(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 dt},getMaximumUtxoSet:function({wallet:e,utxos:t,sizeSupportedTx:r,limit:s=65536,feeState:n}){const{sortFunction:a,unsignedTxBuilder:i}=tt[r],o=ke(),d=a(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=Ye(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*Ye(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(Ye)}),s+1}}),s);return-1===u?[]:d.slice(0,u+1)},getPaginatedUTXOs:Ee,getPchainUnixNow:async function(e){const t=e?x.AVALANCHE_XP_TEST_NETWORK.rpcUrl:x.AVALANCHE_XP_NETWORK.rpcUrl,r=await new a.pvm.PVMApi(t).getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:De,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[a.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Ce,getUnixNow:ke,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,network:r,url:s,token:n,headers:i})=>{const o=q(t),d=Ue(e),u=Ke(o,d);if(a.evmSerial.isExportTx(u))return[];const c=(e=>{if(a.evmSerial.isImportTx(e)||a.avmSerial.isImportTx(e)||a.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case a.EVM:return f.BlockchainId.C_CHAIN;case a.AVM:return f.BlockchainId.X_CHAIN;case a.PVM:return f.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Me(u),h=new f.Glacier({BASE:s,TOKEN:n,HEADERS:i}),p=[...new Set(l.map((e=>e.utxoID.txID.toString())))],g=await Promise.all(p.map((e=>h.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:r,txHash:e}))));return l.reduce(((e,t)=>{const s=g.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const a=we(n,r);return e.push(a),e}),[])},getVmByChainAlias:q,getXpubFromMnemonic:function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=c.mnemonicToSeedSync(e);return u.fromSeed(t).derivePath("44'/9000'/0'").neutered().toBase58()},isAddDelegatorTx:function(e){return"add_delegator"===e.type},isAddPermissionlessDelegatorTx:function(e){return"add_permissionless_delegator"===e.type},isAddPermissionlessValidatorTx:function(e){return"add_permissionless_validator"===e.type},isAddSubnetValidatorTx:function(e){return"add_subnet_validator"===e.type},isAddValidatorTx:function(e){return"add_validator"===e.type},isBaseTx:function(e){return"base"===e.type},isBech32Address:Oe,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:ut,isRegisterL1ValidatorTx:function(e){return"register_l1_validator"===e.type},isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===e.type},isSetL1ValidatorWeightTx:function(e){return"set_l1_validator_weight"===e.type},isTransferSubnetOwnershipTx:function(e){return"transfer_subnet_ownership"===e.type},isTransformSubnetTx:function(e){return"transform_subnet"===e.type},parseAvalancheTx:async function(e,t,r,{feeTolerance:s=50}={}){try{const n=t.getContext(),i=e.getTx(),o=(e=>{for(const t of Object.values(Le)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(i),d=Fe(i,n),u=He(i),c=Re(i).get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0),h=u.get(n.avaxAssetID)??BigInt(0);let p,g=BigInt(0);a.evmSerial.isImportExportTx(i)?g=await t.getApiC().getBaseFee()/BigInt(1e9):"PVM"===i.vm&&(p=t.getUpgradesInfo(),g=await t.getApiP().getFeeState().then((e=>e.price)).catch((()=>BigInt(0))));const{isValid:m,txFee:f}=$e({unsignedTx:e,context:n,burnedAmount:l,baseFee:g,feeTolerance:s});return await o({feeData:{totalAvaxBurned:l,totalAvaxOutput:h,totalAvaxInput:c,isValidAvaxBurnedAmount:m,txFee:f},assetId:n.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:$.Unknown}}},populateCredential:ee,signedTxToHex:te,sortUTXOsByAmount:je,sortUTXOsByAmountAscending:ze,sortUTXOsByAmountDescending:Je,sortUTXOsStaking:We,verifyDerivationPath:rt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Ct,exports.BitcoinLedgerWallet=class extends H{constructor(e,t,r,s,n){super(e,r),this.derivationPath=t,this.transport=s,this.walletPolicyDetails=n}setTransport(e){this.transport=e}async signTx(e,t){const r=function(e){return new p(e)}(this.transport),s=this.ecPair.publicKey,n=this.provider.getNetwork(),a=await r.getMasterFingerprint(),i=L(e,t,n,Buffer.from(a,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(i,o,d),c=F(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 I{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.#r=new t.HttpClient(s||o,i);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#s=new t.HttpClient(n||d,i)}#r;#s;async#n(e,t){return this.isMainnet||t?(await Promise.all(e.map((e=>this.#s.post("",e,{},this.extraParams))))).flat():this.#s.post("",e,{},this.extraParams)}async getTxHex(e){return(await this.#r.post(`/api/v2/tx/${e}`,{},{},this.extraParams)).hex}async getUTXOs(e,t=!0,r){const s=await this.#r.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.#s.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.#n(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.#r.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.#s.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.#n([{...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.#s.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[e]},{},this.extraParams).then((e=>e.result))}async getTransaction(e){const t=await this.#r.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.#r.post(`/api/v2/address/${e}`,{},{},this.extraParams);return await Promise.allSettled(t.txids?.slice(0,25).map((async t=>{try{const r=await this.#r.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return function(e,t){const r=t.vin.filter((t=>t.addresses?.includes(e))),s=t.vout.filter((t=>t.addresses?.includes(e))),n=t.vin.filter((t=>!t.addresses?.includes(e))),a=t.vout.filter((t=>!t.addresses?.includes(e))),i=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=i>o;let u=o-i;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=a.map((e=>e.addresses||[])).flat(),h=d?l:c,p=h.filter(((e,t)=>h.indexOf(e)===t)),g=s.filter((e=>(e.addresses?.length||0)>1)).length>0;return{addresses:p,isSender:d,block:t.blockHeight,fee:Number(t.fees),confirmations:t.confirmations,amount:Number(u),hash:t.txid,containsMultisig:g,receivedTime:t.blockTime,confirmedTime:t.confirmations>0?t.blockTime:void 0}}(e,r)}catch(e){console.log(`Unable to parse full tx ${t}.`)}}))).then((e=>e.map((e=>"fulfilled"===e.status&&e.value?e.value:void 0)).filter((e=>void 0!==e))))}async waitForTx(e,{maxAttempts:t=20,attempt:r=1,pollInterval:s=500}={}){try{return await this.getTransaction(e)}catch(n){if(r>=t)throw n;return await new Promise((e=>setTimeout(e,s))),this.waitForTx(e,{maxAttempts:t,attempt:r+1,pollInterval:s})}}},exports.BitcoinProviderAbstract=I,exports.BitcoinWallet=R,exports.BitcoinWalletAbstract=H,exports.BitcoinWalletVoid=class extends H{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=D,exports.ETH_ACCOUNT_PATH=V,exports.ETH_COIN_PATH=k,exports.JsonRpcBatchInternal=N,exports.LedgerSigner=X,exports.addEncodedSigToPsbt=function(e,t,r,s){const n=[{pubkey:t,signature:e}];r.updateInput(s,{partialSig:n})},exports.createPSBTV2=L,exports.createPsbt=T,exports.createTransferTx=B,exports.createWalletPolicy=function(e,t,r,s){const n=new p.DefaultWalletPolicy("wpkh(@0/**)",`[${e}/44'/60'/${t}']${r}`);return new p.WalletPolicy(s,"wpkh(@0/**)",n.keys)},exports.formatAddressForNetworkBech32=function(t,r){const s=e.address.fromBech32(t);return e.address.toBech32(s.data,s.version,r.bech32)},exports.getAddressDerivationPath=M,exports.getAddressFromXPub=function(e,t){const r=_(e,t);return n.computeAddress(`0x${r.toString("hex")}`)},exports.getAddressPrivateKeyFromXPriv=function(e,t){const r=u.fromBase58(e).derivePath(`0/${t}`);if(!r.privateKey)throw new Error("Unable to derive private key.");return r.privateKey},exports.getAddressPublicKeyFromXPub=_,exports.getAppEth=E,exports.getBech32Address=C,exports.getBech32AddressFromXPub=function(e,t,r){return C(_(e,t),r)},exports.getBtcAddressFromPubKey=function(e,r){const s=t.strip0x(n.SigningKey.computePublicKey(e,!0));return C(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=E(e),n=await s.getAddress(r??V,t,!0),a=new i;return a.publicKey=o.Buffer.from(n.publicKey,"hex"),a.chainCode=o.Buffer.from(n.chainCode,"hex"),a.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=b(e);if(!n)return 0;const{fee:a}=S(t,r,n,s,e);return n-a},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=E(e),a=M(t,r,s),i=await n.getAddress(a,!1,!1);return Buffer.from(i.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(a.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getTransferTxDetails=function(e,t,r,s,n){const a=S(e,t,r,s,P(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),M(t,r,"EVM"))},exports.getXpubFromMnemonic=async function(e){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");const t=await c.mnemonicToSeed(e);return u.fromSeed(t).derivePath(V).neutered().toBase58()},exports.isERC20Transfer=K,exports.isNativeTxn=U,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())&&K(e,n)?s(e,{type:"erc20",contractAddress:e.to}):U(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=F,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=S;
@@ -1,4 +1,3 @@
1
- import * as _avalabs_avalanchejs_dist_vms_pvm from '@avalabs/avalanchejs/dist/vms/pvm';
2
1
  import { Context } from '@avalabs/avalanchejs';
3
2
 
4
3
  /**
@@ -9,23 +8,6 @@ declare const MainnetContext: Context.Context;
9
8
  * Avalanche Fuji testnet context
10
9
  */
11
10
  declare const FujiContext: Context.Context;
12
- declare const DevnetContext: {
13
- addPrimaryNetworkDelegatorFee: bigint;
14
- addPrimaryNetworkValidatorFee: bigint;
15
- addSubnetDelegatorFee: bigint;
16
- addSubnetValidatorFee: bigint;
17
- avaxAssetID: string;
18
- baseTxFee: bigint;
19
- cBlockchainID: string;
20
- createAssetTxFee: bigint;
21
- createBlockchainTxFee: bigint;
22
- createSubnetTxFee: bigint;
23
- hrp: string;
24
- networkID: number;
25
- pBlockchainID: string;
26
- transformSubnetTxFee: bigint;
27
- xBlockchainID: string;
28
- platformFeeConfig: _avalabs_avalanchejs_dist_vms_pvm.FeeConfig;
29
- };
11
+ declare const DevnetContext: Context.Context;
30
12
 
31
13
  export { DevnetContext, FujiContext, MainnetContext };
@@ -1 +1 @@
1
- import{platformFeeConfig as e}from"./platformFeeConfig.js";const t={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e9),transformSubnetTxFee:BigInt(1e10),createBlockchainTxFee:BigInt(1e9),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:1,hrp:"avax",platformFeeConfig:e},a={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),createSubnetTxFee:BigInt(1e8),transformSubnetTxFee:BigInt(1e9),createBlockchainTxFee:BigInt(1e8),addPrimaryNetworkValidatorFee:BigInt(0),addPrimaryNetworkDelegatorFee:BigInt(0),addSubnetValidatorFee:BigInt(1e6),addSubnetDelegatorFee:BigInt(1e6),networkID:5,hrp:"fuji",platformFeeConfig:e},n={addPrimaryNetworkDelegatorFee:0n,addPrimaryNetworkValidatorFee:0n,addSubnetDelegatorFee:1000000n,addSubnetValidatorFee:1000000n,avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",createAssetTxFee:1000000n,createBlockchainTxFee:100000000n,createSubnetTxFee:100000000n,hrp:"custom",networkID:76,pBlockchainID:"11111111111111111111111111111111LpoYY",transformSubnetTxFee:100000000n,xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",platformFeeConfig:e};export{n as DevnetContext,a as FujiContext,t as MainnetContext};
1
+ import{platformFeeConfig as e}from"./platformFeeConfig.js";const o={xBlockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",avaxAssetID:"FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:1,hrp:"avax",platformFeeConfig:e},c={xBlockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",avaxAssetID:"U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK",baseTxFee:BigInt(1e6),createAssetTxFee:BigInt(1e7),networkID:5,hrp:"fuji",platformFeeConfig:e},n={xBlockchainID:"2piQ2AVHCjnduiWXsSY15DtbVuwHE2cwMHYnEXHsLL73BBkdbV",pBlockchainID:"11111111111111111111111111111111LpoYY",cBlockchainID:"vV3cui1DsEPC3nLCGH9rorwo8s6BYxM2Hz4QFE5gEYjwTqAu",avaxAssetID:"22jjRVdyTJiAEtcZciAVR8bTFyVDUVoo1T3o5PiDspQSZ2maXR",baseTxFee:1000000n,createAssetTxFee:1000000n,networkID:76,hrp:"custom",platformFeeConfig:e};export{n as DevnetContext,c as FujiContext,o as MainnetContext};
@@ -1 +1 @@
1
- import{evmSerial as t,utils as e}from"@avalabs/avalanchejs";import{TxType as n}from"../models.js";import a from"./parsers/index.js";const{getBurnedAmountByTx:r,getOutputAmounts:o,getInputAmounts:s,validateBurnedAmount:u}=e;async function i(e,i,g,{feeTolerance:x=50}={}){try{const n=i.getContext(),p=e.getTx(),c=(t=>{for(const e of Object.values(a)){const n=e(t);if(null!==n)return n}throw new Error("no parser found for tx")})(p),d=r(p,n),A=o(p),I=s(p).get(n.avaxAssetID)??BigInt(0),l=d.get(n.avaxAssetID)??BigInt(0),m=A.get(n.avaxAssetID)??BigInt(0);let f,v=BigInt(0);t.isImportExportTx(p)?v=await i.getApiC().getBaseFee()/BigInt(1e9):"PVM"===p.vm&&(f=i.getUpgradesInfo(),v=await i.getApiP().getFeeState().then((t=>t.price)).catch((()=>BigInt(0))));const{isValid:B,txFee:w}=u({upgradesInfo:f,unsignedTx:e,context:n,burnedAmount:l,baseFee:v,feeTolerance:x});return await c({feeData:{totalAvaxBurned:l,totalAvaxOutput:m,totalAvaxInput:I,isValidAvaxBurnedAmount:B,txFee:w},assetId:n.avaxAssetID,provider:i,currentAddress:g})}catch(t){return{type:n.Unknown}}}export{i as parseAvalancheTx};
1
+ import{evmSerial as t,utils as e}from"@avalabs/avalanchejs";import{TxType as n}from"../models.js";import a from"./parsers/index.js";const{getBurnedAmountByTx:r,getOutputAmounts:o,getInputAmounts:s,validateBurnedAmount:i}=e;async function u(e,u,g,{feeTolerance:x=50}={}){try{const n=u.getContext(),c=e.getTx(),p=(t=>{for(const e of Object.values(a)){const n=e(t);if(null!==n)return n}throw new Error("no parser found for tx")})(c),d=r(c,n),A=o(c),l=s(c).get(n.avaxAssetID)??BigInt(0),m=d.get(n.avaxAssetID)??BigInt(0),I=A.get(n.avaxAssetID)??BigInt(0);let v,f=BigInt(0);t.isImportExportTx(c)?f=await u.getApiC().getBaseFee()/BigInt(1e9):"PVM"===c.vm&&(v=u.getUpgradesInfo(),f=await u.getApiP().getFeeState().then((t=>t.price)).catch((()=>BigInt(0))));const{isValid:B,txFee:w}=i({unsignedTx:e,context:n,burnedAmount:m,baseFee:f,feeTolerance:x});return await p({feeData:{totalAvaxBurned:m,totalAvaxOutput:I,totalAvaxInput:l,isValidAvaxBurnedAmount:B,txFee:w},assetId:n.avaxAssetID,provider:u,currentAddress:g})}catch(t){return{type:n.Unknown}}}export{u as parseAvalancheTx};
@@ -1 +1 @@
1
- import r from"./parseAddValidatorTx.js";import e from"./parseAddDelegatorTx.js";import a from"./parseCreateSubnetTx.js";import s from"./parseCreateChainTx.js";import o from"./parseAddSubnetValidorTx.js";import t from"./parseImportTx.js";import p from"./parseExportTx.js";import i from"./parseBaseTx.js";import m from"./parseAddPermissionlessValidatorTx.js";import T from"./parseAddPermissionlessDelegatorTx.js";import x from"./parseRemoveSubnetValidatorTx.js";import d from"./parseTransformSubnetTx.js";import n from"./parseTransferSubnetOwnershipTx.js";import l from"./parseConvertSubnetToL1Tx.js";import f from"./parseRegisterL1ValidatorTx.js";import j from"./parseSetL1ValidatorWeightTx.js";import V from"./parseDisableL1ValidatorTx.js";import b from"./parseIncreaseL1ValidatorBalanceTx.js";var S={parseAddValidatorTx:r,parseAddDelegatorTx:e,parseCreateSubnetTx:a,parseCreateChainTx:s,parseAddSubnetValidatorTx:o,parseRemoveSubnetValidatorTx:x,parseImportTx:t,parseExportTx:p,parseBaseTx:i,parseAddPermissionlessValidatorTx:m,parseAddPermissionlessDelegatorTx:T,parseTransformSubnetTx:d,parseTransferSubnetOwnershipTx:n,parseConvertSubnetTx:l,parseRegisterL1ValidatorTx:f,parseIncreaseL1ValidatorBalanceTx:b,parseSetL1ValidatorWeightTx:j,parseDisableL1ValidatorTx:V};export{S as default};
1
+ import r from"./parseCreateSubnetTx.js";import e from"./parseCreateChainTx.js";import a from"./parseAddSubnetValidorTx.js";import s from"./parseImportTx.js";import o from"./parseExportTx.js";import t from"./parseBaseTx.js";import p from"./parseAddPermissionlessValidatorTx.js";import i from"./parseAddPermissionlessDelegatorTx.js";import m from"./parseRemoveSubnetValidatorTx.js";import x from"./parseTransferSubnetOwnershipTx.js";import T from"./parseConvertSubnetToL1Tx.js";import d from"./parseRegisterL1ValidatorTx.js";import n from"./parseSetL1ValidatorWeightTx.js";import l from"./parseDisableL1ValidatorTx.js";import f from"./parseIncreaseL1ValidatorBalanceTx.js";var j={parseCreateSubnetTx:r,parseCreateChainTx:e,parseAddSubnetValidatorTx:a,parseRemoveSubnetValidatorTx:m,parseImportTx:s,parseExportTx:o,parseBaseTx:t,parseAddPermissionlessValidatorTx:p,parseAddPermissionlessDelegatorTx:i,parseTransferSubnetOwnershipTx:x,parseConvertSubnetTx:T,parseRegisterL1ValidatorTx:d,parseIncreaseL1ValidatorBalanceTx:f,parseSetL1ValidatorWeightTx:n,parseDisableL1ValidatorTx:l};export{j as default};
@@ -1,5 +1,5 @@
1
1
  import { Utxo, pvm } from '@avalabs/avalanchejs';
2
- import { WalletAbstract } from 'Avalanche/wallets';
2
+ import { WalletAbstract } from '../wallets/WalletAbstract.js';
3
3
 
4
4
  /**
5
5
  * The list of transaction types supported by `getMaximumUtxoSet`.
@@ -82,12 +82,6 @@ declare abstract class WalletAbstract {
82
82
  * @param toAddress
83
83
  */
84
84
  exportP({ amount, utxoSet, destination, feeState, toAddress }: ExportP): Common.UnsignedTx;
85
- addValidator(utxos: utils.UtxoSet, nodeId: string, stakeAmount: bigint, startDate: bigint, endDate: bigint, delegationFee: number, config?: {
86
- rewardAddress?: string;
87
- }): Common.UnsignedTx;
88
- addDelegator(utxos: utils.UtxoSet, nodeId: string, stakeAmount: bigint, startDate: bigint, endDate: bigint, config?: {
89
- rewardAddress?: string;
90
- }): Common.UnsignedTx;
91
85
  consolidateP({ utxoSet, amount, feeState, toAddress, options, }: ConsolidateP): Common.UnsignedTx;
92
86
  baseTX({ utxoSet, chain, toAddress, amountsPerAsset, feeState, options, fromAddresses, }: BaseTx): Common.UnsignedTx;
93
87
  convertSubnetToL1({ utxoSet, chainId, subnetId, subnetAuth, feeState, address, validators, options, fromAddresses, }: ConvertSubnetToL1): Common.UnsignedTx;
@@ -130,7 +124,6 @@ declare abstract class WalletAbstract {
130
124
  addPermissionlessDelegator({ utxoSet, nodeId, start, end, weight, subnetId, fromAddresses, rewardAddresses, options, locktime, feeState, threshold, stakingAssetId, }: AddPermissionlessDelegator): Common.UnsignedTx;
131
125
  removeSubnetValidator({ utxoSet, nodeId, subnetId, subnetAuth, fromAddresses, feeState, options, }: RemoveSubnetValidator): Common.UnsignedTx;
132
126
  transferSubnetOwnershipTx({ utxoSet, subnetId, subnetAuth, subnetOwners, feeState, fromAddresses, options, threshold, locktime, }: TransferSubnetOwnershipTx): Common.UnsignedTx;
133
- transformSubnetTx(utxoSet: utils.UtxoSet, subnetId: string, assetId: string, initialSupply: bigint, maximumSupply: bigint, minConsumptionRate: bigint, maxConsumptionRate: bigint, minValidatorStake: bigint, maxValidatorStake: bigint, minStakeDuration: number, maxStakeDuration: number, minDelegationFee: number, minDelegatorStake: bigint, maxValidatorWeightFactor: number, uptimeRequirement: number, subnetAuth: number[], fromAddresses?: string[], options?: Common.SpendOptions): Common.UnsignedTx;
134
127
  protected constructor(provider: AbstractProvider);
135
128
  }
136
129
 
@@ -1 +1 @@
1
- import{TransferableOutput as e,avm as s,pvm as t,evm as r,pvmSerial as d,utils as o,PChainOwner as n,L1Validator as i,networkIDs as a}from"@avalabs/avalanchejs";import"../utils/populateCredential.js";import"@avalabs/glacier-sdk";import{strip0x as h}from"@avalabs/core-utils-sdk";import"ethers";import"../providers/constants.js";import"@avalabs/core-chains-sdk";import"create-hash";import"bip32";import{getUTXOsForAddresses as g}from"../utils/getAllUTXOs.js";import{getStakeForAddresses as m}from"../utils/getStakeForAddresses.js";import"bip39";import"xss";import{sortUTXOsByAmount as u,sortUTXOsStaking as p,sortUTXOsByAmountAscending as A}from"../utils/sortUTXOs.js";import"bip32-path";import{assertFeeStateProvided as c}from"../../utils/assertFeeStateProvided.js";const{parse:x,hexToBuffer:f}=o,l=new Error("Tx type is not supported post-etna");class v{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const s=this.provider.getApi(e);return g(this.getAddresses(e),s)}async getStake(){const e=this.provider.getApiP();return m(this.getAddresses("P"),e)}async getAtomicUTXOs(e,s){if(e===s)throw new Error("Chain can not be the same as source chain.");const t=this.provider.getApi(e),r=this.provider.getChainID(s);return g(this.getAddresses(e),t,{sourceChain:r,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(t,r,d,o){o=o||this.getCurrentAddress(d);const n=x(o)[2],i=this.provider.getAvaxID(),a=e.fromNative(i,t,[n]),h=u(r.getUTXOs(),!0),g=this.provider.getChainID(d),m=this.getAddresses("X").map((e=>x(e)[2])),p=x(this.getChangeAddress("X"))[2];return s.newExportTx(this.provider.getContext(),g,m,h,[a],{threshold:1,changeAddresses:[p]})}importP({utxoSet:e,sourceChain:s,toAddress:r,threshold:d,feeState:o,locktime:n}){const i=this.provider.getChainID(s),a=this.getAddresses("P").map((e=>x(e)[2])),h=x(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const g=x(r)[2],m=e.getUTXOs();if(this.provider.isEtnaEnabled()){if(!o)throw new Error("feeState parameter is required post E-upgrade");return t.e.newImportTx({fromAddressesBytes:a,utxos:m,toAddressesBytes:[g],sourceChainId:i,threshold:d,feeState:o,locktime:n},this.provider.getContext())}return t.newImportTx(this.provider.getContext(),i,m,[g],a,{changeAddresses:[h]})}importX(e,t,r){const d=this.provider.getChainID(t),o=this.getAddresses("X").map((e=>x(e)[2])),n=x(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const i=x(r)[2];return s.newImportTx(this.provider.getContext(),d,e.getUTXOs(),[i],o,{changeAddresses:[n]})}importC(e,s,t,d,o){const n=this.provider.getChainID(s),i=this.getAddresses("C").map((e=>x(e)[2]));o=o||this.getAddressEVM();const a=Buffer.from(h(o),"hex");return r.newImportTxFromBaseFee(this.provider.getContext(),a,i,e.getUTXOs(),n,t,d)}exportC(e,s,t,d,o){const n=f(this.getAddressEVM()),i=this.provider.getChainID(s);o=o||this.getCurrentAddress(s);const a=x(o)[2],h=d/BigInt(1e9);return r.newExportTxFromBaseFee(this.provider.getContext(),h,e,i,n,[a],t)}exportP({amount:s,utxoSet:r,destination:d,feeState:o,toAddress:n}){n=n||this.getCurrentAddress(d);const i=x(n)[2],a=this.provider.getAvaxID(),h=e.fromNative(a,s,[i]),g=u(r.getUTXOs(),!0),m=this.provider.getChainID(d),p=this.getAddresses("P").map((e=>x(e)[2])),A=x(this.getChangeAddress("P"))[2];return this.provider.isEtnaEnabled()?(c(o),t.e.newExportTx({changeAddressesBytes:[A],fromAddressesBytes:p,utxos:g,outputs:[h],destinationChainId:m,feeState:o},this.provider.getContext())):t.newExportTx(this.provider.getContext(),m,p,g,[h],{changeAddresses:[A]})}addValidator(e,s,r,d,o,n,i){const a=p(e.getUTXOs()),h=this.getAddresses("P").map((e=>x(e)[2])),g=i?.rewardAddress||this.getCurrentAddress("P"),m=x(g)[2],u=x(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw l;return t.newAddValidatorTx(this.provider.getContext(),a,h,s,d,o,r,[m],n,{changeAddresses:[u]})}addDelegator(e,s,r,d,o,n){const i=p(e.getUTXOs()),a=this.getAddresses("P").map((e=>x(e)[2])),h=n?.rewardAddress||this.getCurrentAddress("P"),g=x(h)[2],m=x(this.getChangeAddress("P"))[2];if(this.provider.isEtnaEnabled())throw l;return t.newAddDelegatorTx(this.provider.getContext(),i,a,s,d,o,r,[g],{changeAddresses:[m]})}consolidateP({utxoSet:s,amount:r,feeState:d,toAddress:o,options:n}){const i=A(s.getUTXOs());o=o??this.getCurrentAddress("P");const a=x(o)[2],h=this.provider.getContext(),g=[e.fromNative(h.avaxAssetID,r,[a])],m=this.getAddresses("P").map((e=>x(e)[2])),u=x(this.getChangeAddress("P"))[2],p=n?.changeAddresses??[u];return this.provider.isEtnaEnabled()?(c(d),t.e.newBaseTx({changeAddressesBytes:p,fromAddressesBytes:m,utxos:i,outputs:g,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:d},h)):t.newBaseTx(this.provider.getContext(),m,i,g,n)}baseTX({utxoSet:r,chain:d,toAddress:o,amountsPerAsset:n,feeState:i,options:a,fromAddresses:h}){const[g,m,p]=x(o);if(g!==d||m!==this.provider.getHrp())throw new Error(`Invalid recipient address "${o}"`);const A=Object.entries(n).map((([s,t])=>e.fromNative(s,t,[p]))),f=u(r.getUTXOs(),!0),l=(h??this.getAddresses(d)).map((e=>x(e)[2])),v=x(this.getChangeAddress("P"))[2],T=a?.changeAddresses??[v];return"X"===d?s.newBaseTx(this.provider.getContext(),l,f,A,a):this.provider.isEtnaEnabled()?(c(i),t.e.newBaseTx({changeAddressesBytes:T,fromAddressesBytes:l,utxos:f,outputs:A,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:i},this.provider.getContext())):t.newBaseTx(this.provider.getContext(),l,f,A,a)}convertSubnetToL1({utxoSet:e,chainId:s,subnetId:r,subnetAuth:a,feeState:h,address:g,validators:m,options:p,fromAddresses:A}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const c=(A??this.getAddresses("P")).map((e=>x(e)[2])),f=x(this.getChangeAddress("P"))[2],l=p?.changeAddresses??[f],v=m.map((({nodeId:e,pubKey:s,signature:t,balance:r,weight:a,deactivationOwner:h,remainingBalanceOwner:g})=>{const m=new d.ProofOfPossession(Uint8Array.from(o.hexToBuffer(s)),Uint8Array.from(o.hexToBuffer(t))),u=n.fromNative(g.addresses.map((e=>x(e)[2])),g.threshold??1),p=n.fromNative(h.addresses.map((e=>x(e)[2])),h.threshold??1);return i.fromNative(e,a,r,m,u,p)}));return t.e.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:v,fromAddressesBytes:c,address:x(g)[2],chainId:s,subnetId:r,subnetAuth:a,feeState:h,utxos:u(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:s,signature:r,message:d,feeState:n,fromAddresses:i,options:a}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const h=(i??this.getAddresses("P")).map((e=>x(e)[2])),g=x(this.getChangeAddress("P"))[2],m=a?.changeAddresses??[g];return t.e.newRegisterL1ValidatorTx({utxos:u(e.getUTXOs(),!0),balance:s,blsSignature:Uint8Array.from(o.hexToBuffer(r)),changeAddressesBytes:m,feeState:n,fromAddressesBytes:h,memo:a?.memo,message:Uint8Array.from(o.hexToBuffer(d)),minIssuanceTime:a?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:s,message:r,options:d,fromAddresses:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(n??this.getAddresses("P")).map((e=>x(e)[2])),a=x(this.getChangeAddress("P"))[2],h=d?.changeAddresses??[a];return t.e.newSetL1ValidatorWeightTx({utxos:u(e.getUTXOs(),!0),changeAddressesBytes:h,feeState:s,fromAddressesBytes:i,memo:d?.memo,message:Uint8Array.from(o.hexToBuffer(r)),minIssuanceTime:d?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:s,options:r,fromAddresses:d,disableAuth:o,validationId:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(d??this.getAddresses("P")).map((e=>x(e)[2])),a=x(this.getChangeAddress("P"))[2],h=r?.changeAddresses??[a];return t.e.newDisableL1ValidatorTx({disableAuth:o,validationId:n,utxos:u(e.getUTXOs(),!0),changeAddressesBytes:h,feeState:s,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:s,options:r,fromAddresses:d,balance:o,validationId:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(d??this.getAddresses("P")).map((e=>x(e)[2])),a=x(this.getChangeAddress("P"))[2],h=r?.changeAddresses??[a];return t.e.newIncreaseL1ValidatorBalanceTx({balance:o,validationId:n,utxos:u(e.getUTXOs(),!0),changeAddressesBytes:h,feeState:s,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:s,chainName:r,vmID:d,fxIds:o,genesisData:n,subnetAuth:i,feeState:a,options:h,fromAddresses:g}){const m=u(e.getUTXOs(),!0),p=(g??this.getAddresses("P")).map((e=>x(e)[2])),A=x(this.getChangeAddress("P"))[2],f=h?.changeAddresses??[A];return this.provider.isEtnaEnabled()?(c(a),t.e.newCreateChainTx({chainName:r,feeState:a,fromAddressesBytes:p,fxIds:o,genesisData:n,subnetAuth:i,subnetId:s,utxos:m,vmId:d,changeAddressesBytes:f},this.provider.getContext())):t.newCreateBlockchainTx(this.provider.getContext(),m,p,s,r,d,o,n,i,h)}createSubnet({utxoSet:e,rewardAddresses:s,feeState:r,fromAddresses:d,options:o,threshold:n,locktime:i}){const a=u(e.getUTXOs(),!0),h=(d??this.getAddresses("P")).map((e=>x(e)[2])),g=x(this.getChangeAddress("P"))[2],m=o?.changeAddresses??[g],p=s.map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(r),t.e.newCreateSubnetTx({fromAddressesBytes:h,changeAddressesBytes:m,utxos:a,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,feeState:r,threshold:n,locktime:i,subnetOwners:p},this.provider.getContext())):t.newCreateSubnetTx(this.provider.getContext(),a,h,p,o,n??1,i??BigInt(0))}addSubnetValidator({utxoSet:e,nodeId:s,start:r,end:d,weight:o,subnetId:n,subnetAuth:i,feeState:a,fromAddresses:h,options:g}){const m=u(e.getUTXOs(),!0),p=(h??this.getAddresses("P")).map((e=>x(e)[2])),A=x(this.getChangeAddress("P"))[2],f=g?.changeAddresses??[A];return this.provider.isEtnaEnabled()?(c(a),t.e.newAddSubnetValidatorTx({changeAddressesBytes:f,fromAddressesBytes:p,utxos:m,minIssuanceTime:g?.minIssuanceTime,memo:g?.memo,nodeId:s,start:r,end:d,weight:o,subnetId:n,subnetAuth:i,feeState:a},this.provider.getContext())):t.newAddSubnetValidatorTx(this.provider.getContext(),m,p,s,r,d,o,n,i,g)}addPermissionlessValidator({utxoSet:e,nodeId:s,start:r,end:d,weight:o,subnetId:n,shares:i,feeState:h,fromAddresses:g,rewardAddresses:m,delegatorRewardAddresses:u,publicKey:A,signature:f,options:l,threshold:v,locktime:T,stakingAssetId:C}){const b=p(e.getUTXOs()),w=(g??this.getAddresses("P")).map((e=>x(e)[2])),I=(m??[this.getCurrentAddress("P")]).map((e=>x(e)[2])),S=(u??[this.getCurrentAddress("P")]).map((e=>x(e)[2]));if(!(n!==a.PrimaryNetworkID.toString()||A&&f))throw new Error("Must provide public key and signature for primary subnet.");const E=x(this.getChangeAddress("P"))[2],P=l?.changeAddresses??[E];if(this.provider.isEtnaEnabled())return c(h),t.e.newAddPermissionlessValidatorTx({fromAddressesBytes:w,delegatorRewardsOwner:S,utxos:b,minIssuanceTime:l?.minIssuanceTime,memo:l?.memo,changeAddressesBytes:P,nodeId:s,start:r,end:d,weight:o,subnetId:n,shares:i,feeState:h,publicKey:A,rewardAddresses:I,signature:f,locktime:T,threshold:v,stakingAssetId:C},this.provider.getContext());const B={changeAddresses:[E],...l??{}};return t.newAddPermissionlessValidatorTx(this.provider.getContext(),b,w,s,n,r,d,o,I,S,i,B,void 0,void 0,A,f)}addPermissionlessDelegator({utxoSet:e,nodeId:s,start:r,end:d,weight:o,subnetId:n,fromAddresses:i,rewardAddresses:a,options:h,locktime:g,feeState:m,threshold:u,stakingAssetId:A}){const f=p(e.getUTXOs()),l=(i??this.getAddresses("P")).map((e=>x(e)[2])),v=(a??[this.getCurrentAddress("P")]).map((e=>x(e)[2])),T=x(this.getChangeAddress("P"))[2],C=h?.changeAddresses??[T];if(this.provider.isEtnaEnabled())return c(m),t.e.newAddPermissionlessDelegatorTx({fromAddressesBytes:l,utxos:f,minIssuanceTime:h?.minIssuanceTime,memo:h?.memo,changeAddressesBytes:C,nodeId:s,start:r,end:d,weight:o,subnetId:n,rewardAddresses:v,locktime:g,stakingAssetId:A,threshold:u,feeState:m},this.provider.getContext());const b={changeAddresses:[T],...h??{}};return t.newAddPermissionlessDelegatorTx(this.provider.getContext(),f,l,s,n,r,d,o,v,b,void 0,void 0)}removeSubnetValidator({utxoSet:e,nodeId:s,subnetId:r,subnetAuth:d,fromAddresses:o,feeState:n,options:i}){const a=u(e.getUTXOs(),!0),h=(o??this.getAddresses("P")).map((e=>x(e)[2])),g=x(this.getChangeAddress("P"))[2],m=i?.changeAddresses??[g];return this.provider.isEtnaEnabled()?(c(n),t.e.newRemoveSubnetValidatorTx({changeAddressesBytes:m,fromAddressesBytes:h,utxos:a,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:s,subnetId:r,subnetAuth:d,feeState:n},this.provider.getContext())):t.newRemoveSubnetValidatorTx(this.provider.getContext(),a,h,s,r,d,i)}transferSubnetOwnershipTx({utxoSet:e,subnetId:s,subnetAuth:r,subnetOwners:d,feeState:o,fromAddresses:n,options:i,threshold:a,locktime:h}){const g=u(e.getUTXOs(),!0),m=(n??this.getAddresses("P")).map((e=>x(e)[2])),p=x(this.getChangeAddress("P"))[2],A=i?.changeAddresses??[p],f=d.map((e=>x(e)[2]));return this.provider.isEtnaEnabled()?(c(o),t.e.newTransferSubnetOwnershipTx({changeAddressesBytes:A,fromAddressesBytes:m,utxos:g,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:s,subnetAuth:r,subnetOwners:f,feeState:o,threshold:a,locktime:h},this.provider.getContext())):t.newTransferSubnetOwnershipTx(this.provider.getContext(),g,m,s,r,f,i,a??1,h??BigInt(0))}transformSubnetTx(e,s,r,d,o,n,i,a,h,g,m,p,A,c,f,v,T,C){const b=u(e.getUTXOs(),!0),w=(T??this.getAddresses("P")).map((e=>x(e)[2]));if(this.provider.isEtnaEnabled())throw l;return t.newTransformSubnetTx(this.provider.getContext(),b,w,s,r,d,o,n,i,a,h,g,m,p,A,c,f,v,C)}}export{v as WalletAbstract};
1
+ import{TransferableOutput as e,avm as s,pvm as t,evm as r,pvmSerial as d,utils as o,PChainOwner as n,L1Validator as i,networkIDs as a}from"@avalabs/avalanchejs";import"../utils/populateCredential.js";import"@avalabs/glacier-sdk";import{strip0x as h}from"@avalabs/core-utils-sdk";import"ethers";import"../providers/constants.js";import"@avalabs/core-chains-sdk";import"create-hash";import"bip32";import{getUTXOsForAddresses as m}from"../utils/getAllUTXOs.js";import{getStakeForAddresses as g}from"../utils/getStakeForAddresses.js";import"bip39";import"xss";import{sortUTXOsByAmount as u,sortUTXOsByAmountAscending as p,sortUTXOsStaking as A}from"../utils/sortUTXOs.js";import"bip32-path";import{assertFeeStateProvided as c}from"../../utils/assertFeeStateProvided.js";const{parse:f,hexToBuffer:x}=o;class l{constructor(e){this.provider=e}setProvider(e){this.provider=e}getProvider(){return this.provider}async getUTXOs(e){const s=this.provider.getApi(e);return m(this.getAddresses(e),s)}async getStake(){const e=this.provider.getApiP();return g(this.getAddresses("P"),e)}async getAtomicUTXOs(e,s){if(e===s)throw new Error("Chain can not be the same as source chain.");const t=this.provider.getApi(e),r=this.provider.getChainID(s);return m(this.getAddresses(e),t,{sourceChain:r,addresses:[]})}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportX(t,r,d,o){o=o||this.getCurrentAddress(d);const n=f(o)[2],i=this.provider.getAvaxID(),a=e.fromNative(i,t,[n]),h=u(r.getUTXOs(),!0),m=this.provider.getChainID(d),g=this.getAddresses("X").map((e=>f(e)[2])),p=f(this.getChangeAddress("X"))[2];return s.newExportTx(this.provider.getContext(),m,g,h,[a],{threshold:1,changeAddresses:[p]})}importP({utxoSet:e,sourceChain:s,toAddress:r,threshold:d,feeState:o,locktime:n}){const i=this.provider.getChainID(s),a=this.getAddresses("P").map((e=>f(e)[2]));f(this.getChangeAddress("P"))[2],r=r||this.getCurrentAddress("P");const h=f(r)[2],m=e.getUTXOs();return c(o),t.newImportTx({fromAddressesBytes:a,utxos:m,toAddressesBytes:[h],sourceChainId:i,threshold:d,feeState:o,locktime:n},this.provider.getContext())}importX(e,t,r){const d=this.provider.getChainID(t),o=this.getAddresses("X").map((e=>f(e)[2])),n=f(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const i=f(r)[2];return s.newImportTx(this.provider.getContext(),d,e.getUTXOs(),[i],o,{changeAddresses:[n]})}importC(e,s,t,d,o){const n=this.provider.getChainID(s),i=this.getAddresses("C").map((e=>f(e)[2]));o=o||this.getAddressEVM();const a=Buffer.from(h(o),"hex");return r.newImportTxFromBaseFee(this.provider.getContext(),a,i,e.getUTXOs(),n,t,d)}exportC(e,s,t,d,o){const n=x(this.getAddressEVM()),i=this.provider.getChainID(s);o=o||this.getCurrentAddress(s);const a=f(o)[2],h=d/BigInt(1e9);return r.newExportTxFromBaseFee(this.provider.getContext(),h,e,i,n,[a],t)}exportP({amount:s,utxoSet:r,destination:d,feeState:o,toAddress:n}){n=n||this.getCurrentAddress(d);const i=f(n)[2],a=this.provider.getAvaxID(),h=e.fromNative(a,s,[i]),m=u(r.getUTXOs(),!0),g=this.provider.getChainID(d),p=this.getAddresses("P").map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2];return c(o),t.newExportTx({changeAddressesBytes:[A],fromAddressesBytes:p,utxos:m,outputs:[h],destinationChainId:g,feeState:o},this.provider.getContext())}consolidateP({utxoSet:s,amount:r,feeState:d,toAddress:o,options:n}){const i=p(s.getUTXOs());o=o??this.getCurrentAddress("P");const a=f(o)[2],h=this.provider.getContext(),m=[e.fromNative(h.avaxAssetID,r,[a])],g=this.getAddresses("P").map((e=>f(e)[2])),u=f(this.getChangeAddress("P"))[2],A=n?.changeAddresses??[u];return c(d),t.newBaseTx({changeAddressesBytes:A,fromAddressesBytes:g,utxos:i,outputs:m,minIssuanceTime:n?.minIssuanceTime,memo:n?.memo,feeState:d},h)}baseTX({utxoSet:r,chain:d,toAddress:o,amountsPerAsset:n,feeState:i,options:a,fromAddresses:h}){const[m,g,p]=f(o);if(m!==d||g!==this.provider.getHrp())throw new Error(`Invalid recipient address "${o}"`);const A=Object.entries(n).map((([s,t])=>e.fromNative(s,t,[p]))),x=u(r.getUTXOs(),!0),l=(h??this.getAddresses(d)).map((e=>f(e)[2])),I=f(this.getChangeAddress("P"))[2],T=a?.changeAddresses??[I];return"X"===d?s.newBaseTx(this.provider.getContext(),l,x,A,a):(c(i),t.newBaseTx({changeAddressesBytes:T,fromAddressesBytes:l,utxos:x,outputs:A,minIssuanceTime:a?.minIssuanceTime,memo:a?.memo,feeState:i},this.provider.getContext()))}convertSubnetToL1({utxoSet:e,chainId:s,subnetId:r,subnetAuth:a,feeState:h,address:m,validators:g,options:p,fromAddresses:A}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const c=(A??this.getAddresses("P")).map((e=>f(e)[2])),x=f(this.getChangeAddress("P"))[2],l=p?.changeAddresses??[x],I=g.map((({nodeId:e,pubKey:s,signature:t,balance:r,weight:a,deactivationOwner:h,remainingBalanceOwner:m})=>{const g=new d.ProofOfPossession(Uint8Array.from(o.hexToBuffer(s)),Uint8Array.from(o.hexToBuffer(t))),u=n.fromNative(m.addresses.map((e=>f(e)[2])),m.threshold??1),p=n.fromNative(h.addresses.map((e=>f(e)[2])),h.threshold??1);return i.fromNative(e,a,r,g,u,p)}));return t.newConvertSubnetToL1Tx({changeAddressesBytes:l,validators:I,fromAddressesBytes:c,address:f(m)[2],chainId:s,subnetId:r,subnetAuth:a,feeState:h,utxos:u(e.getUTXOs(),!0)},this.provider.getContext())}registerL1Validator({utxoSet:e,balance:s,signature:r,message:d,feeState:n,fromAddresses:i,options:a}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const h=(i??this.getAddresses("P")).map((e=>f(e)[2])),m=f(this.getChangeAddress("P"))[2],g=a?.changeAddresses??[m];return t.newRegisterL1ValidatorTx({utxos:u(e.getUTXOs(),!0),balance:s,blsSignature:Uint8Array.from(o.hexToBuffer(r)),changeAddressesBytes:g,feeState:n,fromAddressesBytes:h,memo:a?.memo,message:Uint8Array.from(o.hexToBuffer(d)),minIssuanceTime:a?.minIssuanceTime},this.provider.getContext())}setL1ValidatorWeight({utxoSet:e,feeState:s,message:r,options:d,fromAddresses:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(n??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],h=d?.changeAddresses??[a];return t.newSetL1ValidatorWeightTx({utxos:u(e.getUTXOs(),!0),changeAddressesBytes:h,feeState:s,fromAddressesBytes:i,memo:d?.memo,message:Uint8Array.from(o.hexToBuffer(r)),minIssuanceTime:d?.minIssuanceTime},this.provider.getContext())}disableL1Validator({utxoSet:e,feeState:s,options:r,fromAddresses:d,disableAuth:o,validationId:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(d??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],h=r?.changeAddresses??[a];return t.newDisableL1ValidatorTx({disableAuth:o,validationId:n,utxos:u(e.getUTXOs(),!0),changeAddressesBytes:h,feeState:s,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}increaseL1ValidatorBalance({utxoSet:e,feeState:s,options:r,fromAddresses:d,balance:o,validationId:n}){if(!this.provider.isEtnaEnabled())throw new Error("Not supported prior to E-upgrade");const i=(d??this.getAddresses("P")).map((e=>f(e)[2])),a=f(this.getChangeAddress("P"))[2],h=r?.changeAddresses??[a];return t.newIncreaseL1ValidatorBalanceTx({balance:o,validationId:n,utxos:u(e.getUTXOs(),!0),changeAddressesBytes:h,feeState:s,fromAddressesBytes:i,memo:r?.memo,minIssuanceTime:r?.minIssuanceTime},this.provider.getContext())}createBlockchain({utxoSet:e,subnetId:s,chainName:r,vmID:d,fxIds:o,genesisData:n,subnetAuth:i,feeState:a,options:h,fromAddresses:m}){const g=u(e.getUTXOs(),!0),p=(m??this.getAddresses("P")).map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2],x=h?.changeAddresses??[A];return c(a),t.newCreateChainTx({chainName:r,feeState:a,fromAddressesBytes:p,fxIds:o,genesisData:n,subnetAuth:i,subnetId:s,utxos:g,vmId:d,changeAddressesBytes:x},this.provider.getContext())}createSubnet({utxoSet:e,rewardAddresses:s,feeState:r,fromAddresses:d,options:o,threshold:n,locktime:i}){const a=u(e.getUTXOs(),!0),h=(d??this.getAddresses("P")).map((e=>f(e)[2])),m=f(this.getChangeAddress("P"))[2],g=o?.changeAddresses??[m],p=s.map((e=>f(e)[2]));return c(r),t.newCreateSubnetTx({fromAddressesBytes:h,changeAddressesBytes:g,utxos:a,minIssuanceTime:o?.minIssuanceTime,memo:o?.memo,feeState:r,threshold:n,locktime:i,subnetOwners:p},this.provider.getContext())}addSubnetValidator({utxoSet:e,nodeId:s,start:r,end:d,weight:o,subnetId:n,subnetAuth:i,feeState:a,fromAddresses:h,options:m}){const g=u(e.getUTXOs(),!0),p=(h??this.getAddresses("P")).map((e=>f(e)[2])),A=f(this.getChangeAddress("P"))[2],x=m?.changeAddresses??[A];return c(a),t.newAddSubnetValidatorTx({changeAddressesBytes:x,fromAddressesBytes:p,utxos:g,minIssuanceTime:m?.minIssuanceTime,memo:m?.memo,nodeId:s,start:r,end:d,weight:o,subnetId:n,subnetAuth:i,feeState:a},this.provider.getContext())}addPermissionlessValidator({utxoSet:e,nodeId:s,start:r,end:d,weight:o,subnetId:n,shares:i,feeState:h,fromAddresses:m,rewardAddresses:g,delegatorRewardAddresses:u,publicKey:p,signature:x,options:l,threshold:I,locktime:T,stakingAssetId:v}){const C=A(e.getUTXOs()),b=(m??this.getAddresses("P")).map((e=>f(e)[2])),S=(g??[this.getCurrentAddress("P")]).map((e=>f(e)[2])),w=(u??[this.getCurrentAddress("P")]).map((e=>f(e)[2]));if(!(n!==a.PrimaryNetworkID.toString()||p&&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 c(h),t.newAddPermissionlessValidatorTx({fromAddressesBytes:b,delegatorRewardsOwner:w,utxos:C,minIssuanceTime:l?.minIssuanceTime,memo:l?.memo,changeAddressesBytes:B,nodeId:s,start:r,end:d,weight:o,subnetId:n,shares:i,feeState:h,publicKey:p,rewardAddresses:S,signature:x,locktime:T,threshold:I,stakingAssetId:v},this.provider.getContext())}addPermissionlessDelegator({utxoSet:e,nodeId:s,start:r,end:d,weight:o,subnetId:n,fromAddresses:i,rewardAddresses:a,options:h,locktime:m,feeState:g,threshold:u,stakingAssetId:p}){const x=A(e.getUTXOs()),l=(i??this.getAddresses("P")).map((e=>f(e)[2])),I=(a??[this.getCurrentAddress("P")]).map((e=>f(e)[2])),T=f(this.getChangeAddress("P"))[2],v=h?.changeAddresses??[T];return c(g),t.newAddPermissionlessDelegatorTx({fromAddressesBytes:l,utxos:x,minIssuanceTime:h?.minIssuanceTime,memo:h?.memo,changeAddressesBytes:v,nodeId:s,start:r,end:d,weight:o,subnetId:n,rewardAddresses:I,locktime:m,stakingAssetId:p,threshold:u,feeState:g},this.provider.getContext())}removeSubnetValidator({utxoSet:e,nodeId:s,subnetId:r,subnetAuth:d,fromAddresses:o,feeState:n,options:i}){const a=u(e.getUTXOs(),!0),h=(o??this.getAddresses("P")).map((e=>f(e)[2])),m=f(this.getChangeAddress("P"))[2],g=i?.changeAddresses??[m];return c(n),t.newRemoveSubnetValidatorTx({changeAddressesBytes:g,fromAddressesBytes:h,utxos:a,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,nodeId:s,subnetId:r,subnetAuth:d,feeState:n},this.provider.getContext())}transferSubnetOwnershipTx({utxoSet:e,subnetId:s,subnetAuth:r,subnetOwners:d,feeState:o,fromAddresses:n,options:i,threshold:a,locktime:h}){const m=u(e.getUTXOs(),!0),g=(n??this.getAddresses("P")).map((e=>f(e)[2])),p=f(this.getChangeAddress("P"))[2],A=i?.changeAddresses??[p],x=d.map((e=>f(e)[2]));return c(o),t.newTransferSubnetOwnershipTx({changeAddressesBytes:A,fromAddressesBytes:g,utxos:m,minIssuanceTime:i?.minIssuanceTime,memo:i?.memo,subnetId:s,subnetAuth:r,subnetOwners:x,feeState:o,threshold:a,locktime:h},this.provider.getContext())}}export{l as WalletAbstract};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avalabs/core-wallets-sdk",
3
- "version": "3.1.0-alpha.31",
3
+ "version": "3.1.0-alpha.33",
4
4
  "license": "Limited Ecosystem License",
5
5
  "private": false,
6
6
  "main": "dist/index.js",
@@ -30,9 +30,9 @@
30
30
  "ts-jest": "29.1.2"
31
31
  },
32
32
  "dependencies": {
33
- "@avalabs/avalanchejs": "4.1.2-alpha.3",
34
- "@avalabs/core-chains-sdk": "3.1.0-alpha.31",
35
- "@avalabs/glacier-sdk": "3.1.0-alpha.31",
33
+ "@avalabs/avalanchejs": "4.2.0-alpha.1",
34
+ "@avalabs/core-chains-sdk": "3.1.0-alpha.33",
35
+ "@avalabs/glacier-sdk": "3.1.0-alpha.33",
36
36
  "@avalabs/hw-app-avalanche": "0.14.1",
37
37
  "@ledgerhq/hw-app-btc": "10.2.4",
38
38
  "@ledgerhq/hw-app-eth": "6.36.1",
@@ -52,5 +52,5 @@
52
52
  "peerDependencies": {
53
53
  "ethers": "^6.7.1"
54
54
  },
55
- "gitHead": "44cae5d5baf78cc5f69f7824b98350f5fb87edad"
55
+ "gitHead": "fce765e5ec99ef943b575fb35a0dc399d76c921e"
56
56
  }
@@ -1 +0,0 @@
1
- import{pvmSerial as e}from"@avalabs/avalanchejs";import{TxType as a}from"../../models.js";import{getTransferableOutputAmount as t}from"./utils/getTransferableAmount.js";const r=r=>e.isAddDelegatorTx(r)?({feeData:e,assetId:s})=>({type:a.AddDelegator,chain:r.getVM(),stake:t(r.stake,s),stakeOuts:r.stake,rewardOwner:r.getRewardsOwner(),nodeID:r.validator.nodeId.value(),start:r.validator.startTime.value().toString(),end:r.validator.endTime.value().toString(),...e}):null;export{r as default};
@@ -1 +0,0 @@
1
- import{pvmSerial as a}from"@avalabs/avalanchejs";import{TxType as e}from"../../models.js";import{getTransferableOutputAmount as t}from"./utils/getTransferableAmount.js";const r=r=>a.isAddValidatorTx(r)?({feeData:a,assetId:s})=>({type:e.AddValidator,chain:r.getVM(),nodeID:r.validator.nodeId.value(),delegationFee:r.shares.value(),stake:t(r.stake,s),stakeOuts:r.stake,start:r.validator.startTime.value().toString(),end:r.validator.endTime.value().toString(),rewardOwner:r.getRewardsOwner(),...a}):null;export{r as default};
@@ -1 +0,0 @@
1
- import{pvmSerial as a}from"@avalabs/avalanchejs";import{TxType as e}from"../../models.js";const t=t=>a.isTransformSubnetTx(t)?({feeData:a})=>({type:e.TransformSubnet,chain:t.getVM(),subnetID:t.subnetID.toString(),assetID:t.assetId.toString(),initialSupply:t.initialSupply.value(),maximumSupply:t.maximumSupply.value(),minConsumptionRate:t.minConsumptionRate.value(),maxConsumptionRate:t.maxConsumptionRate.value(),minValidatorStake:t.minValidatorStake.value(),maxValidatorStake:t.maxValidatorStake.value(),minStakeDuration:t.minStakeDuration.value(),maxStakeDuration:t.maxStakeDuration.value(),minDelegationFee:t.minDelegationFee.value(),minDelegatorStake:t.minDelegatorStake.value(),maxValidatorWeightFactor:Number(t.maxValidatorWeightFactor.toJSON()),uptimeRequirement:t.uptimeRequirement.value(),...a}):null;export{t as default};