@avalabs/core-wallets-sdk 3.1.0-alpha.7 → 3.1.0-alpha.8
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
|
@@ -147,6 +147,7 @@ declare abstract class BitcoinProviderAbstract {
|
|
|
147
147
|
medium: number;
|
|
148
148
|
low: number;
|
|
149
149
|
}>;
|
|
150
|
+
abstract getAddressFromScript(script: string): Promise<string>;
|
|
150
151
|
}
|
|
151
152
|
|
|
152
153
|
declare class BitcoinProvider extends BitcoinProviderAbstract {
|
|
@@ -159,6 +160,7 @@ declare class BitcoinProvider extends BitcoinProviderAbstract {
|
|
|
159
160
|
confirmed: BitcoinInputUTXOWithOptionalScript[];
|
|
160
161
|
unconfirmed: BitcoinInputUTXOWithOptionalScript[];
|
|
161
162
|
}>;
|
|
163
|
+
getAddressFromScript(script: string): Promise<string>;
|
|
162
164
|
getScriptsForUtxos(utxos: BitcoinInputUTXOWithOptionalScript[]): Promise<BitcoinInputUTXO[]>;
|
|
163
165
|
private _parseUtxo;
|
|
164
166
|
getBalances(address: string): Promise<{
|
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"),i=require("@avalabs/avalanchejs"),a=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/core-chains-sdk"),x=require("create-hash"),v=require("@avalabs/glacier-sdk"),w=require("xss"),y=require("bip32-path"),b=require("@avalabs/hw-app-avalanche");function A(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:A(r.confirmed),balanceUnconfirmed:A(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,i){const a=[{address:e,value:s}],{inputs:o,outputs:d,fee:u}=r(i,a,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,i){const a=S(e,t,r,s,P(n));return a.inputs?{...a,psbt:T(a.inputs,a.outputs,i)}:(console.log("Unable to construct transaction, fee needed: ",a.fee),a)}function C(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function k(e){return new s(e,"w0w")}const E="m/44'/60'",D=`${E}/0'`;var M=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(M||{});function V(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==M.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const K=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),O=(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 U=[{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,U,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 F(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=V(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=k(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=k(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,i=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+i.v),r:"0x"+i.r,s:"0x"+i.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...i}=t,a=n.TypedDataEncoder.getPrimaryType(i);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:a,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(a,r,t,p.SignTypedDataVersion.V4),i=p.TypedDataUtils.hashStruct("EIP712Domain",e,t,p.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,i.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function _(t,r,s,n,i,a){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,i,n,g.pathStringToArray(a))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function H(t,r,s,n){const i=new e.Psbt({network:r}),a=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<a;e++){const r=t.getInputWitnessUtxo(e),a=t.getInputBip32Derivation(e,s);i.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:a?[{path:n,pubkey:s,masterFingerprint:a.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)i.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return i}class R{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 $ extends R{keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=M.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),i=u.fromSeed(n),a=V(t,s,"EVM"),o=i.derivePath(a);if(!o.privateKey)throw new Error("Unable to derive private key from the given mnemonic.");return new $(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 $(s,t)}signPsbt(e){return e.signAllInputs(this.keypair),e.validateSignaturesOfAllInputs(),e.finalizeAllInputs(),e.extractTransaction()}}var L=(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.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))(L||{});const q=e=>{switch(e){case"C":return i.EVM;case"X":return i.AVM;case"P":return i.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}},{getTransferableInputsByTx:W,AddressMaps:j}=i.utils,J=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=W(e),o=j.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>i.pvmSerial.isCreateChainTx(e)||i.pvmSerial.isAddSubnetValidatorTx(e)||i.pvmSerial.isRemoveSubnetValidatorTx(e)||i.pvmSerial.isTransformSubnetTx(e)||i.pvmSerial.isTransferSubnetOwnershipTx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=(await t.getApiP().getTx({txID:e.getSubnetID().value()})).unsignedTx.getSubnetOwners().addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new i.utils.AddressMap(n)),r})({tx:e,provider:r,addressMaps:o});return new i.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}return new i.UnsignedTx(e,n,o,s)},{bufferToHex:z,packTx:G}=i.utils,{publicKeyBytesToAddress:Y,recoverPublicKey:Q}=i.secp256k1,Z=new i.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:i}=t,a=n.getCredentials()[i];if(!a)return s;const o=G(n.getTx()),d=m.sha256(o),u=Z.toString();for(const e of a.toJSON()){if(e.toString()===u)continue;const t=Q(d,e.toBytes()),r={toHex:()=>z(Y(t))},a=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of a)t[0]===i&&(s[t[1]]=e)}return s};function te(e){return i.utils.bufferToHex(i.utils.addChecksum(e.toBytes()))}const{getManagerForVM:re,hexToBuffer:se,unpackWithManager:ne}=i.utils,ie=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=q(t);if(n===i.EVM)throw new Error("EVM transactions are not supported");const a=se(e),o=ne(n,a),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=re(s).unpack(t,i.avaxSerial.SignedTx),o=await J({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new i.Credential(ee(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new i.Credential(ee(e))))}})({tx:o,txBytes:a,provider:r,vm:n,utxos:s});return J({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:ae,format:oe}=i.utils,{publicKeyBytesToAddress:de}=i.secp256k1;class ue{constructor(e,t){this.baseUrl=e,this.context=t;const r=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(r)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return i.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new i.avm.AVMApi(this.baseUrl)}getApiP(){return new i.pvm.PVMApi(this.baseUrl)}getApiC(){return new i.evm.EVMApi(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)),i=Buffer.from(s,"hex"),a=de(i);return oe(r,this.getHrp(),a)}getAddressFromBuffer(e,t){return oe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ae(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,a)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&a(new Error("Timeout")),d=s instanceof i.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={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"},le={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"};class pe extends ue{constructor(e,t){super(e,t)}static async fromBaseURL(e){const t=await i.Context.getContextFromURI(e);return new pe(e,t)}static getDefaultMainnetProvider(){return new pe(f.AVALANCHE_XP_NETWORK.rpcUrl,ce)}static getDefaultFujiProvider(){return new pe(f.AVALANCHE_XP_TEST_NETWORK.rpcUrl,le)}}const{bytesCompare:he,parseBech32:ge}=i.utils,me=(e,t)=>"P"===t,fe=(e,t,r)=>{const s=me(0,t)?e.amount:e.asset?.amount;return new i.TransferOutput(new i.BigIntPr(BigInt(s)),i.OutputOwners.fromNative(e.addresses.map((e=>ge(e)[1])).sort(he),BigInt(r??0),e.threshold))},xe=(e,t)=>{const r=((e,t)=>{const{cBlockchainID:r,xBlockchainID:s,pBlockchainID:n}=t?le:ce;if(r===e)return"C";if(s===e)return"X";if(n===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=me(0,r)?e.txHash:e.creationTxHash,n=me(0,r)?e.assetId:e.asset?.assetId;return new i.Utxo(i.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),i.Id.fromString(n),((e,t)=>me(0,t)?e.stakeableLocktime?new i.pvmSerial.StakeableLockOut(new i.BigIntPr(BigInt(e.stakeableLocktime??0)),fe(e,t,e.platformLocktime??0)):fe(e,t,e.platformLocktime):fe(e,t,e.locktime))(e,r))},{unpackWithManager:ve,parse:we,bufferToHex:ye,AddressMaps:be,AddressMap:Ae}=i.utils;function Ie(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 x("sha256").update(s).digest()}const Te=1024,Se=1024;async function Pe(e,t,r){const s=e.slice(0,Te),n=e.slice(Te),i=await Be(t,{...r,addresses:s});if(n.length){const s=await Pe(n,t,{...r,addresses:e});return i.merge(s)}return i}async function Be(e,t){if(t.addresses.length>Te)throw new Error(`Can not get UTXOs for more than ${Te} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new i.utils.UtxoSet(s);if(s.length>=Se){const s=await Be(e,{...t,startIndex:r});return n.merge(s)}return n}function Ce(){return BigInt(Math.floor(Date.now()/1e3))}const{isStakeableLockOut:ke,isTransferOut:Ee}=i.utils,De=e=>{const t=e.output,r=e.getOutputOwners();return{utxoId:e.ID(),assetId:e.getAssetId(),amount:Ee(t)||ke(t)?t.amount():BigInt(0),locktime:r.locktime.value(),stakeableLocktime:ke(t)?t.getStakeableLocktime():BigInt(0),threshold:r.threshold.value()}};async function Me(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await Me(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Ve,hexToBuffer:Ke,unpackWithManager:Oe}=i.utils;function Ue(e,t=!0){try{if(t){const[t]=i.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else i.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)),Fe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0)),Xe=e=>{if([ce.xBlockchainID,le.xBlockchainID].includes(e))return"AVM";if([ce.pBlockchainID,le.pBlockchainID].includes(e))return"PVM";if([ce.cBlockchainID,le.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")};var _e={parseAddValidatorTx:e=>i.pvmSerial.isAddValidatorTx(e)?({feeData:t,assetId:r})=>({type:L.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=>i.pvmSerial.isAddDelegatorTx(e)?({feeData:t,assetId:r})=>({type:L.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=>i.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:L.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>i.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:L.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=>i.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:L.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=>i.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:L.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>i.pvmSerial.isImportTx(e)||i.avmSerial.isImportTx(e)||i.evmSerial.isImportTx(e)?i.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:L.Import,chain:e.getVM(),source:Xe(e.sourceChain.value()),amount:Fe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:L.Import,chain:e.getVM(),source:Xe(e.sourceChain.value()),amount:Fe(e.ins,r),...t}):null,parseExportTx:e=>i.pvmSerial.isExportTx(e)||i.avmSerial.isExportTx(e)||i.evmSerial.isExportTx(e)?i.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:L.Export,chain:e.getVM(),destination:Xe(e.destinationChain.toString()),amount:Ne(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:L.Export,chain:e.getVM(),destination:Xe(e.destination.value()),amount:Ne(e.outs,r),...t}):null,parseBaseTx:e=>i.avmSerial.isAvmBaseTx(e)||i.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,a=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),i.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 i.TransferOutput){const i=n.assetId.value(),a=[...s.values()].indexOf(i),o=e[a],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:i,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===i}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof i.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=Ce(),d=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:L.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!i.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return i.pvmSerial.isSigner(e.signer)&&(r=i.utils.bufferToHex(e.signer.proof.publicKey),t=i.utils.bufferToHex(e.signer.proof.signature)),({feeData:s,assetId:n})=>({type:L.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=>i.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t,assetId:r})=>({type:L.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=>i.pvmSerial.isTransformSubnetTx(e)?({feeData:t})=>({type:L.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=>i.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:L.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};const{getBurnedAmountByTx:He,getOutputAmounts:Re,getInputAmounts:$e,validateBurnedAmount:Le}=i.utils;const{isStakeableLockOut:qe,isTransferOut:We}=i.utils;function je(e){return e.sort(((e,t)=>{const r=e.output,s=t.output,n=qe(r),i=qe(s);if(n&&!i)return-1;if(i&&!n)return 1;if(qe(r)&&qe(s)){const e=r.getStakeableLocktime(),t=s.getStakeableLocktime();if(e<t)return 1;if(e>t)return-1}else if(We(r)&&We(s)){if(r.amount()>s.amount())return-1;if(r.amount()<s.amount())return 1}return 0}))}function Je(e,t){return e.sort(((e,r)=>{const s=e.output,n=r.output;let i=BigInt(0);(We(s)||qe(s))&&(i=s.amount());let a=BigInt(0);(We(n)||qe(n))&&(a=n.amount());const o=t?a-i:i-a;return o>0?1:o<0?-1:0}))}const ze=e=>Je(e,!0),Ge=e=>Je(e,!1);var Ye=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Ye||{});const Qe="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",Ze="11111111111111111111111111111111LpoYY",et=(e,t)=>e.reduce(((e,t)=>e+De(t).amount),BigInt(0))-t,tt={BaseP:{sortFunction:ze,unsignedTxBuilder:(e,t)=>{const r=e.getProvider().getContext();return e.baseTX(new i.utils.UtxoSet(t),"P",e.getCurrentAddress("P"),{[r.avaxAssetID]:et(t,r.baseTxFee)})}},ConsolidateP:{sortFunction:Ge,unsignedTxBuilder:(e,t)=>{const r=e.getProvider().getContext();return e.consolidateP(new i.utils.UtxoSet(t),et(t,r.baseTxFee))}},AddPermissionlessValidator:{sortFunction:je,unsignedTxBuilder:(e,t)=>e.addPermissionlessValidator(new i.utils.UtxoSet(t),Qe,Ce(),Ce()+BigInt(1e3),et(t,e.getProvider().getContext().addPrimaryNetworkValidatorFee),Ze,5,void 0,void 0,void 0,Buffer.from(i.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),Buffer.from(i.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98")))},AddPermissionlessDelegator:{sortFunction:je,unsignedTxBuilder:(e,t)=>e.addPermissionlessDelegator(new i.utils.UtxoSet(t),Qe,Ce(),Ce()+BigInt(1e3),et(t,e.getProvider().getContext().addPrimaryNetworkDelegatorFee),Ze)},ExportP:{sortFunction:ze,unsignedTxBuilder:(e,t)=>e.exportP(et(t,e.getProvider().getContext().baseTxFee),new i.utils.UtxoSet(t),"X")},ImportP:{sortFunction:ze,unsignedTxBuilder:(e,t)=>e.importP(new i.utils.UtxoSet(t),"X")}};function rt(e){return y.validateString(e,!0)&&6===e.split("/").length}const{parse:st,hexToBuffer:nt}=i.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 Pe(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Me(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 Pe(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=st(s)[2],a=this.provider.getAvaxID(),o=i.TransferableOutput.fromNative(a,e,[n]),d=Je(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>st(e)[2])),l=st(this.getChangeAddress("X"))[2];return i.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("P").map((e=>st(e)[2])),a=st(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const o=st(r)[2];return i.pvm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[a]})}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>st(e)[2])),a=st(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=st(r)[2];return i.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[a]})}importC(e,r,s,n,a){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>st(e)[2]));a=a||this.getAddressEVM();const u=Buffer.from(t.strip0x(a),"hex");return i.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const a=nt(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=st(n)[2],u=s/BigInt(1e9);return i.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,a,[d],r)}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportP(e,t,r,s){s=s||this.getCurrentAddress(r);const n=st(s)[2],a=this.provider.getAvaxID(),o=i.TransferableOutput.fromNative(a,e,[n]),d=Je(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>st(e)[2])),l=st(this.getChangeAddress("P"))[2];return i.pvm.newExportTx(this.provider.getContext(),u,c,d,[o],{changeAddresses:[l]})}addValidator(e,t,r,s,n,a,o){const d=je(e.getUTXOs()),u=this.getAddresses("P").map((e=>st(e)[2])),c=o?.rewardAddress||this.getCurrentAddress("P"),l=st(c)[2],p=st(this.getChangeAddress("P"))[2];return i.pvm.newAddValidatorTx(this.provider.getContext(),d,u,t,s,n,r,[l],a,{changeAddresses:[p]})}addDelegator(e,t,r,s,n,a){const o=je(e.getUTXOs()),d=this.getAddresses("P").map((e=>st(e)[2])),u=a?.rewardAddress||this.getCurrentAddress("P"),c=st(u)[2],l=st(this.getChangeAddress("P"))[2];return i.pvm.newAddDelegatorTx(this.provider.getContext(),o,d,t,s,n,r,[c],{changeAddresses:[l]})}consolidateP(e,t,r,s){const n=Ge(e.getUTXOs());r=r??this.getCurrentAddress("P");const a=st(r)[2],o=this.provider.getContext(),d=[i.TransferableOutput.fromNative(o.avaxAssetID,t,[a])],u=this.getAddresses("P").map((e=>st(e)[2]));return i.pvm.newBaseTx(this.provider.getContext(),u,n,d,s)}baseTX(e,t,r,s,n,a){const[o,d,u]=st(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>i.TransferableOutput.fromNative(e,t,[u]))),l=Je(e.getUTXOs(),!0),p=(a??this.getAddresses(t)).map((e=>st(e)[2]));return"X"===t?i.avm.newBaseTx(this.provider.getContext(),p,l,c,n):i.pvm.newBaseTx(this.provider.getContext(),p,l,c,n)}createBlockchain(e,t,r,s,n,a,o,d,u){const c=Je(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newCreateBlockchainTx(this.provider.getContext(),c,l,t,r,s,n,a,o,d)}createSubnet(e,t,r,s,n,a){const o=Je(e.getUTXOs(),!0),d=(r??this.getAddresses("P")).map((e=>st(e)[2])),u=t.map((e=>st(e)[2]));return i.pvm.newCreateSubnetTx(this.provider.getContext(),o,d,u,s,n??1,a??BigInt(0))}addSubnetValidator(e,t,r,s,n,a,o,d,u){const c=Je(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newAddSubnetValidatorTx(this.provider.getContext(),c,l,t,r,s,n,a,o,u)}addPermissionlessValidator(e,t,r,s,n,a,o,d,u,c,l,p,h){const g=je(e.getUTXOs()),m=(d??this.getAddresses("P")).map((e=>st(e)[2])),f=(u??[this.getCurrentAddress("P")]).map((e=>st(e)[2])),x=(c??[this.getCurrentAddress("P")]).map((e=>st(e)[2]));if(!(a!==i.networkIDs.PrimaryNetworkID.toString()||l&&p))throw new Error("Must provide public key and signature for primary subnet.");const v={changeAddresses:[st(this.getChangeAddress("P"))[2]],...h??{}};return i.pvm.newAddPermissionlessValidatorTx(this.provider.getContext(),g,m,t,a,r,s,n,f,x,o,v,void 0,void 0,l,p)}addPermissionlessDelegator(e,t,r,s,n,a,o,d,u){const c=je(e.getUTXOs()),l=(o??this.getAddresses("P")).map((e=>st(e)[2])),p=(d??[this.getCurrentAddress("P")]).map((e=>st(e)[2])),h={changeAddresses:[st(this.getChangeAddress("P"))[2]],...u??{}};return i.pvm.newAddPermissionlessDelegatorTx(this.provider.getContext(),c,l,t,a,r,s,n,p,h,void 0,void 0)}removeSubnetValidator(e,t,r,s,n,a){const o=Je(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newRemoveSubnetValidatorTx(this.provider.getContext(),o,d,t,r,s,a)}transferSubnetOwnershipTx(e,t,r,s,n,a,o,d){const u=Je(e.getUTXOs(),!0),c=(n??this.getAddresses("P")).map((e=>st(e)[2])),l=s.map((e=>st(e)[2]));return i.pvm.newTransferSubnetOwnershipTx(this.provider.getContext(),u,c,t,r,l,a,o??1,d??BigInt(0))}transformSubnetTx(e,t,r,s,n,a,o,d,u,c,l,p,h,g,m,f,x,v){const w=Je(e.getUTXOs(),!0),y=(x??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newTransformSubnetTx(this.provider.getContext(),w,y,t,r,s,n,a,o,d,u,c,l,p,h,g,m,f,v)}}class at 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 i=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(i,"hex"),d=Buffer.from(a,"hex");return new at(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),i=u.fromSeed(n),a=i.derivePath(r),o=i.derivePath(t);return at.fromPublicKey(o.publicKey,a.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 ot={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),i=s.map((e=>e.toString(!0))),a=await n.signHash(r.toString(),i,t),o=a.signatures||new Map;return{hash:a.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const i=this.getApp(e),a=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await i.sign(r.toString(),a,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function dt(e){return!(await ot.getVersion(e)>="0.6.0")}const{parse:ut}=i.utils;class ct extends it{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new at(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(),i=s.derivePath(V(0,M.BIP44,"EVM")).neutered();return new ct(n.toBase58(),i.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(ut(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(ut(e)[2])))}getRawAddressC(){return Buffer.from(ut(this.getCurrentAddress("C"))[2])}}const{isTransferOut:lt,isStakeableLockOut:pt}=i.utils;function ht(e){const t=e.output;return lt(t)||pt(t)?t.getOwners():[]}function gt(e){const t=e.getTx();return i.avmSerial.isExportTx(t)||i.pvmSerial.isExportTx(t)?new Set(t.outs.map(ht).flat()):i.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(ht).flat()):new Set((t.baseTx?.outputs??[]).map(ht).flat())}const{parse:mt}=i.utils;class ft extends ct{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]=mt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await dt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=k(e),i=await ot.getXPUB(e,ft.getAccountPath("X")),a=u.fromPublicKey(i.pubKey,i.chainCode),o=V(0,M.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 ft(a.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"))),i=new Set([...s,...r??[]]),a=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(i.has(t)){const e=[...i].indexOf(t);o.add(`1/${e}`)}else if(a.has(t)){const e=[...a].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(),i=Buffer.from(t.toBytes()),a="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,a),u=this.getAdditionalAddressesByIndices(s??[],!0,a),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>y.fromString(e))),l=[...gt(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>y.fromString(e)));return(await this.signTxBuffer({buffer:i,chain:a,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=y.fromString(ft.getAccountPath(e.chain));return[...(await ot.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:xt}=i.utils;class vt extends ct{constructor(e,t,r){const s=u.fromBase58(e).neutered(),i=new n.SigningKey(t),a=Buffer.from(xt(i.compressedPublicKey),"hex");super(s.toBase58(),a,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'"),i=s.derivePath(V(0,M.BIP44,"EVM"));if(!i.privateKey)throw new Error("Unable to derive EVM private key.");return new vt(n.toBase58(),i.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await i.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:wt,sign:yt,signHash:bt}=i.secp256k1,{addChecksum:At}=i.utils;class It extends at{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(wt(e)),Buffer.from(wt(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),i=u.fromSeed(n),a=i.derivePath(t),o=i.derivePath(r);if(!a.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new It(a.privateKey,o.privateKey,s)}async signMessage(e){const t=Ie(e.message),r=this.getSigningKey(e.chain);return Buffer.from(At(await bt(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await i.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:Tt}=i.utils;class St extends at{constructor(e,t,r,s,a){const o=i.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=i.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),a),this.pathXP=t,this.pathC=s,!rt(t)||!rt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,i){if(await dt(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 a=new s(e),o=await a.getAddress(r,!1),d=await a.getAddress(t,!1),u=Buffer.from(Tt(o.publicKey),"hex"),c=Buffer.from(Tt(d.publicKey),"hex"),l=Buffer.from(Tt(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Tt(n.SigningKey.computePublicKey(c,!0)),"hex");return new St(p,t,l,r,i)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=y.fromString(this.getAccountPath(e.chain)),r=y.fromString(this.getPartialSignerPath(e.chain));return[...(await ot.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Pt}=i.utils;var Bt=Object.freeze({__proto__:null,AbstractProvider:ue,AddressWallet:class extends it{constructor(e,t,r,s,i){if(super(i),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=>!Ue(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!Ue(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(!Ue(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)}},FujiContext:le,JsonRpcProvider:pe,LedgerSigner:St,LedgerWallet:ft,MainnetContext:ce,MnemonicWallet:vt,MnemonicWalletVoid:ct,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 i.EVMUnsignedTx||"C"===t?i.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):i.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(Pt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),i=`0/${this.activeAccountIndex}`,a=new Map;if("C"===n||!this.accountNode)return a;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[i,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&a.set(t,e)}return a}getAddressBipPaths(e,t){return 0===t.size?[y.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(y.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),i=this.getAddressBipPaths(r.getAddresses(),n),a=this.getAddressBipPaths([...gt(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:i,change:a})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=y.fromString(this.getAccountPath(e.chain));return[...(await ot.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||y.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=Ie(e.message),s=(await ot.signHash(e.transport,r,y.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(V(t,M.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=this.getSigningKeys(n,r,s);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await i.addTxSignatures({unsignedTx:t,privateKeys:a}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=Ie(e.message),s=await i.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Ye,StaticSigner:It,TxType:L,WalletAbstract:it,WalletVoid:at,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await ie({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const o=a.getCredentials(),d=a.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 i.Credential(s)),e}),[]),u=new i.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,d);return{signedTxHex:te(new i.avaxSerial.SignedTx(a.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:xe,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=ve(r,e),a=we(t)[2],o=ye(a);if(i.evmSerial.isExportTx(n))return new i.EVMUnsignedTx(n,[],new be([Ae.fromJSON([[o,0]])]));if(i.evmSerial.isImportTx(n)){const e=be.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[a]);return new i.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:J,digestMessage:Ie,emptySignature:Z,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const i=n?"1":"0",a=u.fromBase58(e).derivePath(`${i}/${t}`).publicKey;return r.getAddress(a,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(),i=Ce();return n.forEach((e=>{const t=De(e);s[t.threshold>1?"multisig":t.locktime>i?"locked":t.stakeableLocktime>i?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getLedgerProvider:async function(e){return ot},getMaximumUtxoSet:function(e,t,r,s=65536){const{sortFunction:n,unsignedTxBuilder:i}=tt[r],a=Ce(),o=n(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=De(e);return t<a&&(s<a||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),d=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let i=-1;for(;s<=n;){const a=Math.floor((s+n)/2);t(e.slice(0,a+1))<=r?(i=a,s=a+1):n=a-1}return i}(o,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*De(t).threshold)),0);return 6+e.toBytes().length+t}(i(e,t))}catch(e){return console.log("Unable to estimate size of utxos",{e:e,utxos:t.map(De)}),s+1}}),s);return-1===d?[]:o.slice(0,d+1)},getPaginatedUTXOs:Be,getPchainUnixNow:async function(e){const t=e?pe.getDefaultFujiProvider():pe.getDefaultMainnetProvider(),r=await t.getApiP().getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:Me,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[i.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Pe,getUnixNow:Ce,getUtxoInfo:De,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,isTestnet:r,url:s,token:n,headers:a})=>{const o=q(t),d=Ke(e),u=Oe(o,d);if(i.evmSerial.isExportTx(u))return[];const c=(e=>{if(i.evmSerial.isImportTx(e)||i.avmSerial.isImportTx(e)||i.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case i.EVM:return v.BlockchainId.C_CHAIN;case i.AVM:return v.BlockchainId.X_CHAIN;case i.PVM:return v.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Ve(u),p=new v.Glacier({BASE:s,TOKEN:n,HEADERS:a}),h=r?v.Network.FUJI:v.Network.MAINNET,g=[...new Set(l.map((e=>e.utxoID.txID.toString())))],m=await Promise.all(g.map((e=>p.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:h,txHash:e}))));return l.reduce(((e,t)=>{const s=m.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const i=xe(n,r);return e.push(i),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:Ue,isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isObsidianApp:dt,isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===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){try{const s=t.getContext(),n=e.getTx(),a=(e=>{for(const t of Object.values(_e)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(n),o=He(n),d=Re(n),u=$e(n).get(s.avaxAssetID)??BigInt(0),c=o.get(s.avaxAssetID)??BigInt(0),l=d.get(s.avaxAssetID)??BigInt(0),{isValid:p,txFee:h}=Le({unsignedTx:e,context:s,burnedAmount:c,...i.evmSerial.isImportExportTx(n)&&{evmBaseFee:await t.getApiC().getBaseFee()/BigInt(1e9),evmFeeTolerance:50}});return await a({feeData:{totalAvaxBurned:c,totalAvaxOutput:l,totalAvaxInput:u,isValidAvaxBurnedAmount:p,txFee:h},assetId:s.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:L.Unknown}}},populateCredential:ee,signedTxToHex:te,sortUTXOsByAmount:Je,sortUTXOsByAmountAscending:Ge,sortUTXOsByAmountDescending:ze,sortUTXOsStaking:je,verifyDerivationPath:rt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Bt,exports.BitcoinLedgerWallet=class extends R{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(),i=await r.getMasterFingerprint(),a=_(e,t,n,Buffer.from(i,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(a,o,d),c=H(a,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,i){super(),this.isMainnet=e,this.extraParams=i;const a=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#r=new t.HttpClient(s||o,a);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#s=new t.HttpClient(n||d,a)}#r;#s;async#n(e){return this.isMainnet?(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){const r=await this.#r.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!r?.length)return{confirmed:[],unconfirmed:[]};const s=r.map(this._parseUtxo),n=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return n(s);return n(await this.getScriptsForUtxos(s))}async getScriptsForUtxos(e){const[t,r]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),s=r.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),n=s.length?(await this.#n(s)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...t,...r.map(((e,t)=>({...e,script:n[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(){const e={jsonrpc:"2.0",method:"estimatesmartfee"},t=await this.#n([{...e,id:"1",params:[1]},{...e,id:"2",params:[3]},{...e,id:"3",params:[6]}]).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(t[0]/1024)||1,medium:Math.ceil(t[1]/1024)||1,low:Math.ceil(t[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))),i=t.vout.filter((t=>!t.addresses?.includes(e))),a=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=a>o;let u=o-a;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=i.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=$,exports.BitcoinWalletAbstract=R,exports.BitcoinWalletVoid=class extends R{constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=M,exports.ETH_ACCOUNT_PATH=D,exports.ETH_COIN_PATH=E,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=_,exports.createPsbt=T,exports.createTransferTx=B,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=V,exports.getAddressFromXPub=function(e,t){const r=F(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=F,exports.getAppEth=k,exports.getBech32Address=C,exports.getBech32AddressFromXPub=function(e,t,r){return C(F(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),i=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:i.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=k(e),n=await s.getAddress(r??D,t,!0),i=new a;return i.publicKey=o.Buffer.from(n.publicKey,"hex"),i.chainCode=o.Buffer.from(n.chainCode,"hex"),i.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=A(e);if(!n)return 0;const{fee:i}=S(t,r,n,s,e);return n-i},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=k(e),i=V(t,r,s),a=await n.getAddress(i,!1,!1);return Buffer.from(a.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(i.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getTransferTxDetails=function(e,t,r,s,n){const i=S(e,t,r,s,P(n));return i.inputs||console.log("Unable to construct transaction, fee needed: ",i.fee),i},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),V(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=O,exports.isNativeTxn=K,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()))),i=new Set(t.map((e=>e.toLowerCase()))),a=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&i.has(e.to.toLowerCase())&&O(e,n)?s(e,{type:"erc20",contractAddress:e.to}):K(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",a);return{unsubscribe:()=>o.off("block",a)}},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=H,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"),i=require("@avalabs/avalanchejs"),a=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/core-chains-sdk"),x=require("create-hash"),v=require("@avalabs/glacier-sdk"),w=require("xss"),y=require("bip32-path"),b=require("@avalabs/hw-app-avalanche");function A(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:A(r.confirmed),balanceUnconfirmed:A(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,i){const a=[{address:e,value:s}],{inputs:o,outputs:d,fee:u}=r(i,a,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,i){const a=S(e,t,r,s,P(n));return a.inputs?{...a,psbt:T(a.inputs,a.outputs,i)}:(console.log("Unable to construct transaction, fee needed: ",a.fee),a)}function C(t,r){return e.payments.p2wpkh({pubkey:t,network:r}).address}function k(e){return new s(e,"w0w")}const E="m/44'/60'",D=`${E}/0'`;var M=(e=>(e.BIP44="bip44",e.LedgerLive="ledger_live",e))(M||{});function V(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==M.BIP44?`m/44'/${s}'/0'/0/${e}`:`m/44'/${s}'/${e}'/0/0`}const K=(e,t)=>t.has(e.from.toLowerCase())||t.has((e.to??"").toLowerCase()),O=(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 U=[{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,U,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 F(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=V(e,r,"EVM"),this.accountIndex=e,this.transport=t,this.derivationSpec=r,this._eth=k(t),n.defineProperties(this,{path:this.path,type:"default",provider:s??null})}setTransport(e){this._eth=k(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,i=await this._eth.signTransaction(this.path,s.slice(2),null);return r.signature={v:BigInt("0x"+i.v),r:"0x"+i.r,s:"0x"+i.s},r.serialized}connect(t){return new e(this.accountIndex,this.transport,this.derivationSpec,t)}async signTypedData(e,t,r){const{EIP712Domain:s,...i}=t,a=n.TypedDataEncoder.getPrimaryType(i);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:a,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(a,r,t,p.SignTypedDataVersion.V4),i=p.TypedDataUtils.hashStruct("EIP712Domain",e,t,p.SignTypedDataVersion.V4),o=await this._eth.signEIP712HashedMessage(this.path,i.toString("hex"),s.toString("hex"));return o.r="0x"+o.r,o.s="0x"+o.s,n.Signature.from(o).serialized}throw s}}};function _(t,r,s,n,i,a){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,i,n,g.pathStringToArray(a))})),r.forEach(((t,r)=>{const n=e.address.toOutputScript(t.address,s);o.setOutputAmount(r,t.value),o.setOutputScript(r,n)})),o}function H(t,r,s,n){const i=new e.Psbt({network:r}),a=t.getGlobalInputCount(),o=t.getGlobalOutputCount();for(let e=0;e<a;e++){const r=t.getInputWitnessUtxo(e),a=t.getInputBip32Derivation(e,s);i.addInput({nonWitnessUtxo:t.getInputNonWitnessUtxo(e),witnessUtxo:r?{value:r.amount,script:r.scriptPubKey}:void 0,hash:t.getInputPreviousTxid(e),index:t.getInputOutputIndex(e),bip32Derivation:a?[{path:n,pubkey:s,masterFingerprint:a.masterFingerprint}]:void 0})}for(let s=0;s<o;s++)i.addOutput({value:t.getOutputAmount(s),address:e.address.fromOutputScript(t.getOutputScript(s),r)});return i}class ${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 ${keypair;constructor(t,r){const s=e.ECPair.fromPrivateKey(t);super(s.publicKey,r),this.keypair=s}static async fromMnemonic(e,t,r,s=M.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),i=u.fromSeed(n),a=V(t,s,"EVM"),o=i.derivePath(a);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 L=(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.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))(L||{});const q=e=>{switch(e){case"C":return i.EVM;case"X":return i.AVM;case"P":return i.PVM;default:throw new Error(`Unable to get VM type for chain "${e}"`)}},{getTransferableInputsByTx:W,AddressMaps:j}=i.utils,J=async({tx:e,fromAddressBytes:t,provider:r,credentials:s,utxos:n})=>{const a=W(e),o=j.fromTransferableInputs(a,n,BigInt(Math.floor((new Date).getTime()/1e3)),t);if((e=>i.pvmSerial.isCreateChainTx(e)||i.pvmSerial.isAddSubnetValidatorTx(e)||i.pvmSerial.isRemoveSubnetValidatorTx(e)||i.pvmSerial.isTransformSubnetTx(e)||i.pvmSerial.isTransferSubnetOwnershipTx(e))(e))try{const t=await(async({tx:e,provider:t,addressMaps:r})=>{const s=e.getSubnetAuth().values(),n=(await t.getApiP().getTx({txID:e.getSubnetID().value()})).unsignedTx.getSubnetOwners().addrs.reduce(((e,t,r)=>(s.includes(r)&&e.push([t,r]),e)),[]);return r.push(new i.utils.AddressMap(n)),r})({tx:e,provider:r,addressMaps:o});return new i.UnsignedTx(e,n,t,s)}catch(e){throw new Error(`Error while preparing subnet authorization data: ${e.message}`)}return new i.UnsignedTx(e,n,o,s)},{bufferToHex:z,packTx:G}=i.utils,{publicKeyBytesToAddress:Y,recoverPublicKey:Q}=i.secp256k1,Z=new i.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:i}=t,a=n.getCredentials()[i];if(!a)return s;const o=G(n.getTx()),d=m.sha256(o),u=Z.toString();for(const e of a.toJSON()){if(e.toString()===u)continue;const t=Q(d,e.toBytes()),r={toHex:()=>z(Y(t))},a=n.addressMaps.getSigIndicesForAddress(r,!1)??[];for(const t of a)t[0]===i&&(s[t[1]]=e)}return s};function te(e){return i.utils.bufferToHex(i.utils.addChecksum(e.toBytes()))}const{getManagerForVM:re,hexToBuffer:se,unpackWithManager:ne}=i.utils,ie=async({transactionHex:e,chainAlias:t,provider:r,utxos:s})=>{const n=q(t);if(n===i.EVM)throw new Error("EVM transactions are not supported");const a=se(e),o=ne(n,a),d=await(async({tx:e,txBytes:t,provider:r,vm:s,utxos:n})=>{try{const a=re(s).unpack(t,i.avaxSerial.SignedTx),o=await J({tx:e,utxos:n,provider:r,credentials:a.getCredentials()});return e.getSigIndices().map(((e,t)=>new i.Credential(ee(e,{unsignedTx:o,credentialIndex:t}))))}catch(t){return e.getSigIndices().map((e=>new i.Credential(ee(e))))}})({tx:o,txBytes:a,provider:r,vm:n,utxos:s});return J({tx:o,provider:r,credentials:d,utxos:s})},{parseBech32:ae,format:oe}=i.utils,{publicKeyBytesToAddress:de}=i.secp256k1;class ue{constructor(e,t){this.baseUrl=e,this.context=t;const r=`${e}/ext/bc/C/rpc`;this.evmRpc=new n.JsonRpcProvider(r)}evmRpc;async getEvmFeeData(){return this.evmRpc.getFeeData()}getContext(){return this.context}getChainID(e){switch(e){case"X":return this.context.xBlockchainID;case"P":return this.context.pBlockchainID;case"C":return this.context.cBlockchainID}}getNetworkID(){return this.context.networkID}getHrp(){return i.networkIDs.getHRP(this.getNetworkID())}getApiX(){return new i.avm.AVMApi(this.baseUrl)}getApiP(){return new i.pvm.PVMApi(this.baseUrl)}getApiC(){return new i.evm.EVMApi(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)),i=Buffer.from(s,"hex"),a=de(i);return oe(r,this.getHrp(),a)}getAddressFromBuffer(e,t){return oe(t,this.getHrp(),e)}formatAddress(e,t){const[,r]=ae(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,a)=>{const o=async()=>{let d;switch(r&&n+r<Date.now()&&a(new Error("Timeout")),d=s instanceof i.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={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"},le={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"};class pe extends ue{constructor(e,t){super(e,t)}static async fromBaseURL(e){const t=await i.Context.getContextFromURI(e);return new pe(e,t)}static getDefaultMainnetProvider(){return new pe(f.AVALANCHE_XP_NETWORK.rpcUrl,ce)}static getDefaultFujiProvider(){return new pe(f.AVALANCHE_XP_TEST_NETWORK.rpcUrl,le)}}const{bytesCompare:he,parseBech32:ge}=i.utils,me=(e,t)=>"P"===t,fe=(e,t,r)=>{const s=me(0,t)?e.amount:e.asset?.amount;return new i.TransferOutput(new i.BigIntPr(BigInt(s)),i.OutputOwners.fromNative(e.addresses.map((e=>ge(e)[1])).sort(he),BigInt(r??0),e.threshold))},xe=(e,t)=>{const r=((e,t)=>{const{cBlockchainID:r,xBlockchainID:s,pBlockchainID:n}=t?le:ce;if(r===e)return"C";if(s===e)return"X";if(n===e)return"P";throw new Error(`Unknown chainId "${e}"`)})(e.createdOnChainId,t),s=me(0,r)?e.txHash:e.creationTxHash,n=me(0,r)?e.assetId:e.asset?.assetId;return new i.Utxo(i.avaxSerial.UTXOID.fromNative(s,Number(e.outputIndex)),i.Id.fromString(n),((e,t)=>me(0,t)?e.stakeableLocktime?new i.pvmSerial.StakeableLockOut(new i.BigIntPr(BigInt(e.stakeableLocktime??0)),fe(e,t,e.platformLocktime??0)):fe(e,t,e.platformLocktime):fe(e,t,e.locktime))(e,r))},{unpackWithManager:ve,parse:we,bufferToHex:ye,AddressMaps:be,AddressMap:Ae}=i.utils;function Ie(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 x("sha256").update(s).digest()}const Te=1024,Se=1024;async function Pe(e,t,r){const s=e.slice(0,Te),n=e.slice(Te),i=await Be(t,{...r,addresses:s});if(n.length){const s=await Pe(n,t,{...r,addresses:e});return i.merge(s)}return i}async function Be(e,t){if(t.addresses.length>Te)throw new Error(`Can not get UTXOs for more than ${Te} addresses.`);const{endIndex:r,utxos:s}=await e.getUTXOs(t),n=new i.utils.UtxoSet(s);if(s.length>=Se){const s=await Be(e,{...t,startIndex:r});return n.merge(s)}return n}function Ce(){return BigInt(Math.floor(Date.now()/1e3))}const{isStakeableLockOut:ke,isTransferOut:Ee}=i.utils,De=e=>{const t=e.output,r=e.getOutputOwners();return{utxoId:e.ID(),assetId:e.getAssetId(),amount:Ee(t)||ke(t)?t.amount():BigInt(0),locktime:r.locktime.value(),stakeableLocktime:ke(t)?t.getStakeableLocktime():BigInt(0),threshold:r.threshold.value()}};async function Me(e,t){const r=e.slice(0,256),s=e.slice(256),n=await t.getStake({addresses:r});if(s.length){const e=await Me(s,t);return{staked:n.staked+e.staked,stakedOutputs:[...n.stakedOutputs,...e.stakedOutputs]}}return n}const{getTransferableInputsByTx:Ve,hexToBuffer:Ke,unpackWithManager:Oe}=i.utils;function Ue(e,t=!0){try{if(t){const[t]=i.utils.parse(e);if(!["X","P","C"].includes(t))return!1}else i.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)),Fe=(e,t)=>e.reduce(((e,r)=>r.assetId.toString()!==t?e:e+r.input.amount()),BigInt(0)),Xe=e=>{if([ce.xBlockchainID,le.xBlockchainID].includes(e))return"AVM";if([ce.pBlockchainID,le.pBlockchainID].includes(e))return"PVM";if([ce.cBlockchainID,le.cBlockchainID].includes(e))return"EVM";throw new Error("Unknown chain id. Failed to get alias.")};var _e={parseAddValidatorTx:e=>i.pvmSerial.isAddValidatorTx(e)?({feeData:t,assetId:r})=>({type:L.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=>i.pvmSerial.isAddDelegatorTx(e)?({feeData:t,assetId:r})=>({type:L.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=>i.pvmSerial.isCreateSubnetTx(e)?({feeData:t,provider:r})=>({type:L.CreateSubnet,chain:e.getVM(),threshold:e.getSubnetOwners().threshold.value(),controlKeys:e.getSubnetOwners().addrs.map((e=>`P-${e.toString(r.getHrp())}`)),...t}):null,parseCreateChainTx:e=>i.pvmSerial.isCreateChainTx(e)?({feeData:t})=>({type:L.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=>i.pvmSerial.isAddSubnetValidatorTx(e)?({feeData:t})=>({type:L.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=>i.pvmSerial.isRemoveSubnetValidatorTx(e)?({feeData:t})=>({type:L.RemoveSubnetValidator,chain:e.getVM(),nodeID:e.nodeId.toString(),subnetID:e.getSubnetID().value(),...t}):null,parseImportTx:e=>i.pvmSerial.isImportTx(e)||i.avmSerial.isImportTx(e)||i.evmSerial.isImportTx(e)?i.evmSerial.isImportTx(e)?({feeData:t,assetId:r})=>({type:L.Import,chain:e.getVM(),source:Xe(e.sourceChain.value()),amount:Fe(e.importedInputs,r),...t}):({feeData:t,assetId:r})=>({type:L.Import,chain:e.getVM(),source:Xe(e.sourceChain.value()),amount:Fe(e.ins,r),...t}):null,parseExportTx:e=>i.pvmSerial.isExportTx(e)||i.avmSerial.isExportTx(e)||i.evmSerial.isExportTx(e)?i.evmSerial.isExportTx(e)?({feeData:t,assetId:r})=>({type:L.Export,chain:e.getVM(),destination:Xe(e.destinationChain.toString()),amount:Ne(e.exportedOutputs,r),...t}):({feeData:t,assetId:r})=>({type:L.Export,chain:e.getVM(),destination:Xe(e.destination.value()),amount:Ne(e.outs,r),...t}):null,parseBaseTx:e=>i.avmSerial.isAvmBaseTx(e)||i.pvmSerial.isPvmBaseTx(e)?async({feeData:t,currentAddress:r,provider:s})=>{const n=e.baseTx,a=await(async(e,t)=>{const r=e.baseTx,s=new Set;if(r.outputs.forEach((e=>{s.add(e.assetId.value())})),i.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 i.TransferOutput){const i=n.assetId.value(),a=[...s.values()].indexOf(i),o=e[a],d=n.output.outputOwners.addrs.map((e=>`X-${e.toString(t.getContext().hrp)}`));return[...r,{assetId:i,amount:n.output.amount(),locktime:n.output.getLocktime(),threshold:BigInt(n.output.getThreshold()),assetDescription:o,owners:d,isAvax:t.getContext().avaxAssetID===i}]}return r}),[])}return r.outputs.reduce(((e,r)=>{if(r.output instanceof i.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=Ce(),d=a.filter((e=>!(1===e.owners.length&&e.owners[0]===r&&e.locktime<=o)));return{type:L.Base,chain:e.getVM(),outputs:d,memo:w(Buffer.from(n.memo.toBytes()).toString("utf-8",4)),...t}}:null,parseAddPermissionlessValidatorTx:e=>{if(!i.pvmSerial.isAddPermissionlessValidatorTx(e))return null;let t,r;return i.pvmSerial.isSigner(e.signer)&&(r=i.utils.bufferToHex(e.signer.proof.publicKey),t=i.utils.bufferToHex(e.signer.proof.signature)),({feeData:s,assetId:n})=>({type:L.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=>i.pvmSerial.isAddPermissionlessDelegatorTx(e)?({feeData:t,assetId:r})=>({type:L.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=>i.pvmSerial.isTransformSubnetTx(e)?({feeData:t})=>({type:L.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=>i.pvmSerial.isTransferSubnetOwnershipTx(e)?({feeData:t,provider:r})=>({type:L.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};const{getBurnedAmountByTx:He,getOutputAmounts:$e,getInputAmounts:Re,validateBurnedAmount:Le}=i.utils;const{isStakeableLockOut:qe,isTransferOut:We}=i.utils;function je(e){return e.sort(((e,t)=>{const r=e.output,s=t.output,n=qe(r),i=qe(s);if(n&&!i)return-1;if(i&&!n)return 1;if(qe(r)&&qe(s)){const e=r.getStakeableLocktime(),t=s.getStakeableLocktime();if(e<t)return 1;if(e>t)return-1}else if(We(r)&&We(s)){if(r.amount()>s.amount())return-1;if(r.amount()<s.amount())return 1}return 0}))}function Je(e,t){return e.sort(((e,r)=>{const s=e.output,n=r.output;let i=BigInt(0);(We(s)||qe(s))&&(i=s.amount());let a=BigInt(0);(We(n)||qe(n))&&(a=n.amount());const o=t?a-i:i-a;return o>0?1:o<0?-1:0}))}const ze=e=>Je(e,!0),Ge=e=>Je(e,!1);var Ye=(e=>(e.ExportP="ExportP",e.ImportP="ImportP",e.AddPermissionlessValidator="AddPermissionlessValidator",e.AddPermissionlessDelegator="AddPermissionlessDelegator",e.BaseP="BaseP",e.ConsolidateP="ConsolidateP",e))(Ye||{});const Qe="NodeID-8TArWpFgH3sazEH8qP4gUjtGtFMvjw1aR",Ze="11111111111111111111111111111111LpoYY",et=(e,t)=>e.reduce(((e,t)=>e+De(t).amount),BigInt(0))-t,tt={BaseP:{sortFunction:ze,unsignedTxBuilder:(e,t)=>{const r=e.getProvider().getContext();return e.baseTX(new i.utils.UtxoSet(t),"P",e.getCurrentAddress("P"),{[r.avaxAssetID]:et(t,r.baseTxFee)})}},ConsolidateP:{sortFunction:Ge,unsignedTxBuilder:(e,t)=>{const r=e.getProvider().getContext();return e.consolidateP(new i.utils.UtxoSet(t),et(t,r.baseTxFee))}},AddPermissionlessValidator:{sortFunction:je,unsignedTxBuilder:(e,t)=>e.addPermissionlessValidator(new i.utils.UtxoSet(t),Qe,Ce(),Ce()+BigInt(1e3),et(t,e.getProvider().getContext().addPrimaryNetworkValidatorFee),Ze,5,void 0,void 0,void 0,Buffer.from(i.utils.hexToBuffer("0x8f95423f7142d00a48e1014a3de8d28907d420dc33b3052a6dee03a3f2941a393c2351e354704ca66a3fc29870282e15")),Buffer.from(i.utils.hexToBuffer("0x86a3ab4c45cfe31cae34c1d06f212434ac71b1be6cfe046c80c162e057614a94a5bc9f1ded1a7029deb0ba4ca7c9b71411e293438691be79c2dbf19d1ca7c3eadb9c756246fc5de5b7b89511c7d7302ae051d9e03d7991138299b5ed6a570a98")))},AddPermissionlessDelegator:{sortFunction:je,unsignedTxBuilder:(e,t)=>e.addPermissionlessDelegator(new i.utils.UtxoSet(t),Qe,Ce(),Ce()+BigInt(1e3),et(t,e.getProvider().getContext().addPrimaryNetworkDelegatorFee),Ze)},ExportP:{sortFunction:ze,unsignedTxBuilder:(e,t)=>e.exportP(et(t,e.getProvider().getContext().baseTxFee),new i.utils.UtxoSet(t),"X")},ImportP:{sortFunction:ze,unsignedTxBuilder:(e,t)=>e.importP(new i.utils.UtxoSet(t),"X")}};function rt(e){return y.validateString(e,!0)&&6===e.split("/").length}const{parse:st,hexToBuffer:nt}=i.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 Pe(this.getAddresses(e),t)}async getStake(){const e=this.provider.getApiP();return Me(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 Pe(this.getAddresses(e),r,{sourceChain:s,addresses:[]})}exportX(e,t,r,s){s=s||this.getCurrentAddress(r);const n=st(s)[2],a=this.provider.getAvaxID(),o=i.TransferableOutput.fromNative(a,e,[n]),d=Je(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("X").map((e=>st(e)[2])),l=st(this.getChangeAddress("X"))[2];return i.avm.newExportTx(this.provider.getContext(),u,c,d,[o],{threshold:1,changeAddresses:[l]})}importP(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("P").map((e=>st(e)[2])),a=st(this.getChangeAddress("P"))[2];r=r||this.getCurrentAddress("P");const o=st(r)[2];return i.pvm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[a]})}importX(e,t,r){const s=this.provider.getChainID(t),n=this.getAddresses("X").map((e=>st(e)[2])),a=st(this.getChangeAddress("X"))[2];r=r||this.getCurrentAddress("X");const o=st(r)[2];return i.avm.newImportTx(this.provider.getContext(),s,e.getUTXOs(),[o],n,{changeAddresses:[a]})}importC(e,r,s,n,a){const o=this.provider.getChainID(r),d=this.getAddresses("C").map((e=>st(e)[2]));a=a||this.getAddressEVM();const u=Buffer.from(t.strip0x(a),"hex");return i.evm.newImportTxFromBaseFee(this.provider.getContext(),u,d,e.getUTXOs(),o,s,n)}exportC(e,t,r,s,n){const a=nt(this.getAddressEVM()),o=this.provider.getChainID(t);n=n||this.getCurrentAddress(t);const d=st(n)[2],u=s/BigInt(1e9);return i.evm.newExportTxFromBaseFee(this.provider.getContext(),u,e,o,a,[d],r)}async getNonce(){const e=this.getAddressEVM();return await this.provider.evmRpc.getTransactionCount(e)}exportP(e,t,r,s){s=s||this.getCurrentAddress(r);const n=st(s)[2],a=this.provider.getAvaxID(),o=i.TransferableOutput.fromNative(a,e,[n]),d=Je(t.getUTXOs(),!0),u=this.provider.getChainID(r),c=this.getAddresses("P").map((e=>st(e)[2])),l=st(this.getChangeAddress("P"))[2];return i.pvm.newExportTx(this.provider.getContext(),u,c,d,[o],{changeAddresses:[l]})}addValidator(e,t,r,s,n,a,o){const d=je(e.getUTXOs()),u=this.getAddresses("P").map((e=>st(e)[2])),c=o?.rewardAddress||this.getCurrentAddress("P"),l=st(c)[2],p=st(this.getChangeAddress("P"))[2];return i.pvm.newAddValidatorTx(this.provider.getContext(),d,u,t,s,n,r,[l],a,{changeAddresses:[p]})}addDelegator(e,t,r,s,n,a){const o=je(e.getUTXOs()),d=this.getAddresses("P").map((e=>st(e)[2])),u=a?.rewardAddress||this.getCurrentAddress("P"),c=st(u)[2],l=st(this.getChangeAddress("P"))[2];return i.pvm.newAddDelegatorTx(this.provider.getContext(),o,d,t,s,n,r,[c],{changeAddresses:[l]})}consolidateP(e,t,r,s){const n=Ge(e.getUTXOs());r=r??this.getCurrentAddress("P");const a=st(r)[2],o=this.provider.getContext(),d=[i.TransferableOutput.fromNative(o.avaxAssetID,t,[a])],u=this.getAddresses("P").map((e=>st(e)[2]));return i.pvm.newBaseTx(this.provider.getContext(),u,n,d,s)}baseTX(e,t,r,s,n,a){const[o,d,u]=st(r);if(o!==t||d!==this.provider.getHrp())throw new Error(`Invalid recipient address "${r}"`);const c=Object.entries(s).map((([e,t])=>i.TransferableOutput.fromNative(e,t,[u]))),l=Je(e.getUTXOs(),!0),p=(a??this.getAddresses(t)).map((e=>st(e)[2]));return"X"===t?i.avm.newBaseTx(this.provider.getContext(),p,l,c,n):i.pvm.newBaseTx(this.provider.getContext(),p,l,c,n)}createBlockchain(e,t,r,s,n,a,o,d,u){const c=Je(e.getUTXOs(),!0),l=(u??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newCreateBlockchainTx(this.provider.getContext(),c,l,t,r,s,n,a,o,d)}createSubnet(e,t,r,s,n,a){const o=Je(e.getUTXOs(),!0),d=(r??this.getAddresses("P")).map((e=>st(e)[2])),u=t.map((e=>st(e)[2]));return i.pvm.newCreateSubnetTx(this.provider.getContext(),o,d,u,s,n??1,a??BigInt(0))}addSubnetValidator(e,t,r,s,n,a,o,d,u){const c=Je(e.getUTXOs(),!0),l=(d??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newAddSubnetValidatorTx(this.provider.getContext(),c,l,t,r,s,n,a,o,u)}addPermissionlessValidator(e,t,r,s,n,a,o,d,u,c,l,p,h){const g=je(e.getUTXOs()),m=(d??this.getAddresses("P")).map((e=>st(e)[2])),f=(u??[this.getCurrentAddress("P")]).map((e=>st(e)[2])),x=(c??[this.getCurrentAddress("P")]).map((e=>st(e)[2]));if(!(a!==i.networkIDs.PrimaryNetworkID.toString()||l&&p))throw new Error("Must provide public key and signature for primary subnet.");const v={changeAddresses:[st(this.getChangeAddress("P"))[2]],...h??{}};return i.pvm.newAddPermissionlessValidatorTx(this.provider.getContext(),g,m,t,a,r,s,n,f,x,o,v,void 0,void 0,l,p)}addPermissionlessDelegator(e,t,r,s,n,a,o,d,u){const c=je(e.getUTXOs()),l=(o??this.getAddresses("P")).map((e=>st(e)[2])),p=(d??[this.getCurrentAddress("P")]).map((e=>st(e)[2])),h={changeAddresses:[st(this.getChangeAddress("P"))[2]],...u??{}};return i.pvm.newAddPermissionlessDelegatorTx(this.provider.getContext(),c,l,t,a,r,s,n,p,h,void 0,void 0)}removeSubnetValidator(e,t,r,s,n,a){const o=Je(e.getUTXOs(),!0),d=(n??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newRemoveSubnetValidatorTx(this.provider.getContext(),o,d,t,r,s,a)}transferSubnetOwnershipTx(e,t,r,s,n,a,o,d){const u=Je(e.getUTXOs(),!0),c=(n??this.getAddresses("P")).map((e=>st(e)[2])),l=s.map((e=>st(e)[2]));return i.pvm.newTransferSubnetOwnershipTx(this.provider.getContext(),u,c,t,r,l,a,o??1,d??BigInt(0))}transformSubnetTx(e,t,r,s,n,a,o,d,u,c,l,p,h,g,m,f,x,v){const w=Je(e.getUTXOs(),!0),y=(x??this.getAddresses("P")).map((e=>st(e)[2]));return i.pvm.newTransformSubnetTx(this.provider.getContext(),w,y,t,r,s,n,a,o,d,u,c,l,p,h,g,m,f,v)}}class at 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 i=t.strip0x(n.SigningKey.computePublicKey(e,!0)),a=t.strip0x(n.SigningKey.computePublicKey(r,!0)),o=Buffer.from(i,"hex"),d=Buffer.from(a,"hex");return new at(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),i=u.fromSeed(n),a=i.derivePath(r),o=i.derivePath(t);return at.fromPublicKey(o.publicKey,a.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 ot={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),i=s.map((e=>e.toString(!0))),a=await n.signHash(r.toString(),i,t),o=a.signatures||new Map;return{hash:a.hash||Buffer.from(""),signatures:o}},async signTx(e,t,r,s,n){const i=this.getApp(e),a=s.map((e=>e.toString(!0))),o=n?.map((e=>e.toString(!0)))||[],d=await i.sign(r.toString(),a,t,o),u=d.signatures||new Map;return{...d,signatures:u}}};async function dt(e){return!(await ot.getVersion(e)>="0.6.0")}const{parse:ut}=i.utils;class ct extends it{constructor(e,t,r){super(r),this.avmXpub=e,this.accountNode=u.fromBase58(e),this.evmWallet=new at(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(),i=s.derivePath(V(0,M.BIP44,"EVM")).neutered();return new ct(n.toBase58(),i.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(ut(e)[2])))}getExternalRawAddresses(){return this.getExternalAddresses("X").map((e=>Buffer.from(ut(e)[2])))}getRawAddressC(){return Buffer.from(ut(this.getCurrentAddress("C"))[2])}}const{isTransferOut:lt,isStakeableLockOut:pt}=i.utils;function ht(e){const t=e.output;return lt(t)||pt(t)?t.getOwners():[]}function gt(e){const t=e.getTx();return i.avmSerial.isExportTx(t)||i.pvmSerial.isExportTx(t)?new Set(t.outs.map(ht).flat()):i.evmSerial.isExportTx(t)?new Set(t.exportedOutputs.map(ht).flat()):new Set((t.baseTx?.outputs??[]).map(ht).flat())}const{parse:mt}=i.utils;class ft extends ct{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]=mt(s);return Buffer.from(n).toString("hex")}))}static async fromTransport(e,r){if(await dt(e))throw new Error("Unsupported ledger app version. Must be >= 0.6.0");const s=k(e),i=await ot.getXPUB(e,ft.getAccountPath("X")),a=u.fromPublicKey(i.pubKey,i.chainCode),o=V(0,M.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 ft(a.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"))),i=new Set([...s,...r??[]]),a=new Set([...n,...t??[]]),o=new Set;return e.forEach((e=>{const t=e.toString("hex");if(i.has(t)){const e=[...i].indexOf(t);o.add(`1/${e}`)}else if(a.has(t)){const e=[...a].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(),i=Buffer.from(t.toBytes()),a="EVM"===n?"C":"X",o=t.getAddresses().map((e=>Buffer.from(e))),d=this.getAdditionalAddressesByIndices(r??[],!1,a),u=this.getAdditionalAddressesByIndices(s??[],!0,a),c=[...this.filterOwnedAddresses(o,d,u).values()].map((e=>y.fromString(e))),l=[...gt(t)].map((e=>Buffer.from(e))),p=[...this.filterOwnedAddresses(l).values()].map((e=>y.fromString(e)));return(await this.signTxBuffer({buffer:i,chain:a,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=y.fromString(ft.getAccountPath(e.chain));return[...(await ot.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}}const{strip0x:xt}=i.utils;class vt extends ct{constructor(e,t,r){const s=u.fromBase58(e).neutered(),i=new n.SigningKey(t),a=Buffer.from(xt(i.compressedPublicKey),"hex");super(s.toBase58(),a,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'"),i=s.derivePath(V(0,M.BIP44,"EVM"));if(!i.privateKey)throw new Error("Unable to derive EVM private key.");return new vt(n.toBase58(),i.privateKey,t)}async signTx(e){const t=this.getSigningKeys(e);return await i.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:wt,sign:yt,signHash:bt}=i.secp256k1,{addChecksum:At}=i.utils;class It extends at{privKeyXP;privKeyC;constructor(e,t,r){super(Buffer.from(wt(e)),Buffer.from(wt(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),i=u.fromSeed(n),a=i.derivePath(t),o=i.derivePath(r);if(!a.privateKey||!o.privateKey)throw new Error("Failed to generate private keys.");return new It(a.privateKey,o.privateKey,s)}async signMessage(e){const t=Ie(e.message),r=this.getSigningKey(e.chain);return Buffer.from(At(await bt(t,r)))}getSigningKey(e){return"C"===e?this.privKeyC:this.privKeyXP}async signTx(e){return await i.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:Tt}=i.utils;class St extends at{constructor(e,t,r,s,a){const o=i.utils.strip0x(n.SigningKey.computePublicKey(e,!0)),d=i.utils.strip0x(n.SigningKey.computePublicKey(r,!0));if(super(Buffer.from(o,"hex"),Buffer.from(d,"hex"),a),this.pathXP=t,this.pathC=s,!rt(t)||!rt(s))throw new Error("Invalid path configuration.")}static async fromTransport(e,t,r,i){if(await dt(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 a=new s(e),o=await a.getAddress(r,!1),d=await a.getAddress(t,!1),u=Buffer.from(Tt(o.publicKey),"hex"),c=Buffer.from(Tt(d.publicKey),"hex"),l=Buffer.from(Tt(n.SigningKey.computePublicKey(u,!0)),"hex"),p=Buffer.from(Tt(n.SigningKey.computePublicKey(c,!0)),"hex");return new St(p,t,l,r,i)}async signMessage(e){throw new Error("not implemented")}getFullSignerPath(e){return"C"===e?this.pathC:this.pathXP}getPartialSignerPath(e){return this.getFullSignerPath(e).split("/").slice(4).join("/")}getAccountPath(e){return this.getFullSignerPath(e).split("/").slice(0,4).join("/")}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=e.tx,r=t.getVM(),s=Buffer.from(t.toBytes()),n="EVM"===r?"C":"X";return(await this.signTxBuffer({buffer:s,chain:n,transport:e.transport})).forEach((e=>{t.addSignature(e)})),t}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=y.fromString(this.getAccountPath(e.chain)),r=y.fromString(this.getPartialSignerPath(e.chain));return[...(await ot.signTx(e.transport,e.buffer,t,[r],[r])).signatures.values()]}}const{parse:Pt}=i.utils;var Bt=Object.freeze({__proto__:null,AbstractProvider:ue,AddressWallet:class extends it{constructor(e,t,r,s,i){if(super(i),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=>!Ue(e,!1))))throw new Error("Given addresses must be valid avalanche bech32 addresses without the chain alias prefix");if(!Ue(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(!Ue(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)}},FujiContext:le,JsonRpcProvider:pe,LedgerSigner:St,LedgerWallet:ft,MainnetContext:ce,MnemonicWallet:vt,MnemonicWalletVoid:ct,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 i.EVMUnsignedTx||"C"===t?i.EVMUnsignedTx.fromJSON(JSON.stringify(e.toJSON())):i.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(Pt(s)[2]).toString("hex")}getAddressPathMap(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=this.getChainAlias(t),i=`0/${this.activeAccountIndex}`,a=new Map;if("C"===n||!this.accountNode)return a;const o=(r??[]).map((e=>`0/${e}`)),d=(s??[]).map((e=>`1/${e}`)),u=[i,...o,...d];for(const e of u){const t=this.getAddressOfPath(e,n);t&&a.set(t,e)}return a}getAddressBipPaths(e,t){return 0===t.size?[y.fromString(`0/${this.activeAccountIndex}`)]:e.reduce(((e,r)=>{const s=t.get(Buffer.from(r).toString("hex"));return s&&e.push(y.fromString(s)),e}),[])}async signTx(e){if(!e.transport)throw new Error("Ledger transport not provided");const t=this.getChainAlias(e.tx),r=this.reSerializeTx(e.tx,t),s=Buffer.from(r.toBytes()),n=this.getAddressPathMap(e),i=this.getAddressBipPaths(r.getAddresses(),n),a=this.getAddressBipPaths([...gt(r)],n);return(await this.signTxBuffer({buffer:s,chain:t,transport:e.transport,signers:i,change:a})).forEach((e=>{r.addSignature(e)})),r}async signTxBuffer(e){if(!e.transport)throw new Error("Ledger transport not provided");if(!e.signers)throw new Error("Signers not provided");const t=e.change||[],r=y.fromString(this.getAccountPath(e.chain));return[...(await ot.signTx(e.transport,e.buffer,r,e.signers,t)).signatures.values()]}async signMessage(e){if(!e.transport||!e.message)throw new Error("Unable to sign message. Incomplete or invalid request.");const t=e.signer||y.fromString(`0/${this.activeAccountIndex}`);if(2!=t.toPathArray().length)throw new Error("Given signer path must have a depth of 2. Ex. 0/0, 0/1");const r=Ie(e.message),s=(await ot.signHash(e.transport,r,y.fromString(this.getAccountPath(e.chain)),[t])).signatures.get(t.toString(!0));if(!s)throw new Error("Failed to sign message.");return s}},SimpleSigner:class{accountNodeXP;signerNodeEVM;activeAccountIndex;constructor(e,t){if(!c.validateMnemonic(e))throw new Error("Invalid mnemonic phrase.");if(t<0||t%1!=0)throw new Error("Invalid account index.");const r=c.mnemonicToSeedSync(e),s=u.fromSeed(r);this.accountNodeXP=s.derivePath("m/44'/9000'/0'");const n=s.derivePath(V(t,M.BIP44,"EVM"));this.signerNodeEVM=n,this.activeAccountIndex=t}getAdditionalKeys(e,t){return[...new Set(e??[])].reduce(((e,r)=>{const s=this.accountNodeXP.derivePath(`${t?1:0}/${r}`);if(!s.privateKey)throw new Error("Unable to get private key.");return e.push(s.privateKey),e}),[])}getSigningKeys(e,t,r){if("EVM"===e){if(!this.signerNodeEVM.privateKey)throw new Error("Unable to derive EVM private key.");return[this.signerNodeEVM.privateKey]}const s=this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);if(!s.privateKey)throw new Error("Unable to derive X/P private key.");const n=this.getAdditionalKeys(t,!1);if("AVM"===e){const e=this.getAdditionalKeys(r,!0);return[s.privateKey,...n,...e]}if("PVM"===e)return[s.privateKey,...n]}async signTx(e){const{tx:t,externalIndices:r,internalIndices:s}=e,n=t.getVM(),a=this.getSigningKeys(n,r,s);if(!a?.length)throw new Error("Unable to sign transaction: signing keys are missing.");return await i.addTxSignatures({unsignedTx:t,privateKeys:a}),e.tx}async signTxBuffer(e){throw new Error("Not implemented")}getActiveAccountNode(e){switch(e){case"X":case"P":return this.accountNodeXP.derivePath(`0/${this.activeAccountIndex}`);case"C":return this.signerNodeEVM}}async signMessage(e){const t=this.getActiveAccountNode(e.chain);if(!t.privateKey)throw Error("Unable to sign message, key not found.");const r=Ie(e.message),s=await i.secp256k1.signHash(r,t.privateKey);return Buffer.from(s)}},SizeSupportedTx:Ye,StaticSigner:It,TxType:L,WalletAbstract:it,WalletVoid:at,addSignaturesToAvalancheTx:async({transactionHex:e,signatures:t,chainAlias:r,provider:s,utxos:n})=>{if(!t.length)throw new Error("signatures were not provided");const a=await ie({transactionHex:e,chainAlias:r,provider:s,utxos:n});await Promise.all(t.map((e=>a.addSignature(e))));const o=a.getCredentials(),d=a.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 i.Credential(s)),e}),[]),u=new i.UnsignedTx(a.getTx(),a.getInputUtxos(),a.addressMaps,d);return{signedTxHex:te(new i.avaxSerial.SignedTx(a.getTx(),d)),hasAllSignatures:u.hasAllSignatures()}},convertGlacierUtxo:xe,createAvalancheEvmUnsignedTx:async({txBytes:e,fromAddress:t,vm:r,utxos:s})=>{const n=ve(r,e),a=we(t)[2],o=ye(a);if(i.evmSerial.isExportTx(n))return new i.EVMUnsignedTx(n,[],new be([Ae.fromJSON([[o,0]])]));if(i.evmSerial.isImportTx(n)){const e=be.fromTransferableInputs(n.importedInputs,s,BigInt(Math.floor((new Date).getTime()/1e3)),[a]);return new i.UnsignedTx(n,s,e)}throw new Error("Unsupported transaction type")},createAvalancheUnsignedTx:J,digestMessage:Ie,emptySignature:Z,getAddressFromXpub:function(e,t,r,s,n=!1){if(t<0)throw new Error("Account index must be >= 0");const i=n?"1":"0",a=u.fromBase58(e).derivePath(`${i}/${t}`).publicKey;return r.getAddress(a,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(),i=Ce();return n.forEach((e=>{const t=De(e);s[t.threshold>1?"multisig":t.locktime>i?"locked":t.stakeableLocktime>i?"lockedStakeable":"available"]+=t.amount})),s.total=s.locked+s.lockedStakeable+s.multisig+s.available,s},getLedgerProvider:async function(e){return ot},getMaximumUtxoSet:function(e,t,r,s=65536){const{sortFunction:n,unsignedTxBuilder:i}=tt[r],a=Ce(),o=n(t.filter((e=>{const{locktime:t,stakeableLocktime:s}=De(e);return t<a&&(s<a||("AddPermissionlessDelegator"===r||"AddPermissionlessValidator"===r))}))),d=function(e,t,r){let s=0,n=e.length-1;if(t(e)<=r)return n;let i=-1;for(;s<=n;){const a=Math.floor((s+n)/2);t(e.slice(0,a+1))<=r?(i=a,s=a+1):n=a-1}return i}(o,(t=>{try{return function(e){const t=e.getInputUtxos().reduce(((e,t)=>e+(8+65*De(t).threshold)),0);return 6+e.toBytes().length+t}(i(e,t))}catch(e){return console.log("Unable to estimate size of utxos",{e:e,utxos:t.map(De)}),s+1}}),s);return-1===d?[]:o.slice(0,d+1)},getPaginatedUTXOs:Be,getPchainUnixNow:async function(e){const t=e?pe.getDefaultFujiProvider():pe.getDefaultMainnetProvider(),r=await t.getApiP().getTimestamp(),s=new Date(r.timestamp),n=Math.floor(s.getTime()/1e3);return BigInt(n)},getStakeForAddresses:Me,getStakedAssetBalance:function(e){const{stakedOutputs:t}=e,r={unlockedStaked:BigInt(0),lockedStaked:BigInt(0),total:BigInt(0)};return t.forEach((e=>{r[i.utils.isStakeableLockOut(e)?"lockedStaked":"unlockedStaked"]+=e.amount()})),r.total=r.lockedStaked+r.unlockedStaked,r},getUTXOsForAddresses:Pe,getUnixNow:Ce,getUtxoInfo:De,getUtxosByTxFromGlacier:async({transactionHex:e,chainAlias:t,isTestnet:r,url:s,token:n,headers:a})=>{const o=q(t),d=Ke(e),u=Oe(o,d);if(i.evmSerial.isExportTx(u))return[];const c=(e=>{if(i.evmSerial.isImportTx(e)||i.avmSerial.isImportTx(e)||i.pvmSerial.isImportTx(e))return e.sourceChain.toString();const t=e.getVM();switch(t){case i.EVM:return v.BlockchainId.C_CHAIN;case i.AVM:return v.BlockchainId.X_CHAIN;case i.PVM:return v.BlockchainId.P_CHAIN;default:throw new Error(`Unable to get chain for VM type "${t}"`)}})(u),l=Ve(u),p=new v.Glacier({BASE:s,TOKEN:n,HEADERS:a}),h=r?v.Network.FUJI:v.Network.MAINNET,g=[...new Set(l.map((e=>e.utxoID.txID.toString())))],m=await Promise.all(g.map((e=>p.primaryNetworkTransactions.getTxByHash({blockchainId:c,network:h,txHash:e}))));return l.reduce(((e,t)=>{const s=m.find((e=>e.txHash===t.utxoID.txID.toString()));if(!s)throw new Error(`Unable to find parent tx "${t.utxoID.txID.toString()}"`);const n=s.emittedUtxos.find((e=>e.utxoId===t.utxoID.ID()));if(!n)throw new Error(`Unable to find UTXO "${t.utxoID.ID()}" at index "${t.utxoID.outputIdx.value()}"`);const i=xe(n,r);return e.push(i),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:Ue,isCreateChainTx:function(e){return"create_chain"===e.type},isCreateSubnetTx:function(e){return"create_subnet"===e.type},isExportTx:function(e){return"export"===e.type},isImportTx:function(e){return"import"===e.type},isObsidianApp:dt,isRemoveSubnetValidatorTx:function(e){return"remove_subnet_validator"===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){try{const s=t.getContext(),n=e.getTx(),a=(e=>{for(const t of Object.values(_e)){const r=t(e);if(null!==r)return r}throw new Error("no parser found for tx")})(n),o=He(n),d=$e(n),u=Re(n).get(s.avaxAssetID)??BigInt(0),c=o.get(s.avaxAssetID)??BigInt(0),l=d.get(s.avaxAssetID)??BigInt(0),{isValid:p,txFee:h}=Le({unsignedTx:e,context:s,burnedAmount:c,...i.evmSerial.isImportExportTx(n)&&{evmBaseFee:await t.getApiC().getBaseFee()/BigInt(1e9),evmFeeTolerance:50}});return await a({feeData:{totalAvaxBurned:c,totalAvaxOutput:l,totalAvaxInput:u,isValidAvaxBurnedAmount:p,txFee:h},assetId:s.avaxAssetID,provider:t,currentAddress:r})}catch(e){return{type:L.Unknown}}},populateCredential:ee,signedTxToHex:te,sortUTXOsByAmount:Je,sortUTXOsByAmountAscending:Ge,sortUTXOsByAmountDescending:ze,sortUTXOsStaking:je,verifyDerivationPath:rt});Object.defineProperty(exports,"BtcNetworks",{enumerable:!0,get:function(){return e.networks}}),exports.Avalanche=Bt,exports.BitcoinLedgerWallet=class extends ${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(),i=await r.getMasterFingerprint(),a=_(e,t,n,Buffer.from(i,"hex"),s,this.derivationPath),{policy:o,hmac:d}=this.walletPolicyDetails,u=await r.signPsbt(a,o,d),c=H(a,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,i){super(),this.isMainnet=e,this.extraParams=i;const a=r?{headers:{"api-key":r}}:{},o=e?"https://btcbook.nownodes.io":"https://btcbook-testnet.nownodes.io";this.#r=new t.HttpClient(s||o,a);const d=e?"https://btc.nownodes.io":"https://btc-testnet.nownodes.io";this.#s=new t.HttpClient(n||d,a)}#r;#s;async#n(e){return this.isMainnet?(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){const r=await this.#r.post(`/api/v2/utxo/${e}`,{},{},this.extraParams);if(!r?.length)return{confirmed:[],unconfirmed:[]};const s=r.map(this._parseUtxo),n=e=>({confirmed:e.filter((e=>e.confirmations>0)),unconfirmed:e.filter((e=>0===e.confirmations))});if(!t)return n(s);return n(await this.getScriptsForUtxos(s))}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){const[t,r]=e.reduce((([e,t],r)=>r.script?[[...e,r],t]:[e,[...t,r]]),[[],[]]),s=r.map(((e,t)=>({jsonrpc:"2.0",method:"gettxout",params:[e.txHash,e.index],id:`${t}`}))),n=s.length?(await this.#n(s)).sort(((e,t)=>Number(e.id)-Number(t.id))):[];return[...t,...r.map(((e,t)=>({...e,script:n[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(){const e={jsonrpc:"2.0",method:"estimatesmartfee"},t=await this.#n([{...e,id:"1",params:[1]},{...e,id:"2",params:[3]},{...e,id:"3",params:[6]}]).then((e=>e.sort(((e,t)=>Number(e.id)-Number(t.id))).map((e=>1e8*(e.result?.feerate??0)))));return{high:Math.ceil(t[0]/1024)||1,medium:Math.ceil(t[1]/1024)||1,low:Math.ceil(t[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))),i=t.vout.filter((t=>!t.addresses?.includes(e))),a=r.reduce(((e,t)=>e+BigInt(t.value)),0n),o=s.reduce(((e,t)=>e+BigInt(t.value)),0n),d=a>o;let u=o-a;d&&(u+=BigInt(t.fees));const c=n.map((e=>e.addresses||[])).flat(),l=i.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=$,exports.BitcoinWalletVoid=class extends ${constructor(e,t){super(e,t)}signTx(e){throw new Error("Void wallets can not sign.")}},exports.DerivationPath=M,exports.ETH_ACCOUNT_PATH=D,exports.ETH_COIN_PATH=E,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=_,exports.createPsbt=T,exports.createTransferTx=B,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=V,exports.getAddressFromXPub=function(e,t){const r=F(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=F,exports.getAppEth=k,exports.getBech32Address=C,exports.getBech32AddressFromXPub=function(e,t,r){return C(F(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),i=t.subarray(2+r+1,2+r+1+s);return{applicationName:n.toString("ascii"),version:i.toString("ascii")}},exports.getLedgerExtendedPublicKey=async function(e,t=!1,r){const s=k(e),n=await s.getAddress(r??D,t,!0),i=new a;return i.publicKey=o.Buffer.from(n.publicKey,"hex"),i.chainCode=o.Buffer.from(n.chainCode,"hex"),i.publicExtendedKey},exports.getMaxTransferAmount=function(e,t,r,s){const n=A(e);if(!n)return 0;const{fee:i}=S(t,r,n,s,e);return n-i},exports.getPubKeyFromTransport=async function(e,t,r,s="EVM"){const n=k(e),i=V(t,r,s),a=await n.getAddress(i,!1,!1);return Buffer.from(a.publicKey,"hex")},exports.getPublicKeyFromPrivateKey=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e,"hex");try{return Buffer.from(i.secp256k1.getPublicKey(t))}finally{t.fill(0)}},exports.getTransferTxDetails=function(e,t,r,s,n){const i=S(e,t,r,s,P(n));return i.inputs||console.log("Unable to construct transaction, fee needed: ",i.fee),i},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),V(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=O,exports.isNativeTxn=K,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()))),i=new Set(t.map((e=>e.toLowerCase()))),a=async e=>{const t=await r.getBlock(e,!0);t?.prefetchedTransactions.forEach((function(e){e.to&&i.has(e.to.toLowerCase())&&O(e,n)?s(e,{type:"erc20",contractAddress:e.to}):K(e,n)&&s(e,{type:"native"})}))},o=await r.on("block",a);return{unsubscribe:()=>o.off("block",a)}},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=H,exports.quitLedgerApp=async function(e){return await e.send(176,167,0,0)},exports.selectUtxos=S;
|
|
@@ -12,6 +12,7 @@ declare class BitcoinProvider extends BitcoinProviderAbstract {
|
|
|
12
12
|
confirmed: BitcoinInputUTXOWithOptionalScript[];
|
|
13
13
|
unconfirmed: BitcoinInputUTXOWithOptionalScript[];
|
|
14
14
|
}>;
|
|
15
|
+
getAddressFromScript(script: string): Promise<string>;
|
|
15
16
|
getScriptsForUtxos(utxos: BitcoinInputUTXOWithOptionalScript[]): Promise<BitcoinInputUTXO[]>;
|
|
16
17
|
private _parseUtxo;
|
|
17
18
|
getBalances(address: string): Promise<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BitcoinProviderAbstract as t}from"./BitcoinProviderAbstract.js";import{networks as e}from"bitcoinjs-lib";import{HttpClient as a}from"@avalabs/core-utils-sdk";import{URL_EXPLORER_MAINNET as s,URL_EXPLORER_TESTNET as r,URL_NODE_MAINNET as i,URL_NODE_TESTNET as n}from"./models.js";import{parseAddressFullTx as o}from"./utils/parseAddressFullTx.js";class l extends t{constructor(t=!0,e,o,l,c){super(),this.isMainnet=t,this.extraParams=c;const m=e?{headers:{"api-key":e}}:{},p=t?s:r;this.#t=new a(o||p,m);const
|
|
1
|
+
import{BitcoinProviderAbstract as t}from"./BitcoinProviderAbstract.js";import{networks as e}from"bitcoinjs-lib";import{HttpClient as a}from"@avalabs/core-utils-sdk";import{URL_EXPLORER_MAINNET as s,URL_EXPLORER_TESTNET as r,URL_NODE_MAINNET as i,URL_NODE_TESTNET as n}from"./models.js";import{parseAddressFullTx as o}from"./utils/parseAddressFullTx.js";class l extends t{constructor(t=!0,e,o,l,c){super(),this.isMainnet=t,this.extraParams=c;const m=e?{headers:{"api-key":e}}:{},p=t?s:r;this.#t=new a(o||p,m);const d=t?i:n;this.#e=new a(l||d,m)}#t;#e;async#a(t){return this.isMainnet?(await Promise.all(t.map((t=>this.#e.post("",t,{},this.extraParams))))).flat():this.#e.post("",t,{},this.extraParams)}async getTxHex(t){return(await this.#t.post(`/api/v2/tx/${t}`,{},{},this.extraParams)).hex}async getUTXOs(t,e=!0){const a=await this.#t.post(`/api/v2/utxo/${t}`,{},{},this.extraParams);if(!a?.length)return{confirmed:[],unconfirmed:[]};const s=a.map(this._parseUtxo),r=t=>({confirmed:t.filter((t=>t.confirmations>0)),unconfirmed:t.filter((t=>0===t.confirmations))});if(!e)return r(s);return r(await this.getScriptsForUtxos(s))}async getAddressFromScript(t){const e=await this.#e.post("",{jsonrpc:"2.0",id:`decode-script-${t}`,method:"decodescript",params:[t]},{},this.extraParams);if(e.result)return e.result.address;throw new Error(`Unable to resolve address for script: ${t}. ${e.error.message}`)}async getScriptsForUtxos(t){const[e,a]=t.reduce((([t,e],a)=>a.script?[[...t,a],e]:[t,[...e,a]]),[[],[]]),s=a.map(((t,e)=>({jsonrpc:"2.0",method:"gettxout",params:[t.txHash,t.index],id:`${e}`}))),r=s.length?(await this.#a(s)).sort(((t,e)=>Number(t.id)-Number(e.id))):[];return[...e,...a.map(((t,e)=>({...t,script:r[e]?.result?.scriptPubKey.hex})))]}_parseUtxo(t){return{...t,txHash:t.txid,index:t.vout,value:Number(t.value),blockHeight:t.height,script:t.script,confirmations:t.confirmations}}async getBalances(t){const e=await this.#t.post(`/api/v2/address/${t}`,{},{},this.extraParams);return{available:BigInt(e.balance),pending:BigInt(e.unconfirmedBalance),final:BigInt(e.balance)+BigInt(e.unconfirmedBalance)}}async getChainHeight(){return(await this.#e.post("",{jsonrpc:"2.0",id:"nownodes",method:"getblockcount",params:[]},{},this.extraParams)).result}async getFeeRates(){const t={jsonrpc:"2.0",method:"estimatesmartfee"},e=await this.#a([{...t,id:"1",params:[1]},{...t,id:"2",params:[3]},{...t,id:"3",params:[6]}]).then((t=>t.sort(((t,e)=>Number(t.id)-Number(e.id))).map((t=>1e8*(t.result?.feerate??0)))));return{high:Math.ceil(e[0]/1024)||1,medium:Math.ceil(e[1]/1024)||1,low:Math.ceil(e[2]/1024)||1}}getNetwork(){return this.isMainnet?e.bitcoin:e.testnet}async issueRawTx(t){return await this.#e.post("",{jsonrpc:"2.0",id:"nownodes",method:"sendrawtransaction",params:[t]},{},this.extraParams).then((t=>t.result))}async getTransaction(t){const e=await this.#t.post(`/api/v2/tx/${t}`,{},{},this.extraParams);return{block:e.blockHeight,fees:Number(e.fees),confirmations:e.confirmations,amount:Number(e.value),hash:e.txid,addresses:Array.from(new Set([...e.vin.map((t=>t.addresses||[])).flat(),...e.vout.map((t=>t.addresses||[])).flat()])),blockTime:e.blockTime,inputs:[...e.vin.map((t=>({...t,value:Number(t.value)})))],outputs:[...e.vout.map((t=>({...t,value:Number(t.value)})))]}}async getTxHistory(t){const e=await this.#t.post(`/api/v2/address/${t}`,{},{},this.extraParams);return await Promise.allSettled(e.txids?.slice(0,25).map((async e=>{try{const a=await this.#t.post(`/api/v2/tx/${e}`,{},{},this.extraParams);return o(t,a)}catch(t){console.log(`Unable to parse full tx ${e}.`)}}))).then((t=>t.map((t=>"fulfilled"===t.status&&t.value?t.value:void 0)).filter((t=>void 0!==t))))}async waitForTx(t,{maxAttempts:e=20,attempt:a=1,pollInterval:s=500}={}){try{return await this.getTransaction(t)}catch(r){if(a>=e)throw r;return await new Promise((t=>setTimeout(t,s))),this.waitForTx(t,{maxAttempts:e,attempt:a+1,pollInterval:s})}}}export{l as BitcoinProvider};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@avalabs/core-wallets-sdk",
|
|
3
|
-
"version": "3.1.0-alpha.
|
|
3
|
+
"version": "3.1.0-alpha.8",
|
|
4
4
|
"license": "Limited Ecosystem License",
|
|
5
5
|
"private": false,
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -31,8 +31,8 @@
|
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"@avalabs/avalanchejs": "4.0.5",
|
|
34
|
-
"@avalabs/core-chains-sdk": "3.1.0-alpha.
|
|
35
|
-
"@avalabs/glacier-sdk": "3.1.0-alpha.
|
|
34
|
+
"@avalabs/core-chains-sdk": "3.1.0-alpha.8",
|
|
35
|
+
"@avalabs/glacier-sdk": "3.1.0-alpha.8",
|
|
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": "
|
|
55
|
+
"gitHead": "00586756b491194a3a2a14861e1fc6fc813ca874"
|
|
56
56
|
}
|