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C;IAEA;;;KAGC,GACD,MAAa,aAA+B;QACxC,OAAO,MAAM,CAAA,GAAA,yCAAc,EAAE,UAAU,CAAC,IAAI,CAAC,eAAe,CAAC,OAAO;IACxE;IAEA;;;KAGC,GACD,MAAa,mBAAqD;QAC9D,MAAM,gBAAgB,MAAM,CAAA,GAAA,yCAAc,EAAE,gBAAgB,CAAC,IAAI,CAAC,eAAe,CAAC,OAAO;QACzF,MAAM,UAAmC,CAAC;QAE1C,+DAA+D;QAC/D,MAAM,cAAc,IAAI,IAAI;eACrB,OAAO,IAAI,CAAC,cAAc,SAAS;eACnC,OAAO,IAAI,CAAC,cAAc,WAAW;SAC3C;QAED,qEAAqE;QACrE,KAAK,MAAM,WAAW,YAAa;YAC/B,MAAM,kBAAkB,cAAc,SAAS,CAAC,QAAQ,IAAI;YAC5D,MAAM,oBAAoB,cAAc,WAAW,CAAC,QAAQ,IAAI;YAEhE,6BAA6B;YAC7B,IAAI,oBAAoB,KAAK,sBAAsB,GAC/C,OAAO,CAAC,QAAQ,GAAG;gBACf,WAAW,OAAO,iBAAiB,QAAQ;gBAC3C,aAAa,OAAO,mBAAmB,QAAQ;YACnD;QAER;QAEA,OAAO;IACX;AACJ;;;;;;;;;;;;;;;;;A/B7MA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,MAAM,kCAAY;IACd,SAAS,CAAC,CAAC,EAAE,CAAA,GAAA,iCAAM,GAAG;YACtB;AACJ;IAEA,2CAAe","sources":["src/index.ts","package.json","src/wallet/Wallet.ts","src/network/RostrumProvider.ts","src/models/rostrum.entities.ts","src/utils/WalletUtils.ts","node_modules/js-big-decimal/dist/esm/big-decimal.js","node_modules/src/add.ts","node_modules/src/abs.ts","node_modules/src/roundingModes.ts","node_modules/src/round.ts","node_modules/src/stripTrailingZero.ts","node_modules/src/multiply.ts","node_modules/src/divide.ts","node_modules/src/subtract.ts","node_modules/src/modulus.ts","node_modules/src/compareTo.ts","node_modules/src/big-decimal.ts","src/wallet/accounts/models/DappAccount.ts","src/wallet/accounts/interfaces/BaseAccountInterface.ts","src/wallet/accounts/models/DefaultAccount.ts","src/wallet/accounts/models/VaultAccount.ts","src/utils/CommonUtils.ts","src/utils/TokenUtils.ts","src/wallet/transactions/WalletTransactionCreator.ts","src/utils/TXUtils.ts","src/models/wallet.entities.ts","src/wallet/transactions/interfaces/TransactionCreator.ts","src/models/transaction.entities.ts","src/wallet/accounts/AccountStore.ts","src/utils/ValidationUtils.ts","src/wallet/WatchOnlyWallet.ts","src/wallet/transactions/WatchOnlyTransactionCreator.ts","src/utils/WatchOnlyTXUtils.ts"],"sourcesContent":["import { version } from '../package.json';\nimport Wallet from \"./wallet/Wallet\";\n\n/**\n * Wallet SDK - A TypeScript SDK for the Nexa blockchain\n *\n * This SDK provides comprehensive wallet functionality including:\n * - Creating and managing wallets from seed phrases or private keys\n * - Account management with different account types\n * - Transaction building and signing\n * - Token operations and management\n * - Message signing and verification\n *\n * @example\n * ```typescript\n * import { Wallet } from 'wallet-sdk-ts';\n *\n * // Create a new wallet\n * const wallet = Wallet.create();\n *\n * // Or restore from seed phrase\n * const wallet = Wallet.fromSeedPhrase('your seed phrase here');\n *\n * // Initialize and discover accounts\n * await wallet.initialize();\n * ```\n */\nconst walletSdk = {\n    version: `v${version}`,\n    Wallet\n}\n\nexport default walletSdk\n\nexport { default as Wallet } from './wallet/Wallet'\nexport { default as WatchOnlyWallet } from './wallet/WatchOnlyWallet'\n\n// Export utility enums and types\nexport { AccountType, TxTokenType, isValidNexaAddress } from './utils/WalletUtils'\nexport { default as ValidationUtils } from './utils/ValidationUtils'\n\n// Export account interfaces and classes\nexport { BaseAccount } from './wallet/accounts/interfaces/BaseAccountInterface'\nexport { default as DefaultAccount } from './wallet/accounts/models/DefaultAccount'\nexport { default as DappAccount } from './wallet/accounts/models/DappAccount'\nexport { default as VaultAccount } from './wallet/accounts/models/VaultAccount'\nexport { default as AccountStore } from './wallet/accounts/AccountStore'\n\n// Export transaction creators\nexport { default as WalletTransactionCreator } from './wallet/transactions/WalletTransactionCreator'\nexport { default as WatchOnlyTransactionCreator } from './wallet/transactions/WatchOnlyTransactionCreator'\n\n// Export network provider\nexport { rostrumProvider } from './network/RostrumProvider'\n\n// Export Rostrum types and constants\nexport { RostrumScheme } from './models/rostrum.entities'\nexport type {\n    RostrumParams,\n    RostrumTransportScheme,\n    BlockTip,\n    IFirstUse,\n    ITokenGenesis,\n    ITokensBalance,\n    ITokenListUnspent,\n    ITokenUtxo,\n    IListUnspentRecord,\n    IUtxo,\n    ISpent,\n    ITransaction,\n    ITXInput,\n    ITXOutput,\n    IScriptSig,\n    IScriptPubKey,\n    IHistoryFilter,\n    ITXHistory,\n} from './models/rostrum.entities'\n\n// Re-export libnexa-ts SighashType for transaction signing\nexport { SighashType } from 'libnexa-ts'\n\n// Export entity types and interfaces\nexport type {\n    AccountKeys,\n    AccountIndexes,\n    AddressKey,\n    Balance,\n    WatchOnlyAddress,\n    TxStatus,\n    HodlStatus\n} from './models/wallet.entities'\n\n// Export utility classes\nexport { AccountKeysUtils } from './models/wallet.entities'\n\nexport { GroupType, SubgroupType } from './models/transaction.entities'\nexport type {\n    TxEntityState,\n    TxTemplateData,\n    TxOptions,\n    TokenAction,\n    PermissionLabel,\n    TransactionEntity,\n    GroupOptions,\n    NftSubgroupOptions,\n    SftSubgroupOptions,\n    GenericSubgroupOptions\n} from './models/transaction.entities'\n","{\n  \"name\": \"nexa-wallet-sdk\",\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"source\": \"src/index.ts\",\n  \"types\": \"dist/index.d.ts\",\n  \"main\": \"dist/index.mjs\",\n  \"browser\": \"dist/index.web.mjs\",\n  \"exports\": {\n    \"types\": \"./dist/index.d.ts\",\n    \"node\": \"./dist/index.mjs\",\n    \"browser\": \"./dist/index.web.mjs\",\n    \"default\": \"./dist/index.mjs\"\n  },\n  \"engines\": {\n    \"node\": \">=20.19.0\"\n  },\n  \"scripts\": {\n    \"build\": \"parcel build\",\n    \"lint\": \"eslint .\",\n    \"fix-lint\": \"eslint --fix .\",\n    \"dev\": \"parcel watch\",\n    \"test\": \"vitest run\",\n    \"clean\": \"rm -rf dist .parcel-cache\",\n    \"docs\": \"typedoc && cp -r docs-src/* docs/\",\n    \"docs:serve\": \"typedoc && cp -r docs-src/* docs/ && mkdocs serve\",\n    \"docs:mkdocs\": \"typedoc && cp -r docs-src/* docs/ && mkdocs serve\",\n    \"docs:build\": \"typedoc && cp -r docs-src/* docs/ && mkdocs build\",\n    \"docs:setup\": \"./scripts/setup-docs.sh\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+ssh://git@gitlab.com/nexa/wallet-sdk-ts.git\"\n  },\n  \"keywords\": [\n    \"nexa\",\n    \"wallet\",\n    \"web3\",\n    \"crypto\",\n    \"dapp\",\n    \"walletcomms\",\n    \"walletsdk\"\n  ],\n  \"contributors\": [\n    {\n      \"name\": \"Dolaned\"\n    },\n    {\n      \"name\": \"Griffith\"\n    },\n    {\n      \"name\": \"Vgrunner\"\n    },\n    {\n      \"name\": \"myendy\"\n    }\n  ],\n  \"author\": \"Dolaned\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://gitlab.com/nexa/wallet-sdk-ts/issues\"\n  },\n  \"homepage\": \"https://gitlab.com/nexa/wallet-sdk-ts#readme\",\n  \"description\": \"Wallet SDK for the Nexa blockchain\",\n  \"devDependencies\": {\n    \"@parcel/bundler-library\": \"^2.16.0\",\n    \"@parcel/packager-ts\": \"^2.15.4\",\n    \"@parcel/transformer-typescript-types\": \"^2.15.4\",\n    \"@types/lodash-es\": \"^4.17.12\",\n    \"@types/node\": \"^22.13.1\",\n    \"eslint\": \"^9.20.1\",\n    \"parcel\": \"^2.15.4\",\n    \"typedoc\": \"^0.28.7\",\n    \"typedoc-plugin-markdown\": \"^4.7.0\",\n    \"typedoc-plugin-rename-defaults\": \"^0.7.3\",\n    \"typescript\": \"^5.8.3\",\n    \"typescript-eslint\": \"^8.24.1\",\n    \"vitest\": \"^3.0.8\"\n  },\n  \"targets\": {\n    \"main\": {\n      \"context\": \"node\",\n      \"outputFormat\": \"esmodule\",\n      \"distDir\": \"dist\",\n      \"isLibrary\": true,\n      \"includeNodeModules\": [\"js-big-decimal\"]\n    },\n    \"browser\": {\n      \"context\": \"browser\",\n      \"outputFormat\": \"esmodule\",\n      \"distDir\": \"dist\",\n      \"isLibrary\": true,\n      \"includeNodeModules\": [\"js-big-decimal\"]\n    }\n  },\n  \"dependencies\": {\n    \"@vgrunner/electrum-cash\": \"^2.0.12\",\n    \"bip39\": \"^3.1.0\",\n    \"js-big-decimal\": \"^2.2.0\",\n    \"libnexa-ts\": \"^3.0.0\",\n    \"lodash-es\": \"^4.17.21\"\n  },\n  \"files\": [\n    \"dist\"\n  ],\n  \"directories\": {\n    \"test\": \"tests\"\n  },\n  \"@parcel/resolver-default\": {\n    \"packageExports\": true\n  }\n}\n","import type { Networkish} from \"libnexa-ts\";\nimport {HDPrivateKey, Message, Networks, TransactionBuilder,} from \"libnexa-ts\";\nimport * as Bip39 from 'bip39'\nimport {rostrumProvider} from \"../network/RostrumProvider\";\nimport type {AccountType} from \"../utils/WalletUtils\";\nimport { discoverWallet,} from \"../utils/WalletUtils\";\nimport {isArray, isBuffer, isNil, isString} from \"lodash-es\";\nimport WalletTransactionCreator from \"./transactions/WalletTransactionCreator\";\nimport AccountStore from \"./accounts/AccountStore\";\nimport type {BaseAccount} from \"./accounts/interfaces/BaseAccountInterface\";\nimport ValidationUtils from \"../utils/ValidationUtils\";\nimport type {SubscribeCallback} from \"@vgrunner/electrum-cash\";\n\n/**\n * Main Wallet class for managing Nexa blockchain wallet operations\n *\n * This class provides comprehensive wallet functionality including:\n * - Creating wallets from seed phrases or private keys\n * - Account discovery and management\n * - Transaction creation and signing\n * - Message signing and verification\n * - Multi-account support with different account types\n *\n * @example\n * ```typescript\n * // Create a new wallet with random seed phrase\n * const wallet = Wallet.create();\n *\n * // Restore wallet from existing seed phrase\n * const wallet = Wallet.fromSeedPhrase('your twelve word seed phrase here');\n *\n * // Initialize wallet (discovers accounts and balances)\n * await wallet.initialize();\n *\n * // Create a new account\n * const account = await wallet.newAccount('DefaultAccount');\n *\n * // Create and send a transaction\n * const tx = wallet.newTransaction(account)\n *   .to('nexa:address', 1000000) // 1 NEXA in satoshis\n *   .sign();\n *\n * const txId = await wallet.sendTransaction(tx.toHex());\n * ```\n */\nexport default class Wallet {\n\n    /** The master HD private key derived from the seed phrase */\n    private readonly masterKey!: HDPrivateKey;\n\n    /** Store for managing wallet accounts */\n    private _accountStore: AccountStore;\n\n    /** The blockchain network this wallet operates on */\n    private readonly _network: Networkish\n\n    /** The BIP39 seed phrase used to generate this wallet (if created from phrase) */\n    private readonly phrase?: string;\n\n    /** Whether to force sequential account indexing instead of discovery-based indexing */\n    private _forceSequentialIndexing: boolean = false;\n\n    /**\n     * Creates a new Wallet instance\n     *\n     * @param data - Optional wallet data:\n     *   - undefined: Generate new random seed phrase\n     *   - string: Use as BIP39 seed phrase\n     *   - HDPrivateKey: Use as master key directly\n     * @param network - Network name ('mainnet', 'testnet', 'regtest'). Defaults to 'mainnet'\n     *\n     * @example\n     * ```typescript\n     * // Create new wallet with random seed\n     * const wallet = new Wallet();\n     *\n     * // Create from seed phrase\n     * const wallet = new Wallet('abandon abandon abandon...');\n     *\n     * // Create from master key\n     * const masterKey = HDPrivateKey.fromString('xprv...');\n     * const wallet = new Wallet(masterKey);\n     *\n     * // Create on testnet\n     * const wallet = new Wallet(undefined, 'testnet');\n     * ```\n     */\n    constructor(data?: string | HDPrivateKey | undefined, network?: string) {\n        this._network = Networks.get(network) ?? Networks.mainnet\n        this._accountStore = new AccountStore()\n\n        if(isNil(data)) {\n            // Generate new random seed phrase\n            this.phrase = Bip39.generateMnemonic(128, undefined, Bip39.wordlists.english)\n            const seed = Bip39.mnemonicToSeedSync(this.phrase, '')\n\n            const masterKey = HDPrivateKey.fromSeed(seed, this._network ?? Networks.mainnet)\n            this.masterKey = masterKey.deriveChild(44, true).deriveChild(29223, true)\n        } else if(data instanceof HDPrivateKey) {\n            // Use provided HDPrivateKey directly\n            this.masterKey = data.deriveChild(44, true).deriveChild(29223, true)\n        } else if (isString(data)) {\n            // Validate and use provided seed phrase\n            ValidationUtils.validateArgument(Bip39.validateMnemonic(data), 'Invalid BIP39 seed phrase provided')\n\n            this.phrase = data\n            const seed = Bip39.mnemonicToSeedSync(this.phrase, '')\n\n            const masterKey = HDPrivateKey.fromSeed(seed, this._network ?? Networks.mainnet)\n            this.masterKey = masterKey.deriveChild(44, true).deriveChild(29223, true)\n        }\n    }\n\n    /**\n     * Create a new wallet with a randomly generated seed phrase\n     *\n     * This is the recommended way to create a new wallet for first-time users.\n     * The generated seed phrase should be securely stored by the user.\n     *\n     * @returns A new Wallet instance with a random 12-word seed phrase\n     *\n     * @example\n     * ```typescript\n     * const wallet = Wallet.create();\n     * console.log(wallet.export().phrase); // Store this securely!\n     * ```\n     */\n    public static create(): Wallet {\n        return new Wallet()\n    }\n\n    /**\n     * Create a wallet from an existing BIP39 seed phrase\n     *\n     * Use this method to restore a wallet from a previously generated seed phrase.\n     * The seed phrase should be a valid BIP39 mnemonic.\n     *\n     * @param phrase - The BIP39 seed phrase (12 or 24 words)\n     * @param network - Optional network name ('mainnet', 'testnet', 'regtest')\n     * @returns A new Wallet instance restored from the seed phrase\n     * @throws {Error} If the seed phrase is invalid or not provided\n     *\n     * @example\n     * ```typescript\n     * const wallet = Wallet.fromSeedPhrase(\n     *   'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',\n     *   'testnet'\n     * );\n     * ```\n     */\n    public static fromSeedPhrase(phrase: string, network?: string): Wallet {\n        ValidationUtils.validateArgument(isString(phrase), 'seedphrase must be provided')\n        ValidationUtils.validateArgument(Bip39.validateMnemonic(phrase), 'Invalid BIP39 seed phrase provided')\n        return new Wallet(phrase, network)\n    }\n\n    /**\n     * Create a wallet from an extended private key (xpriv)\n     *\n     * Use this method to create a wallet from a master private key in extended format.\n     * This is useful for advanced users who want to use a specific key derivation.\n     *\n     * @param xpriv - The extended private key string (starts with 'xprv')\n     * @param network - Optional network name ('mainnet', 'testnet', 'regtest')\n     * @returns A new Wallet instance using the provided master key\n     * @throws {Error} If the private key is invalid or not provided\n     *\n     * @example\n     * ```typescript\n     * const wallet = Wallet.fromXpriv(\n     *   'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi'\n     * );\n     * ```\n     */\n    public static fromXpriv(xpriv: string, network?: string): Wallet {\n        ValidationUtils.validateArgument(isString(xpriv), 'private key must be provided')\n        ValidationUtils.validateArgument(xpriv.trim().length > 0, 'private key cannot be empty')\n\n        let masterKey: HDPrivateKey\n        try {\n            masterKey = HDPrivateKey.fromString(xpriv)\n        } catch (error) {\n            throw new Error(`Invalid extended private key format: ${error instanceof Error ? error.message : 'Unknown error'}`)\n        }\n\n        return new Wallet(masterKey, network)\n    }\n\n    /**\n     * Initialize the wallet by discovering accounts and loading balances\n     *\n     * This method performs account discovery using the BIP44 derivation path\n     * and scans for existing accounts with transaction history or balances.\n     * Must be called before using the wallet's accounts.\n     *\n     * @returns Promise that resolves when initialization is complete\n     *\n     * @example\n     * ```typescript\n     * const wallet = Wallet.fromSeedPhrase('your seed phrase');\n     * await wallet.initialize();\n     *\n     * // Now you can access discovered accounts\n     * const accounts = wallet.accountStore.listAccounts();\n     * ```\n     */\n    public async initialize(): Promise<void> {\n        const walletAccounts: BaseAccount[] = await discoverWallet(this.masterKey, this._forceSequentialIndexing)\n        for(const account of walletAccounts){\n            this._accountStore.importAccount(account)\n        }\n    }\n\n    /**\n     * Create a new transaction builder for this wallet\n     *\n     * @param fromAccount - The account to send the transaction from\n     * @param x - Optional existing transaction data:\n     *   - TransactionBuilder: Use existing transaction builder\n     *   - string: Parse from hex string\n     *   - Buffer: Parse from binary buffer\n     *   - undefined: Create new empty transaction\n     * @returns A new WalletTransactionCreator instance\n     *\n     * @example\n     * ```typescript\n     * const account = wallet.accountStore.getAccount(0);\n     * const tx = wallet.newTransaction(account)\n     *   .to('nexa:address', 1000000) // 1 NEXA\n     *   .sign();\n     *\n     * // Or from existing transaction hex\n     * const tx = wallet.newTransaction(account, 'raw_tx_hex')\n     *   .sign();\n     * ```\n     */\n    public newTransaction(fromAccount: BaseAccount, x?: TransactionBuilder | string | Buffer): WalletTransactionCreator {\n        let tx: WalletTransactionCreator;\n\n        if (x instanceof TransactionBuilder) {\n            tx = new WalletTransactionCreator(fromAccount, x);\n        } else if (isString(x)) {\n            tx = new WalletTransactionCreator(fromAccount).parseTxHex(x);\n        } else if (isBuffer(x) && !isNil(x)) {\n            tx = new WalletTransactionCreator(fromAccount).parseTxBuffer(x);\n        } else {\n            tx = new WalletTransactionCreator(fromAccount);\n        }\n\n        return tx.onNetwork(this._network);\n    }\n\n    /**\n     * Create a new account for this wallet\n     *\n     * @param accountType - The type of account to create:\n     *   - 'DefaultAccount': Standard account for general use\n     *   - 'VaultAccount': Secured account with additional protection\n     *   - 'DappAccount': Account optimized for dApp interactions\n     * @returns Promise that resolves to the newly created account\n     *\n     * @example\n     * ```typescript\n     * const defaultAccount = await wallet.newAccount('DefaultAccount');\n     * const vaultAccount = await wallet.newAccount('VaultAccount');\n     * const dappAccount = await wallet.newAccount('DappAccount');\n     * ```\n     */\n    public async newAccount(accountType: AccountType): Promise<BaseAccount>{\n        return await this.accountStore.createAccount(accountType, this.masterKey, this._forceSequentialIndexing)\n    }\n\n    /**\n     * Broadcast a signed transaction to the Nexa network\n     *\n     * Optionally pass the source account to automatically refresh its balances\n     * after a successful broadcast, so subsequent balance reads are up to date.\n     *\n     * @param transaction - The signed transaction in hex format\n     * @param account - Optional source account to refresh balances after broadcast\n     * @returns Promise that resolves to the transaction hash\n     * @throws {Error} If the transaction is invalid or broadcast fails\n     *\n     * @example\n     * ```typescript\n     * const tx = await wallet.newTransaction(account)\n     *   .sendTo('nexa:address', '10000')\n     *   .populate()\n     *   .sign()\n     *   .build();\n     *\n     * // Auto-refresh balances after broadcast\n     * const txHash = await wallet.sendTransaction(tx, account);\n     *\n     * // account.balance is now up to date\n     * console.log('New balance:', account.balance);\n     * ```\n     */\n    public async sendTransaction(transaction: string, account?: BaseAccount): Promise<string> {\n        ValidationUtils.validateArgument(isString(transaction), 'transaction must be present and valid')\n        const txHash = await rostrumProvider.broadcast(transaction)\n        if (account) {\n            await account.loadBalances()\n        }\n        return txHash\n    }\n\n    /**\n     * Subscribe to address notifications for transaction updates\n     *\n     * This method allows you to monitor one or more addresses for incoming and outgoing transactions.\n     * You can provide either a single address string or an array of addresses. The callback will be\n     * invoked whenever there are updates to any of the monitored addresses.\n     *\n     * @param addresses - A single address string or array of addresses to monitor\n     * @param callback - Function to call when address notifications are received\n     * @returns Promise that resolves when subscription is established\n     * @throws {Error} If addresses parameter is invalid or empty\n     *\n     * @example\n     * ```typescript\n     * // Subscribe to a single address\n     * await wallet.subscribeToAddressNotifications(\n     *   'nexa:address123',\n     *   (notification) => {\n     *     console.log('Address notification:', notification);\n     *   }\n     * );\n     *\n     * // Subscribe to multiple addresses\n     * await wallet.subscribeToAddressNotifications(\n     *   ['nexa:address1', 'nexa:address2', 'nexa:address3'],\n     *   (notification) => {\n     *     console.log('Address notification:', notification);\n     *   }\n     * );\n     *\n     * // Subscribe to all wallet addresses\n     * const accounts = wallet.accountStore.listAccounts();\n     * const addresses = accounts.flatMap(account =>\n     *   account.getAddresses().map(addr => addr.address)\n     * );\n     * await wallet.subscribeToAddressNotifications(addresses, callback);\n     * ```\n     */\n    public async subscribeToAddressNotifications(addresses: string | string[], callback: SubscribeCallback): Promise<void> {\n        ValidationUtils.validateArgument(!isNil(addresses), 'addresses parameter is required')\n        ValidationUtils.validateArgument(!isNil(callback), 'callback function is required')\n\n        let addressArray: string[];\n\n        if (isString(addresses)) {\n            addressArray = [addresses];\n        } else if (isArray(addresses)) {\n            ValidationUtils.validateArgument(addresses.length > 0, 'addresses array cannot be empty')\n            addressArray = addresses;\n        } else {\n            throw new Error('addresses must be a string or array of strings')\n        }\n\n        return rostrumProvider.subscribeToAddresses(addressArray, callback)\n    }\n\n    /**\n     * Unsubscribe from address notifications to prevent memory leaks\n     *\n     * This method stops listening for notifications on the specified addresses.\n     * It's important to call this method when you no longer need to monitor addresses\n     * to prevent memory leaks from accumulating callback references.\n     *\n     * @param addresses - Single address string or array of address strings to unsubscribe from\n     * @param callback - The exact same callback function used in subscribeToAddressNotifications\n     *\n     * @example\n     * ```typescript\n     * // Unsubscribe from a single address\n     * await wallet.unsubscribeFromAddressNotifications(\n     *     'nexa:nqtsq5g5jsdmqqywaqd82lhnnk3a8wqunjz6gtxdtavnnekc',\n     *     myCallback\n     * );\n     *\n     * // Unsubscribe from multiple addresses\n     * await wallet.unsubscribeFromAddressNotifications(addresses, myCallback);\n     * ```\n     */\n    public async unsubscribeFromAddressNotifications(addresses: string | string[], callback: SubscribeCallback): Promise<void> {\n        ValidationUtils.validateArgument(!isNil(addresses), 'addresses parameter is required')\n        ValidationUtils.validateArgument(!isNil(callback), 'callback function is required')\n\n        let addressArray: string[];\n\n        if (isString(addresses)) {\n            addressArray = [addresses];\n        } else if (isArray(addresses)) {\n            ValidationUtils.validateArgument(addresses.length > 0, 'addresses array cannot be empty')\n            addressArray = addresses;\n        } else {\n            throw new Error('addresses must be a string or array of strings')\n        }\n\n        return rostrumProvider.unsubscribeFromAddresses(addressArray, callback)\n    }\n\n    /**\n     * Sign a message using a specific address from this wallet\n     *\n     * The message is signed using the private key associated with the given address.\n     * This can be used for authentication or to prove ownership of an address.\n     *\n     * @param message - The message to sign\n     * @param addressToUse - The address whose private key should sign the message\n     * @returns The signature as a base64-encoded string\n     * @throws {Error} If the address is not owned by this wallet\n     *\n     * @example\n     * ```typescript\n     * const account = wallet.accountStore.getAccount(0);\n     * const address = account.getReceiveAddress();\n     * const signature = wallet.signMessage('Hello World', address);\n     * ```\n     */\n    public signMessage(message: string, addressToUse: string): string {\n        let msg = new Message(message);\n        const addressKey = this.accountStore.findKeyForAddress(addressToUse)\n        if (!addressKey) {\n            throw new Error(\"You don't own this private key\")\n        }\n        return msg.sign(addressKey.key.privateKey)\n    }\n\n    /**\n     * Verify a message signature against an address\n     *\n     * This method can verify signatures created by any address, not just addresses\n     * owned by this wallet. It's useful for verifying messages from other parties.\n     *\n     * @param message - The original message that was signed\n     * @param signature - The signature to verify (base64-encoded)\n     * @param address - The address that supposedly signed the message\n     * @returns true if the signature is valid, false otherwise\n     * @throws {Error} If any parameters are missing or invalid\n     *\n     * @example\n     * ```typescript\n     * const isValid = wallet.verifyMessage(\n     *   'Hello World',\n     *   'signature_string',\n     *   'nexa:address'\n     * );\n     * console.log('Signature valid:', isValid);\n     * ```\n     */\n    public verifyMessage(message: string, signature: string, address: string): boolean {\n        ValidationUtils.validateArgument(!isNil(message), 'message is required')\n        ValidationUtils.validateArgument(!isNil(signature), 'signature is required')\n        ValidationUtils.validateArgument(!isNil(address), 'address is required ')\n        let msg = new Message(message);\n        const addressKey = this.accountStore.findKeyForAddress(address)\n        ValidationUtils.validateArgument(!isNil(addressKey), \"You dont own this private key\")\n        return msg.verify(address, signature)\n    }\n\n    /**\n     * Export the wallet data for backup or storage\n     *\n     * Returns an object containing the wallet's seed phrase, master key, and accounts.\n     * This data can be used to restore the wallet later. The seed phrase should be\n     * stored securely as it provides full access to the wallet.\n     *\n     * @returns Object containing wallet data\n     * @property {string} phrase - The BIP39 seed phrase (if available)\n     * @property {HDPrivateKey} masterKey - The master private key\n     * @property {BaseAccount[]} accounts - Array of discovered accounts\n     *\n     * @example\n     * ```typescript\n     * const walletData = wallet.export();\n     *\n     * // Store the seed phrase securely\n     * const seedPhrase = walletData.phrase;\n     *\n     * // Later, restore the wallet\n     * const restoredWallet = Wallet.fromSeedPhrase(seedPhrase);\n     * ```\n     */\n    public export(): { phrase?: string; masterKey: HDPrivateKey; accounts: Map<string, BaseAccount> } {\n        return {\n            phrase: this.phrase,\n            masterKey: this.masterKey,\n            accounts: this._accountStore.listAccounts(),\n        }\n    }\n\n    /**\n     * Get the account store for managing wallet accounts\n     *\n     * The account store provides methods to create, import, and manage accounts\n     * within this wallet. Each account has its own set of addresses and keys.\n     *\n     * @returns The wallet's account store\n     *\n     * @example\n     * ```typescript\n     * const accountStore = wallet.accountStore;\n     * const accounts = accountStore.listAccounts();\n     * const firstAccount = accountStore.getAccount(0);\n     * ```\n     */\n    get accountStore(): AccountStore {\n        return this._accountStore;\n    }\n\n    /**\n     * Get the network this wallet is operating on\n     *\n     * @returns The network object (mainnet, testnet, or regtest)\n     *\n     * @example\n     * ```typescript\n     * const network = wallet.network;\n     * console.log('Network:', network.name);\n     * ```\n     */\n    get network(): Networkish {\n        return this._network;\n    }\n\n    /**\n     * Get the current sequential indexing setting\n     *\n     * @returns true if forcing sequential indexing, false if using discovery-based indexing\n     *\n     * @example\n     * ```typescript\n     * const isSequential = wallet.forceSequentialIndexing;\n     * console.log('Sequential indexing:', isSequential);\n     * ```\n     */\n    get forceSequentialIndexing(): boolean {\n        return this._forceSequentialIndexing;\n    }\n\n    /**\n     * Set whether to force sequential account indexing\n     *\n     * When enabled, new accounts will use sequential indexes (0, 1, 2, ...) regardless\n     * of blockchain activity. This is useful for multi-user wallets where each user\n     * needs a unique account even if they haven't used it yet.\n     *\n     * When disabled (default), account creation uses discovery-based indexing which\n     * scans the blockchain for existing activity before assigning indexes.\n     *\n     * @param force - true to force sequential indexing, false for discovery-based\n     *\n     * @example\n     * ```typescript\n     * // Enable sequential indexing for multi-user scenarios\n     * wallet.forceSequentialIndexing = true;\n     *\n     * // Create accounts - they'll be 2.0, 2.1, 2.2 regardless of usage\n     * const alice = await wallet.newAccount(AccountType.DAPP_ACCOUNT);\n     * const bob = await wallet.newAccount(AccountType.DAPP_ACCOUNT);\n     * const charlie = await wallet.newAccount(AccountType.DAPP_ACCOUNT);\n     *\n     * // Disable for normal discovery-based indexing\n     * wallet.forceSequentialIndexing = false;\n     * ```\n     */\n    set forceSequentialIndexing(force: boolean) {\n        this._forceSequentialIndexing = force;\n    }\n}\n","import {ConnectionStatus, ElectrumClient, SubscribeCallback} from \"@vgrunner/electrum-cash\";\nimport type {\n    BlockTip,\n    IFirstUse,\n    IHistoryFilter,\n    IListUnspentRecord,\n    ITokenGenesis,\n    ITokenListUnspent,\n    ITokensBalance,\n    ITransaction,\n    ITXHistory,\n    IUtxo,\n    RostrumParams,\n    RostrumTransportScheme\n} from \"../models/rostrum.entities\";\nimport {RostrumScheme} from \"../models/rostrum.entities\";\nimport type {Balance} from \"../models/wallet.entities\";\nimport {Networkish, Networks} from \"libnexa-ts\";\n\ntype RPCParameter = string | number | boolean | null;\n\nexport class RostrumProvider {\n\n    private client?: ElectrumClient;\n\n    public constructor() {}\n\n    /**\n     * Get Rostum Server Version\n     */\n    public async getVersion() {\n        return await this.execute<string[]>('server.version');\n    }\n\n    /**\n     * Get the block tip of the network / chain we are currently connected to\n     */\n    public async getBlockTip() {\n        return await this.execute<BlockTip>('blockchain.headers.tip');\n    }\n\n    /**\n     * Get the nexa balance of an address without the token balances\n     * @param address\n     */\n    public async getBalance(address: string) {\n        return await this.execute<Balance>('blockchain.address.get_balance', address, 'exclude_tokens');\n    }\n\n    /**\n     * Get The transaction history for an address\n     * @param address\n     * @param filter - Optional filter for pagination and filtering (from_height, to_height, offset, limit, include_tokens, tokens_only, exclude_tokens)\n     */\n    public async getTransactionHistory(address: string, filter?: IHistoryFilter) {\n        if (filter) {\n            const res = await this.client!.request('blockchain.address.get_history', ...([address, filter] as unknown as RPCParameter[]));\n            if (res instanceof Error) throw res;\n            return res as ITXHistory[];\n        }\n        return await this.execute<ITXHistory[]>('blockchain.address.get_history', address);\n    }\n\n    /**\n     * Get the latest transaction for an address.\n     * Uses a recent block window (~1 day) first to avoid fetching full history\n     * for high-volume addresses. Falls back to full history if nothing recent.\n     * @param address\n     * @param verbose - Return full transaction object (default: true)\n     */\n    public async getLatestTransaction(address: string, verbose = true) {\n        const tip = await this.getBlockTip();\n        let history = await this.getTransactionHistory(address, {\n            from_height: tip.height - 720\n        });\n        if (history.length === 0) {\n            history = await this.getTransactionHistory(address);\n        }\n        if (history.length === 0) return null;\n        const latest = history[history.length - 1];\n        return await this.getTransaction(latest.tx_hash, verbose);\n    }\n\n    /**\n     * Get the block height or block has of when the address was first used\n     * @param address\n     */\n    public async getFirstUse(address: string) {\n        return await this.execute<IFirstUse>('blockchain.address.get_first_use', address);\n    }\n\n    /**\n     * Get a single transaction object\n     * @param id\n     * @param verbose\n     */\n    public async getTransaction(id: string, verbose = true) {\n        return await this.execute<ITransaction>('blockchain.transaction.get', id, verbose);\n    }\n\n    /**\n     * Get a single unspent output including group data\n     * @param outpoint\n     */\n    public async getUtxo(outpoint: string) {\n        return await this.execute<IUtxo>('blockchain.utxo.get', outpoint);\n    }\n\n    /**\n     * Get Utxos only containing nexa information\n     * @param address\n     */\n    public async getNexaUtxos(address: string) {\n        return await this.execute<IListUnspentRecord[]>('blockchain.address.listunspent', address, 'exclude_tokens');\n    }\n\n    /**\n     * Get all the utxo's for a token at an address\n     * @param address\n     * @param token\n     */\n    public async getTokenUtxos(address: string, token: string) {\n        let listunspent = await this.execute<ITokenListUnspent>('token.address.listunspent', address, null, token);\n        return listunspent.unspent;\n    }\n\n    /**\n     * Get the token balances for an address\n     * @param address\n     * @param token\n     */\n    public async getTokensBalance(address: string, token?: string) {\n        if (token) {\n            return await this.execute<ITokensBalance>('token.address.get_balance', address, null, token);\n        }\n        return await this.execute<ITokensBalance>('token.address.get_balance', address);\n    }\n\n    /**\n     * Get the token genesis for a token\n     * @param token\n     */\n    public async getTokenGenesis(token: string) {\n        return await this.execute<ITokenGenesis>('token.genesis.info', token);\n    }\n\n    /**\n     * Subscribe to address call back notifications, handy for updating the user when they receive nexa or tokens in\n     * their wallet\n     * @param addresses\n     * @param callback\n     */\n    public async subscribeToAddresses(addresses:string[], callback: SubscribeCallback) {\n        for (const addr of addresses) {\n            await this.client?.subscribe(callback, 'blockchain.address.subscribe', addr)\n        }\n    }\n\n    /**\n     * Unsubscribe from address notifications to prevent memory leaks\n     * @param addresses\n     * @param callback\n     */\n    public async unsubscribeFromAddresses(addresses: string[], callback: SubscribeCallback) {\n        for (const addr of addresses) {\n            await this.client?.unsubscribe(callback, 'blockchain.address.subscribe', addr)\n        }\n    }\n\n    /**\n     * Broadcast a presigned transaction hash\n     * @param txHex\n     */\n    public async broadcast(txHex: string) {\n        return await this.execute<string>('blockchain.transaction.broadcast', txHex);\n    }\n\n    /**\n     * Get the latency of the server connection\n     */\n    public async getLatency() {\n        try {\n            let start = Date.now();\n            let res = await this.getBlockTip();\n            if (res) {\n                return Date.now() - start;\n            }\n            return 0;\n        } catch {\n            return 0;\n        }\n    }\n\n    /**\n     * Create initial connection with the rostrum server\n     * @param netOrParams - Network identifier or RostrumParams object\n     * @param params - RostrumParams object (for backward compatibility)\n     * @param electrumClient - Optional pre-configured ElectrumClient instance\n     */\n    public async connect(netOrParams?: Networkish | RostrumParams, params?: RostrumParams, electrumClient?: ElectrumClient) {\n        try {\n            let connectionParams: RostrumParams;\n\n            // Handle backward compatibility: connect(params) or connect(network, params)\n            if (netOrParams && typeof netOrParams === 'object' && 'host' in netOrParams && 'port' in netOrParams && 'scheme' in netOrParams) {\n                // First parameter is RostrumParams\n                connectionParams = netOrParams;\n            } else if (params) {\n                // Second parameter contains RostrumParams, ignore network\n                connectionParams = params;\n            } else {\n                // Use network to determine default params\n                const network = netOrParams ? Networks.get(netOrParams) : Networks.mainnet;\n\n                if (network === Networks.mainnet) {\n                    connectionParams = {\n                        host: 'electrum.nexa.org',\n                        port: 20004,\n                        scheme: RostrumScheme.WSS as RostrumTransportScheme\n                    };\n                } else if (network === Networks.testnet) {\n                    connectionParams = {\n                        host: 'testnet-electrum.nexa.org',\n                        port: 30004,\n                        scheme: RostrumScheme.WSS as RostrumTransportScheme\n                    };\n                } else {\n                    // Default fallback for other networks (like regtest)\n                    connectionParams = {\n                        host: 'localhost',\n                        port: 30004,\n                        scheme: RostrumScheme.WS as RostrumTransportScheme\n                    };\n                }\n            }\n\n            if (electrumClient) {\n                this.client = electrumClient;\n                if(this.client.connection.status == ConnectionStatus.DISCONNECTED) {\n                    await this.client.connect();\n                }\n            } else {\n                this.client = new ElectrumClient(\"com.nexa.wallet-sdk\", \"1.4.3\", connectionParams.host, connectionParams.port, connectionParams.scheme, 30*1000, 10*1000, true);\n                await this.client.connect();\n            }\n        } catch (e) {\n            throw e;\n        }\n    }\n\n    /**\n     * Disconnect from the rostrum server\n     * @param force\n     */\n    public async disconnect(force?: boolean) {\n        try {\n            return await this.client!.disconnect(force);\n        } catch (_) {\n            return false;\n        }\n    }\n\n    /**\n     * internal function to call commands against the rostrum API\n     * @param method\n     * @param parameters\n     * @private\n     */\n    private async execute<T>(method: string, ...parameters: RPCParameter[]) {\n        let res = await this.client!.request(method, ...parameters);\n        if (res instanceof Error) {\n            throw res;\n        }\n        return res as T;\n    }\n}\n\nexport const rostrumProvider = new RostrumProvider();\n","export type RostrumTransportScheme = 'ws' | 'wss' | \"tcp\" | \"tcp_tls\";\n\nexport const RostrumScheme = {\n    WS: 'ws',\n    WSS: 'wss',\n    TCP: \"tcp\",\n    TCP_TLS: \"tcp_tls\",\n}\n\nexport interface RostrumParams {\n    scheme: RostrumTransportScheme;\n    host: string;\n    port: number;\n}\n\nexport interface BlockTip {\n    height: number;\n    hex: string;\n}\n\nexport interface IFirstUse {\n    block_hash: string;\n    block_height: number;\n    height: number;\n    tx_hash: string;\n}\n\nexport interface ITokenGenesis {\n    decimal_places?: number,\n    document_hash?: string;\n    document_url?: string;\n    group: string;\n    height: number;\n    name?: string;\n    op_return?: string;\n    ticker?: string;\n    token_id_hex: string;\n    txid: string;\n    txidem: string;\n    op_return_id: number;\n}\n\nexport interface ITokensBalance {\n    cursor?: any;\n    confirmed: Record<string, bigint | number>;\n    unconfirmed: Record<string, bigint | number>;\n}\n\nexport interface ITokenListUnspent {\n    cursor?: any;\n    unspent: ITokenUtxo[];\n}\n\nexport interface ITokenUtxo {\n    group: string;\n    height: number;\n    outpoint_hash: string;\n    token_amount: number | bigint;\n    token_id_hex: string;\n    tx_hash: string;\n    tx_pos: number;\n    value: number;\n    permissions?: string[];\n    address?: string;\n}\n\nexport interface IListUnspentRecord {\n    has_token: boolean;\n    height: number;\n    outpoint_hash: string;\n    tx_hash: string;\n    tx_pos: number;\n    value: number;\n}\n\nexport interface IUtxo {\n    addresses: string[];\n    amount: number;\n    group: string;\n    group_authority: bigint | number;\n    group_quantity: bigint | number;\n    height: number;\n    scripthash: string;\n    scriptpubkey: string;\n    spent: ISpent;\n    status: string;\n    template_argumenthash: string;\n    template_scripthash: string;\n    token_id_hex: string;\n    tx_hash: string;\n    tx_idem: string;\n    tx_pos: number;\n    permissions?: string[];\n}\n\nexport interface ISpent {\n    height: number;\n    tx_hash: string;\n    tx_pos: number;\n}\n\nexport interface ITransaction {\n    blockhash: string;\n    blocktime: number;\n    confirmations: number;\n    fee: number;\n    fee_satoshi: number;\n    hash: string;\n    height: number;\n    hex: string;\n    locktime: number;\n    size: number;\n    time: number;\n    txid: string;\n    txidem: string;\n    version: number;\n    vin: ITXInput[];\n    vout: ITXOutput[];\n}\n\nexport interface ITXInput {\n    outpoint: string;\n    scriptSig: IScriptSig;\n    sequence: number;\n    value: number;\n    value_satoshi: bigint | number;\n    addresses: string[];\n    group: string;\n    groupAuthority: bigint | number;\n    groupQuantity: bigint | number;\n}\n\nexport interface ITXOutput {\n    n: number;\n    outpoint_hash: string;\n    scriptPubKey: IScriptPubKey;\n    type: number;\n    value: number;\n    value_satoshi: bigint | number;\n}\n\nexport interface IScriptSig {\n    asm: string;\n    hex: string;\n}\n\nexport interface IScriptPubKey {\n    addresses: string[];\n    argHash: string;\n    asm: string;\n    group: string;\n    groupAuthority: bigint | number;\n    groupQuantity: bigint | number;\n    hex: string;\n    scriptHash: string;\n    token_id_hex?: string;\n    type: string;\n}\n\nexport interface IHistoryFilter {\n    from_height?: number;\n    to_height?: number;\n    include_tokens?: boolean;\n    tokens_only?: boolean;\n    exclude_tokens?: boolean;\n    offset?: number;\n    limit?: number;\n}\n\nexport interface ITXHistory {\n    fee?: number;\n    height: number;\n    tx_hash: string;\n}\n","import {rostrumProvider} from \"../network/RostrumProvider\";\nimport type {AccountIndexes, AccountKeys, AddressKey, Balance} from \"../models/wallet.entities\";\nimport type {ITokenUtxo} from \"../models/rostrum.entities\";\nimport * as Bip39 from 'bip39';\nimport bigDecimal from \"js-big-decimal\";\nimport type {ITXHistory, ITXInput, ITXOutput} from \"../models/rostrum.entities\";\nimport type { Networkish} from \"libnexa-ts\";\nimport {Address, AddressType, HDPrivateKey} from \"libnexa-ts\";\n\nimport {isNil} from \"lodash-es\";\nimport type {BaseAccount} from \"../wallet/accounts/interfaces/BaseAccountInterface\";\nimport DAppAccount from \"../wallet/accounts/models/DappAccount\";\nimport DefaultAccount from \"../wallet/accounts/models/DefaultAccount\";\nimport VaultAccount from \"../wallet/accounts/models/VaultAccount\";\nimport type {TransactionEntity, TxEntityState} from \"../models/transaction.entities\";\nimport {currentTimestamp, isNullOrEmpty} from \"./CommonUtils\";\nimport {getAuthorityPermissions} from \"./TokenUtils\";\n\nexport enum TxTokenType {\n    NO_GROUP,\n    CREATE,\n    MINT,\n    MELT,\n    RENEW,\n    TRANSFER\n}\n\nexport enum AccountType {\n    NEXA_ACCOUNT,\n    VAULT_ACCOUNT,\n    DAPP_ACCOUNT,\n}\n\nexport function isValidNexaAddress(address: string, network: Networkish, type = AddressType.PayToScriptTemplate) {\n    return Address.isValid(address, network, type);\n}\n\nexport function generateMasterKey(mnemonic: string, passphrase?: string | undefined) {\n    const seed = Bip39.mnemonicToSeedSync(mnemonic, passphrase);\n    const masterKey = HDPrivateKey.fromSeed(seed);\n    return masterKey.deriveChild(44, true).deriveChild(29223, true);\n}\n\nexport function generateAccountKey(masterKey: HDPrivateKey, account: number) {\n    return masterKey.deriveChild(account, true);\n}\n\nexport function generateKeysAndAddresses(accountKey: HDPrivateKey, fromRIndex: number, rIndex: number, fromCIndex: number, cIndex: number): AccountKeys {\n    if (fromRIndex < 0) {\n        throw new Error(`Can not generate keys with fromRIndex ${fromRIndex}. must be >= 0.`);\n    }\n    if (fromCIndex < 0) {\n        throw new Error(`Can not generate keys with fromCIndex ${fromCIndex}. must be >= 0.`);\n    }\n    let receive = accountKey.deriveChild(0, false);\n    let change = accountKey.deriveChild(1, false);\n    let rKeys: AddressKey[] = [], cKeys: AddressKey[] = [];\n    for (let index = fromRIndex; index < rIndex; index++) {\n        let k = receive.deriveChild(index, false);\n        let addr = k.privateKey.toAddress().toString();\n        rKeys.push({key: k, address: addr, balance: \"0\", tokensBalance: {}});\n    }\n    for (let index = fromCIndex; index < cIndex; index++) {\n        let k = change.deriveChild(index, false);\n        let addr = k.privateKey.toAddress().toString();\n        cKeys.push({key: k, address: addr, balance: \"0\", tokensBalance: {}});\n    }\n    return {receiveKeys: rKeys, changeKeys: cKeys};\n}\n\nexport function generateKeyAndAddress(accountKey: HDPrivateKey, rIndex: number): AddressKey {\n    let receive = accountKey.deriveChild(0, false);\n    let k = receive.deriveChild(rIndex, false);\n    let addr = k.privateKey.toAddress().toString();\n    return ({key: k, address: addr, balance: \"0\", tokensBalance: {}});\n}\n\nasync function discoverUsedAccountIndexes(deriveKey: HDPrivateKey) {\n    let lastUsed = -1, index = 0, toScan = 20;\n\n    while (toScan > 0) {\n        toScan--;\n        let rAddr = deriveKey.deriveChild(index, false).privateKey.toAddress().toString();\n        let isUsed = await isAddressUsed(rAddr);\n        if (isUsed) {\n            lastUsed = index;\n            toScan = 20;\n        }\n        index++;\n    }\n    // return the last used index, returns -1 if no indexes are used\n    return lastUsed;\n}\n\nexport async function discoverNexaAccount(accountKey: HDPrivateKey) {\n\n    let receiveKey = accountKey.deriveChild(0, false);\n    let changeKey = accountKey.deriveChild(1, false);\n\n    let rIndexPromise = discoverUsedAccountIndexes(receiveKey);\n    let cIndexPromise = discoverUsedAccountIndexes(changeKey);\n\n    let [rIndex, cIndex] = await Promise.all([rIndexPromise, cIndexPromise]);\n\n    // get the index that is the last used nexa addr\n    let indexes: AccountIndexes = { rIndex: rIndex, cIndex: cIndex };\n\n    return indexes;\n}\n\nexport async function discoverNexaAccounts(masterKey: HDPrivateKey, forceSequential: boolean = false) {\n    let accounts: DefaultAccount[] = [];\n\n    let index = 0;\n    while (true) {\n        const nexaAccountKey = generateAccountKey(masterKey, index);\n        const indexes = await discoverNexaAccount(nexaAccountKey);\n        if (indexes.rIndex < 0 && indexes.cIndex < 0)\n        {\n            break;\n        }\n        if (indexes.rIndex < 0) {\n            indexes.rIndex = 0;\n        }\n        if (indexes.cIndex < 0) {\n            indexes.cIndex = 0;\n        }\n        // make account after break check, otherwise we might push an empty account\n        const nexaAccount = new DefaultAccount(index, indexes, generateKeysAndAddresses(nexaAccountKey, 0, indexes.rIndex + 20, 0, indexes.cIndex + 20), nexaAccountKey, forceSequential)\n        await nexaAccount.loadBalances()\n        accounts.push(nexaAccount);\n        if (index == 0) {\n            index = 100;\n        }\n        else {\n            index++;\n        }\n    }\n    if (accounts.length == 0) {\n        // default account was unused but we need to populate at least one account,\n        // make the default account here\n        let defaultNexaAccountKey = generateAccountKey(masterKey, 0);\n        // get the last used indexes, -1 means unused\n        let defaultIndexes: AccountIndexes = { rIndex: 0, cIndex: 0 };\n        const defaultAccount = new DefaultAccount(0, defaultIndexes, generateKeysAndAddresses(defaultNexaAccountKey, defaultIndexes.rIndex, defaultIndexes.rIndex + 20, defaultIndexes.cIndex, defaultIndexes.cIndex + 20), defaultNexaAccountKey, forceSequential)\n        await defaultAccount.loadBalances()\n        accounts.push(defaultAccount)\n    }\n    return accounts;\n}\n\nasync function findUsedVaultAccounts(masterKey: HDPrivateKey) {\n    // all vaults are in bip44 account 1\n    let vaultAccountKey = generateAccountKey(masterKey, 1);\n    // all vaults are in the external chain\n    let vaultChain = vaultAccountKey.deriveChild(0, false);\n    // get the index that is the last used vault\n    return await discoverUsedAccountIndexes(vaultChain);\n}\n\nexport async function discoverVaults(masterKey: HDPrivateKey) {\n    let accounts: VaultAccount[] = [];\n    // all vaults are in bip44 account 1\n    let vaultAccountKey = generateAccountKey(masterKey, 1);\n    // find the next unused vault\n    let lastUsedVaultIndex: number = await findUsedVaultAccounts(masterKey);\n    // if all vaults unused, generate at least the first vault account\n    if (lastUsedVaultIndex < 0) lastUsedVaultIndex = 0;\n    // for each vault found, make the DefaultAccount for that vault\n    for (let index = 0; index <= lastUsedVaultIndex; index++)\n    {\n        const vaultAccount = new VaultAccount(1, index, generateKeyAndAddress(vaultAccountKey, index))\n        await vaultAccount.loadBalances();\n        accounts.push(vaultAccount);\n    }\n    return accounts;\n}\n\nasync function findUsedDappAccounts(masterKey: HDPrivateKey) {\n    // all dApp accounts are in bip44 account 2\n    let dappAccountKey = generateAccountKey(masterKey, 2);\n    // all dApp accounts use the external chain\n    let dappChain = dappAccountKey.deriveChild(0, false);\n    // get the index that is the next unused dApp account\n    return await discoverUsedAccountIndexes(dappChain);\n}\n\nexport async function discoverDappAccounts(masterKey: HDPrivateKey) {\n    let accounts: DAppAccount[] = [];\n    // all dApp accounts are in bip44 account 2\n    let dappAccountKey = generateAccountKey(masterKey, 2);\n    // find the next unused dapp account\n    let lastUsedDappIndex: number = await findUsedDappAccounts(masterKey);\n    // if all dapp accounts unused, generate at least the first dapp account\n    if (lastUsedDappIndex < 0) lastUsedDappIndex = 0;\n    // for each dApp account found, make the DefaultAccount for that dApp account\n    // for each vault found, make the DefaultAccount for that vault\n    for (let index = 0; index <= lastUsedDappIndex; index++)\n    {\n        const dappAccount = new DAppAccount(2, index, generateKeyAndAddress(dappAccountKey, index))\n        await dappAccount.loadBalances();\n        accounts.push(dappAccount);\n    }\n    return accounts;\n}\n\nexport async function discoverWallet(masterKey: HDPrivateKey, forceSequential: boolean = false) {\n    let accounts: BaseAccount[] = [];\n    // accounts 0, 100+\n    const nexaAccounts = await discoverNexaAccounts(masterKey, forceSequential);\n    // vaults in bip44 account 1\n    const vaultAccounts = await discoverVaults(masterKey);\n    // dApp accounts in bip44 account 2\n    const dappAccounts = await discoverDappAccounts(masterKey);\n    // 3 - 99 are reserved and will go here when added\n    accounts = accounts.concat(nexaAccounts);\n    accounts = accounts.concat(vaultAccounts);\n    accounts = accounts.concat(dappAccounts);\n    return accounts;\n}\n\nexport async function isAddressUsed(address: string) {\n    try {\n        let firstUse = await rostrumProvider.getFirstUse(address);\n        return firstUse.tx_hash && firstUse.tx_hash !== \"\";\n    } catch (e) {\n        if (e instanceof Error && e.message.includes(\"not found\")) {\n            return false;\n        }\n        throw e;\n    }\n}\n\nasync function getKeyTokenBalanceAndAuthorities(address: string) {\n    const tokensBalance = await rostrumProvider.getTokensBalance(address);\n    const balance: Record<string, Balance> = {};\n    const authorities: Record<string, ITokenUtxo[]> = {};\n\n\n    // Get all unique token IDs from both confirmed and unconfirmed\n    const allTokenIds = new Set([\n        ...Object.keys(tokensBalance.confirmed),\n        ...Object.keys(tokensBalance.unconfirmed)\n    ]);\n\n    // Process each token to get both balance and check for authorities\n    for (const tokenId of allTokenIds) {\n        const confirmedAmount = tokensBalance.confirmed[tokenId] || 0;\n        const unconfirmedAmount = tokensBalance.unconfirmed[tokenId] || 0;\n\n        // Add to balance if non-zero\n        if (confirmedAmount !== 0 || unconfirmedAmount !== 0) {\n            balance[tokenId] = {\n                confirmed: BigInt(confirmedAmount).toString(),\n                unconfirmed: BigInt(unconfirmedAmount).toString()\n            };\n        }\n\n        // Check for authorities by getting token UTXOs\n        try {\n            const tokenUtxos = await rostrumProvider.getTokenUtxos(address, tokenId);\n\n            if (tokenUtxos && tokenUtxos.length > 0) {\n                // Look for authorities (negative amounts)\n                const authUtxos = tokenUtxos.filter((utxo) => {\n                    const amount = parseInt(String(utxo.token_amount || '0'));\n                    return amount < 0;\n                });\n\n                // Add permissions and address to each authority UTXO and organize by token ID\n                if (authUtxos.length > 0) {\n                    const authoritiesWithPermissions = authUtxos.map(utxo => ({\n                        ...utxo,\n                        permissions: getAuthorityPermissions(parseInt(String(utxo.token_amount || '0'))),\n                        address: address\n                    }));\n                    authorities[tokenId] = authoritiesWithPermissions;\n                }\n            }\n        } catch (_) {\n            // Authority check failed for this token/address — skip\n        }\n    }\n\n    return { balance, authorities };\n}\n\nasync function getAndUpdateAddressKeyBalance(key: AddressKey) {\n    let balance = await rostrumProvider.getBalance(key.address);\n    key.balance = (BigInt(balance.confirmed) + BigInt(balance.unconfirmed)).toString();\n\n    const { balance: tokenBalance, authorities } = await getKeyTokenBalanceAndAuthorities(key.address);\n    key.tokensBalance = tokenBalance;\n\n    return { balance, authorities };\n}\n\nexport async function fetchTotalBalanceAndAuthorities(keys: AddressKey[]): Promise<{balances: Balance[], authorities: Record<string, ITokenUtxo[]>}> {\n    let promises: Promise<{balance: Balance, authorities: Record<string, ITokenUtxo[]>}>[] = [];\n    keys.forEach(key => {\n        promises.push(getAndUpdateAddressKeyBalance(key));\n    });\n\n    const results = await Promise.all(promises);\n    const balances = results.map(r => r.balance);\n\n    // Combine authorities from all addresses, merging by token ID\n    const combinedAuthorities: Record<string, ITokenUtxo[]> = {};\n    results.forEach(result => {\n        Object.keys(result.authorities).forEach(tokenId => {\n            if (combinedAuthorities[tokenId]) {\n                combinedAuthorities[tokenId] = combinedAuthorities[tokenId].concat(result.authorities[tokenId]);\n            } else {\n                combinedAuthorities[tokenId] = result.authorities[tokenId];\n            }\n        });\n    });\n\n    return { balances, authorities: combinedAuthorities };\n}\n\nexport function sumBalance(balances: Balance[]): Balance {\n    let confirmed = new bigDecimal(0), unconfirmed = new bigDecimal(0);\n    balances.forEach(b => {\n        confirmed = confirmed.add(new bigDecimal(b.confirmed));\n        unconfirmed = unconfirmed.add(new bigDecimal(b.unconfirmed));\n    });\n    return {confirmed: confirmed.getValue(), unconfirmed: unconfirmed.getValue()};\n}\n\nexport function sumTokensBalance(balances: Record<string, Balance>[]) {\n    let tokensBalance: Record<string, Balance> = {};\n    balances.forEach(b => {\n        for (const key in b) {\n            if (tokensBalance[key]) {\n                tokensBalance[key].confirmed = (BigInt(tokensBalance[key].confirmed) + BigInt(b[key].confirmed)).toString();\n                tokensBalance[key].unconfirmed = (BigInt(tokensBalance[key].unconfirmed) + BigInt(b[key].unconfirmed)).toString();\n            } else {\n                tokensBalance[key] = { confirmed: b[key].confirmed, unconfirmed: b[key].unconfirmed };\n            }\n        }\n    });\n\n    return tokensBalance;\n}\n\nexport async function fetchTransactionsHistory(addresses: string[], fromHeight: number) {\n    let index = 0, i = 0, data = new Map<string, ITXHistory>(), maxHeight = fromHeight;\n\n    for (let address of addresses) {\n        i++;\n        let txHistory = await rostrumProvider.getTransactionHistory(address);\n        if (txHistory && txHistory.length > 0) {\n            index = i;\n            for (let tx of txHistory) {\n                if (tx.height === 0 || tx.height > fromHeight) {\n                    maxHeight = Math.max(maxHeight, tx.height);\n                    data.set(tx.tx_hash, tx);\n                }\n            }\n        }\n    }\n\n    return {index: index, txs: data, lastHeight: maxHeight};\n}\n\n\nexport async function getNextAccountIndex(accountType: AccountType, masterKey: HDPrivateKey) {\n    if (accountType == AccountType.NEXA_ACCOUNT) {\n        let defaultNexaAccountKey = generateAccountKey(masterKey, 0);\n        const defaultIndexes = await discoverNexaAccount(defaultNexaAccountKey);\n        if (defaultIndexes.rIndex < 0 && defaultIndexes.cIndex < 0){\n            return 0;\n        }\n        else {\n            // account 0 was not empty\n            for (let index = 100; ; index++) {\n                const nexaAccountKey = generateAccountKey(masterKey, index);\n                const indexes = await discoverNexaAccount(nexaAccountKey);\n                if (indexes.rIndex < 0 && indexes.cIndex < 0)\n                {\n                    return index;\n                }\n            }\n        }\n    }\n    else if (accountType == AccountType.VAULT_ACCOUNT) {\n        // find the next unused vault\n        const lastUsedVault: number = await findUsedVaultAccounts(masterKey);\n        return lastUsedVault + 1;\n    }\n    else if (accountType == AccountType.DAPP_ACCOUNT) {\n        // find the next unused dapp account\n        const lastUsedDappAccount: number = await findUsedDappAccounts(masterKey);\n        return lastUsedDappAccount + 1;\n    }\n    else {\n        throw new Error(\"Can not get next account index. Invalid accountType.\");\n    }\n}\n\nexport async function classifyTransaction(txHistory: ITXHistory, myAddresses: string[]) {\n    let t = await rostrumProvider.getTransaction(txHistory.tx_hash);\n\n    let outputs = t.vout.filter(utxo => !isNil(utxo.scriptPubKey.addresses));\n\n    let isOutgoing = t.vin.length > 0 && myAddresses.includes(t.vin[0].addresses[0]);\n    let isIncoming = !isOutgoing || outputs.every(utxo => myAddresses.includes(utxo.scriptPubKey.addresses[0]));\n    let isConfirmed = t.height > 0;\n\n    let txEntry = {} as TransactionEntity;\n    txEntry.txId = t.txid;\n    txEntry.txIdem = t.txidem;\n    txEntry.height = isConfirmed ? t.height : 0;\n    txEntry.time = isConfirmed ? t.time : currentTimestamp();\n    txEntry.fee = t.fee_satoshi;\n\n    if (isOutgoing && isIncoming) {\n        txEntry.state = 'both';\n        txEntry.value = \"0\";\n        txEntry.payTo = \"Payment to yourself\";\n    } else if (isIncoming) {\n        txEntry.state = 'incoming';\n        let utxos = outputs.filter(utxo => myAddresses.includes(utxo.scriptPubKey.addresses[0]));\n        let amount = new bigDecimal(0);\n        utxos.forEach(utxo => {\n            amount = amount.add(new bigDecimal(utxo.value_satoshi));\n        });\n        txEntry.value = amount.getValue();\n        txEntry.payTo = utxos[0].scriptPubKey.addresses[0];\n    } else if(isOutgoing) {\n        txEntry.state = 'outgoing';\n        let utxos = outputs.filter(utxo => !myAddresses.includes(utxo.scriptPubKey.addresses[0]));\n        let amount = new bigDecimal(0);\n        utxos.forEach(utxo => {\n            amount = amount.add(new bigDecimal(utxo.value_satoshi));\n        });\n        txEntry.value = amount.getValue();\n        txEntry.payTo = utxos[0].scriptPubKey.addresses[0];\n    }\n\n    let [txType, txGroup, tokenAmount, extraGroup] = classifyTokenTransaction(t.vin, outputs, txEntry.state, myAddresses);\n    txEntry.txGroupType = txType;\n    txEntry.token = txGroup;\n    txEntry.tokenAmount = tokenAmount;\n    txEntry.extraGroup = extraGroup;\n\n    return txEntry;\n}\n\nfunction classifyTokenTransaction(vin: ITXInput[], vout: ITXOutput[], txState: TxEntityState, myAddresses: string[]): [TxTokenType, string, string, string] {\n    let groupInputs = vin.filter(input => !isNullOrEmpty(input.group));\n    let groupOutputs = vout.filter(output => !isNullOrEmpty(output.scriptPubKey.group));\n\n    if (isNullOrEmpty(groupInputs) && isNullOrEmpty(groupOutputs)) {\n        return [TxTokenType.NO_GROUP, \"none\", \"0\", \"none\"];\n    }\n\n    let myGroupInputs = groupInputs.filter(input => myAddresses.includes(input.addresses[0]));\n    let myGroupOutputs = groupOutputs.filter(output => myAddresses.includes(output.scriptPubKey.addresses[0]));\n\n    if (isNullOrEmpty(myGroupInputs) && isNullOrEmpty(myGroupOutputs)) {\n        return [TxTokenType.NO_GROUP, \"none\", \"0\", \"none\"];\n    }\n\n    if (isNullOrEmpty(groupInputs)) {\n        let group = myGroupOutputs.find(output => BigInt(output.scriptPubKey.groupQuantity) < 0n)?.scriptPubKey.group ?? \"none\";\n        return [TxTokenType.CREATE, group, \"0\", \"none\"];\n    }\n\n    if (isNullOrEmpty(groupOutputs)) {\n        if (txState === 'incoming') {\n            return [TxTokenType.NO_GROUP, \"none\", \"0\", \"none\"];\n        }\n\n        let inputs = myGroupInputs.filter(input => BigInt(input.groupQuantity) > 0n);\n        if (!isNullOrEmpty(inputs)) {\n            let amount = new bigDecimal(0);\n            inputs.forEach(utxo => {\n                amount = amount.add(new bigDecimal(utxo.groupQuantity));\n            });\n            let group = inputs[0].group;\n            let extraGroup = myGroupInputs.find(input => BigInt(input.groupQuantity) < 0n && inputs[0].group != input.group)?.group ?? \"none\";\n            return [TxTokenType.MELT, group, amount.getValue(), extraGroup];\n        }\n\n        let group = myGroupInputs.find(input => BigInt(input.groupQuantity) < 0n)?.group ?? \"none\";\n        let extraGroup = myGroupInputs.find(input => BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? \"none\";\n        return [TxTokenType.MELT, group, \"0\", extraGroup];\n    }\n\n    let tokenInputs = groupInputs.filter(input => BigInt(input.groupQuantity) > 0n);\n    let tokenOutputs = groupOutputs.filter(output => BigInt(output.scriptPubKey.groupQuantity) > 0n);\n\n    if (isNullOrEmpty(tokenInputs) && isNullOrEmpty(tokenOutputs)) {\n        let group = groupInputs.find(input => BigInt(input.groupQuantity) < 0n)?.group ?? \"none\";\n        let extraGroup = groupOutputs.find(output => BigInt(output.scriptPubKey.groupQuantity) < 0n && group != output.scriptPubKey.group)?.scriptPubKey.group ?? \"none\";\n        return [TxTokenType.RENEW, extraGroup !== 'none' ? extraGroup : group, \"0\", extraGroup !== 'none' ? group : extraGroup];\n    }\n\n    if (isNullOrEmpty(tokenInputs)) {\n        let group = tokenOutputs[0].scriptPubKey.group;\n        let amount = new bigDecimal(0);\n        tokenOutputs.forEach(utxo => {\n            amount = amount.add(new bigDecimal(utxo.scriptPubKey.groupQuantity));\n        });\n        let extraGroup = groupInputs.find(input => BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? \"none\";\n        return [TxTokenType.MINT, group, amount.getValue(), extraGroup];\n    }\n\n    if (isNullOrEmpty(tokenOutputs)) {\n        let group = tokenInputs[0].group;\n        let amount = new bigDecimal(0);\n        tokenInputs.forEach(utxo => {\n            amount = amount.add(new bigDecimal(utxo.groupQuantity));\n        });\n        let extraGroup = groupInputs.find(input => BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? \"none\";\n        return [TxTokenType.MELT, group, amount.getValue(), extraGroup];\n    }\n\n    let outQuantitySum = tokenOutputs.map(output => BigInt(output.scriptPubKey.groupQuantity)).reduce((a, b) => a + b, 0n);\n    let inQuantitySum = tokenInputs.map(input => BigInt(input.groupQuantity)).reduce((a, b) => a + b, 0n);\n\n    if (outQuantitySum > inQuantitySum) {\n        let group = tokenOutputs[0].scriptPubKey.group;\n        let extraGroup = groupInputs.find(input => BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? \"none\";\n        return [TxTokenType.MINT, group, (outQuantitySum - inQuantitySum).toString(), extraGroup];\n    }\n\n    if (inQuantitySum > outQuantitySum) {\n        let group = tokenInputs[0].group;\n        let extraGroup = groupInputs.find(input => BigInt(input.groupQuantity) < 0n && group != input.group)?.group ?? \"none\";\n        return [TxTokenType.MELT, group, (inQuantitySum - outQuantitySum).toString(), extraGroup];\n    }\n\n    let group = tokenOutputs[0].scriptPubKey.group;\n    let amount = \"\";\n    if (txState === 'incoming') {\n        amount = tokenOutputs\n            .filter(output => myAddresses.includes(output.scriptPubKey.addresses[0]))\n            .map(output => BigInt(output.scriptPubKey.groupQuantity))\n            .reduce((a, b) => a + b, 0n)\n            .toString();\n    } else if (txState === 'outgoing') {\n        amount = tokenOutputs\n            .filter(output => !myAddresses.includes(output.scriptPubKey.addresses[0]))\n            .map(output => BigInt(output.scriptPubKey.groupQuantity))\n            .reduce((a, b) => a + b, 0n)\n            .toString();\n    } else {\n        amount = \"0\";\n    }\n\n    return [TxTokenType.TRANSFER, group, amount, \"none\"];\n}\n",null,"//function add {\r\nexport function add(number1: string, number2 = \"0\") {\r\n  let neg = 0,\r\n    ind = -1,\r\n    neg_len;\r\n\r\n  //check for negatives\r\n  if (number1[0] == \"-\") {\r\n    number1 = number1.substring(1);\r\n    if (!testZero(number1)) {\r\n      neg++;\r\n      ind = 1;\r\n      neg_len = number1.length;\r\n    }\r\n  }\r\n  if (number2[0] == \"-\") {\r\n    number2 = number2.substring(1);\r\n    if (!testZero(number2)) {\r\n      neg++;\r\n      ind = 2;\r\n      neg_len = number2.length;\r\n    }\r\n  }\r\n\r\n  number1 = trim(number1);\r\n  number2 = trim(number2);\r\n\r\n  [number1, number2] = pad(trim(number1), trim(number2));\r\n\r\n  if (neg == 1) {\r\n    if (ind === 1) number1 = compliment(number1);\r\n    else if (ind === 2) number2 = compliment(number2);\r\n  }\r\n\r\n  let res = addCore(number1, number2);\r\n  if (!neg) return trim(res);\r\n  else if (neg == 2) return \"-\" + trim(res);\r\n  else {\r\n    if (number1.length < res.length) return trim(res.substring(1));\r\n    else return \"-\" + trim(compliment(res));\r\n  }\r\n}\r\n\r\nfunction compliment(number: string) {\r\n  if (testZero(number)) {\r\n    return number;\r\n  }\r\n\r\n  let s = \"\",\r\n    l = number.length,\r\n    dec = number.split(\".\")[1],\r\n    ld = dec ? dec.length : 0;\r\n\r\n  for (let i = 0; i < l; i++) {\r\n    if (number[i] >= \"0\" && number[i] <= \"9\") s += 9 - parseInt(number[i]);\r\n    else s += number[i];\r\n  }\r\n\r\n  let one = ld > 0 ? \"0.\" + new Array(ld).join(\"0\") + \"1\" : \"1\";\r\n\r\n  return addCore(s, one);\r\n}\r\n\r\nexport function trim(number: string) {\r\n  let parts = number.split(\".\");\r\n\r\n  if (!parts[0]) parts[0] = \"0\";\r\n\r\n  while (parts[0][0] == \"0\" && parts[0].length > 1)\r\n    parts[0] = parts[0].substring(1);\r\n\r\n  return parts[0] + (parts[1] ? \".\" + parts[1] : \"\");\r\n}\r\n\r\nexport function pad(number1: string, number2: string) {\r\n  let parts1 = number1.split(\".\"),\r\n    parts2 = number2.split(\".\");\r\n\r\n  //pad integral part\r\n  let length1 = parts1[0].length,\r\n    length2 = parts2[0].length;\r\n  if (length1 > length2) {\r\n    parts2[0] =\r\n      new Array(Math.abs(length1 - length2) + 1).join(\"0\") +\r\n      (parts2[0] ? parts2[0] : \"\");\r\n  } else {\r\n    parts1[0] =\r\n      new Array(Math.abs(length1 - length2) + 1).join(\"0\") +\r\n      (parts1[0] ? parts1[0] : \"\");\r\n  }\r\n\r\n  //pad fractional part\r\n  (length1 = parts1[1] ? parts1[1].length : 0),\r\n    (length2 = parts2[1] ? parts2[1].length : 0);\r\n  if (length1 || length2) {\r\n    if (length1 > length2) {\r\n      parts2[1] =\r\n        (parts2[1] ? parts2[1] : \"\") +\r\n        new Array(Math.abs(length1 - length2) + 1).join(\"0\");\r\n    } else {\r\n      parts1[1] =\r\n        (parts1[1] ? parts1[1] : \"\") +\r\n        new Array(Math.abs(length1 - length2) + 1).join(\"0\");\r\n    }\r\n  }\r\n\r\n  number1 = parts1[0] + (parts1[1] ? \".\" + parts1[1] : \"\");\r\n  number2 = parts2[0] + (parts2[1] ? \".\" + parts2[1] : \"\");\r\n\r\n  return [number1, number2];\r\n}\r\n\r\nfunction addCore(number1: string, number2: string) {\r\n  [number1, number2] = pad(number1, number2);\r\n\r\n  let sum = \"\",\r\n    carry = 0;\r\n\r\n  for (let i = number1.length - 1; i >= 0; i--) {\r\n    if (number1[i] === \".\") {\r\n      sum = \".\" + sum;\r\n      continue;\r\n    }\r\n    let temp = parseInt(number1[i]) + parseInt(number2[i]) + carry;\r\n    sum = (temp % 10) + sum;\r\n    carry = Math.floor(temp / 10);\r\n  }\r\n\r\n  return carry ? carry.toString() + sum : sum;\r\n}\r\n\r\nfunction testZero(number: string) {\r\n  return /^0[0]*[.]{0,1}[0]*$/.test(number);\r\n}\r\n","export function abs(n: number | string | bigint) {\r\n  if (typeof n == \"number\" || typeof n == \"bigint\") n = n.toString();\r\n  if (n[0] == \"-\") return n.substring(1);\r\n  return n;\r\n}\r\n","export enum RoundingModes {\r\n    /**\r\n     * Rounding mode to round towards positive infinity.\r\n     */\r\n    CEILING,\r\n\r\n    /**\r\n     * Rounding mode to round towards zero.\r\n     */\r\n    DOWN,\r\n\r\n    /**\r\n     * Rounding mode to round towards negative infinity.\r\n     */\r\n    FLOOR,\r\n\r\n    /**\r\n     * Rounding mode to round towards \"nearest neighbor\" unless both neighbors are equidistant, \r\n     * in which case round down.\r\n     */\r\n    HALF_DOWN,\r\n\r\n    /**\r\n     * Rounding mode to round towards the \"nearest neighbor\" unless both neighbors are equidistant, \r\n     * in which case, round towards the even neighbor.\r\n     */\r\n    HALF_EVEN,\r\n\r\n    /**\r\n     * Rounding mode to round towards \"nearest neighbor\" unless both neighbors are equidistant, \r\n     * in which case round up.\r\n     */\r\n    HALF_UP,\r\n\r\n    /**\r\n     * Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.\r\n     * UNIMPLEMENTED\r\n     */\r\n    UNNECESSARY,\r\n\r\n    /**\r\n     * Rounding mode to round away from zero.\r\n     */\r\n    UP\r\n}\r\n\r\n","import { RoundingModes } from './roundingModes';\r\n/**\r\n * \r\n * @param input the number to round\r\n * @param n precision\r\n * @param mode Rounding Mode\r\n */\r\nexport function roundOff(input: number | string | bigint, n: number = 0, mode=RoundingModes.HALF_EVEN) {\r\n    if (mode === RoundingModes.UNNECESSARY) {\r\n        throw new Error(\"UNNECESSARY Rounding Mode has not yet been implemented\");\r\n    }\r\n\r\n    if (typeof (input) == 'number' || typeof (input) == 'bigint')\r\n        input = input.toString();\r\n\r\n    let neg = false;\r\n    if (input[0] === '-') {\r\n        neg = true;\r\n        input = input.substring(1);\r\n    }\r\n\r\n    let parts = input.split('.'),\r\n        partInt = parts[0],\r\n        partDec = parts[1];\r\n\r\n    //handle case of -ve n: roundOff(12564,-2)=12600\r\n    if (n < 0) {\r\n        n = -n;\r\n        if (partInt.length <= n)\r\n            return '0';\r\n        else {\r\n            let prefix = partInt.substr(0, partInt.length - n);\r\n            input = prefix + '.' + partInt.substr(partInt.length - n) + partDec;\r\n            prefix = roundOff(input, 0, mode);\r\n            return (neg ? '-' : '') + prefix + (new Array(n + 1).join('0'));\r\n        }\r\n    }\r\n\r\n\r\n    // handle case when integer output is desired\r\n    if (n == 0) {\r\n        let l = partInt.length;\r\n        if (greaterThanFive(parts[1], partInt, neg, mode)) {\r\n            partInt = increment(partInt);\r\n        }\r\n        return (neg&&parseInt(partInt) ? '-' : '') + partInt;\r\n    }\r\n\r\n\r\n    // handle case when n>0\r\n    if (!parts[1]) {\r\n        return (neg ? '-' : '') + partInt + '.' + (new Array(n + 1).join('0'));\r\n    } else if (parts[1].length < n) {\r\n        return (neg ? '-' : '') + partInt + '.' + parts[1] + (new Array(n - parts[1].length + 1).join('0'));\r\n    }\r\n\r\n    partDec = parts[1].substring(0, n);\r\n    let rem = parts[1].substring(n);\r\n\r\n    if (rem && greaterThanFive(rem, partDec, neg, mode)) {\r\n        partDec = increment(partDec);\r\n        if (partDec.length > n) {\r\n            return (neg ? '-' : '') + increment(partInt, parseInt(partDec[0])) + '.' + partDec.substring(1);\r\n        }\r\n    }\r\n    return (neg&&(parseInt(partInt) || parseInt(partDec)) ? '-' : '') + partInt + '.' + partDec;\r\n}\r\n\r\nfunction greaterThanFive(part: string, pre: string, neg: boolean, mode: RoundingModes) {\r\n    if (!part || part === new Array(part.length + 1).join('0'))\r\n        return false;\r\n\r\n    // #region UP, DOWN, CEILING, FLOOR \r\n    if (mode === RoundingModes.DOWN || (!neg && mode === RoundingModes.FLOOR) ||\r\n        (neg && mode === RoundingModes.CEILING))\r\n        return false;\r\n\r\n    if (mode === RoundingModes.UP || (neg && mode === RoundingModes.FLOOR) ||\r\n        (!neg && mode === RoundingModes.CEILING))\r\n        return true;\r\n    // #endregion\r\n\r\n    // case when part !== five\r\n    let five = '5' + (new Array(part.length).join('0'));\r\n    if (part > five)\r\n        return true;\r\n    else if (part < five)\r\n        return false;\r\n\r\n    // case when part === five\r\n    switch (mode) {\r\n        case RoundingModes.HALF_DOWN: return false;\r\n        case RoundingModes.HALF_UP: return true;\r\n        case RoundingModes.HALF_EVEN:\r\n        default: return (parseInt(pre[pre.length - 1]) % 2 == 1)\r\n    }\r\n}\r\n\r\nfunction increment(part, c: number = 0) {\r\n    if (!c)\r\n        c = 1;\r\n    if (typeof (part) == 'number')\r\n        part.toString();\r\n\r\n    let l = part.length - 1,\r\n        s = '';\r\n\r\n    for (let i = l; i >= 0; i--) {\r\n        let x = parseInt(part[i]) + c;\r\n        if (x == 10) {\r\n            c = 1; x = 0;\r\n        } else {\r\n            c = 0;\r\n        }\r\n        s += x;\r\n    }\r\n    if (c)\r\n        s += c;\r\n\r\n    return s.split('').reverse().join('');\r\n}","/*\r\n* Removes zero from front and back*/\r\nexport function stripTrailingZero(number) {\r\n\tconst isNegative = number[0] === '-';\r\n\tif (isNegative) {\r\n\t\tnumber = number.substr(1);\r\n\t}\r\n\twhile (number[0] == '0') {\r\n\t\tnumber = number.substr(1);\r\n\t}\r\n\tif (number.indexOf('.') != -1) {\r\n\t\twhile (number[number.length - 1] == '0') {\r\n\t\t\tnumber = number.substr(0, number.length - 1);\r\n\t\t}\r\n\t}\r\n\tif (number == \"\" || number == \".\") {\r\n\t\tnumber = '0';\r\n\t} else if (number[number.length - 1] == '.') {\r\n\t\tnumber = number.substr(0, number.length - 1);\r\n\t}\r\n\tif (number[0] == '.') {\r\n\t\tnumber = '0' + number;\r\n\t}\r\n\tif (isNegative && number != '0') {\r\n\t\tnumber = '-' + number;\r\n\t}\r\n\treturn number;\r\n}","import { stripTrailingZero } from \"./stripTrailingZero\"\r\n\r\nexport function multiply(number1, number2) {\r\n\tnumber1 = number1.toString();\r\n\tnumber2 = number2.toString();\r\n\r\n\t/*Filter numbers*/\r\n\tlet negative = 0;\r\n\tif (number1[0] == '-') {\r\n\t\tnegative++;\r\n\t\tnumber1 = number1.substr(1);\r\n\t}\r\n\tif (number2[0] == '-') {\r\n\t\tnegative++;\r\n\t\tnumber2 = number2.substr(1);\r\n\t}\r\n\tnumber1 = stripTrailingZero(number1);\r\n\tnumber2 = stripTrailingZero(number2);\r\n\tlet decimalLength1 = 0;\r\n\tlet decimalLength2 = 0;\r\n\r\n\tif (number1.indexOf('.') != -1) {\r\n\t\tdecimalLength1 = number1.length - number1.indexOf('.') - 1;\r\n\t}\r\n\r\n\tif (number2.indexOf('.') != -1) {\r\n\t\tdecimalLength2 = number2.length - number2.indexOf('.') - 1;\r\n\t}\r\n\tlet decimalLength = decimalLength1 + decimalLength2;\r\n\tnumber1 = stripTrailingZero(number1.replace('.', ''));\r\n\tnumber2 = stripTrailingZero(number2.replace('.', ''));\r\n\r\n\tif (number1.length < number2.length) {\r\n\t\tlet temp = number1;\r\n\t\tnumber1 = number2;\r\n\t\tnumber2 = temp;\r\n\t}\r\n\r\n\tif (number2 == '0') {\r\n\t\treturn '0';\r\n\t}\r\n\r\n\t/*\r\n\t* Core multiplication\r\n\t*/\r\n\tlet length = number2.length;\r\n\tlet carry = 0;\r\n\tlet positionVector = [];\r\n\tlet currentPosition = length - 1;\r\n\r\n\tlet result = \"\";\r\n\tfor (let i = 0; i < length; i++) {\r\n\t\tpositionVector[i] = number1.length - 1;\r\n\t}\r\n\tfor (let i = 0; i < 2 * number1.length; i++) {\r\n\t\tlet sum = 0;\r\n\t\tfor (let j = number2.length - 1; j >= currentPosition && j >= 0; j--) {\r\n\t\t\tif (positionVector[j] > -1 && positionVector[j] < number1.length) {\r\n\t\t\t\tsum += parseInt(number1[positionVector[j]--]) * parseInt(number2[j]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tsum += carry;\r\n\t\tcarry = Math.floor(sum / 10);\r\n\t\tresult = sum % 10 + result;\r\n\t\tcurrentPosition--;\r\n\t}\r\n\t/*\r\n\t* Formatting result\r\n\t*/\r\n\tresult = stripTrailingZero(adjustDecimal(result, decimalLength));\r\n\tif (negative == 1) {\r\n\t\tresult = '-' + result;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/*\r\n* Add decimal point\r\n*/\r\nfunction adjustDecimal(number, decimal) {\r\n\tif (decimal == 0)\r\n\t\treturn number;\r\n\telse {\r\n\t\tnumber = (decimal >= number.length) ? ((new Array(decimal - number.length + 1)).join('0') + number) : number;\r\n\t\treturn number.substr(0, number.length - decimal) + '.' + number.substr(number.length - decimal, decimal)\r\n\t}\r\n}\r\n","import { add, trim } from './add';\r\nimport { roundOff } from './round';\r\nimport { RoundingModes } from './roundingModes';\r\n\r\nexport function divide(dividend, divisor, precission = 8, mode = RoundingModes.HALF_EVEN) {\r\n    if (divisor == 0) {\r\n        throw new Error('Cannot divide by 0');\r\n    }\r\n\r\n    dividend = dividend.toString();\r\n    divisor = divisor.toString();\r\n\r\n    // remove trailing zeros in decimal ISSUE#18\r\n    dividend = dividend.replace(/(\\.\\d*?[1-9])0+$/g, \"$1\").replace(/\\.0+$/, \"\");\r\n    divisor = divisor.replace(/(\\.\\d*?[1-9])0+$/g, \"$1\").replace(/\\.0+$/, \"\");\r\n\r\n    if (dividend == 0)\r\n        return '0';\r\n\r\n    let neg = 0;\r\n    if (divisor[0] == '-') {\r\n        divisor = divisor.substring(1);\r\n        neg++;\r\n    }\r\n    if (dividend[0] == '-') {\r\n        dividend = dividend.substring(1);\r\n        neg++;\r\n    }\r\n\r\n    var pt_dvsr = divisor.indexOf('.') > 0 ? divisor.length - divisor.indexOf('.') - 1 : -1;\r\n\r\n    divisor = trim(divisor.replace('.', ''));\r\n    if (pt_dvsr >= 0) {\r\n        let pt_dvnd = dividend.indexOf('.') > 0 ? dividend.length - dividend.indexOf('.') - 1 : -1;\r\n\r\n        if (pt_dvnd == -1) {\r\n            dividend = trim(dividend + (new Array(pt_dvsr + 1)).join('0'));\r\n        } else {\r\n            if (pt_dvsr > pt_dvnd) {\r\n                dividend = dividend.replace('.', '');\r\n                dividend = trim(dividend + (new Array(pt_dvsr - pt_dvnd + 1)).join('0'));\r\n            } else if (pt_dvsr < pt_dvnd) {\r\n                dividend = dividend.replace('.', '');\r\n                let loc = dividend.length - pt_dvnd + pt_dvsr;\r\n                dividend = trim(dividend.substring(0, loc) + '.' + dividend.substring(loc));\r\n            } else if (pt_dvsr == pt_dvnd) {\r\n                dividend = trim(dividend.replace('.', ''));\r\n            }\r\n        }\r\n    }\r\n\r\n    let prec = 0, dl = divisor.length, rem = '0', quotent = '';\r\n    let dvnd = (dividend.indexOf('.') > -1 && dividend.indexOf('.') < dl) ? dividend.substring(0, dl + 1) : dividend.substring(0, dl);\r\n    dividend = (dividend.indexOf('.') > -1 && dividend.indexOf('.') < dl) ? dividend.substring(dl + 1) : dividend.substring(dl);\r\n    \r\n    if (dvnd.indexOf('.') > -1) {\r\n        let shift = dvnd.length - dvnd.indexOf('.') - 1;\r\n        dvnd = dvnd.replace('.', '');\r\n        if (dl > dvnd.length) {\r\n            shift += dl - dvnd.length;\r\n            dvnd = dvnd + (new Array(dl - dvnd.length + 1)).join('0');\r\n        }\r\n        prec = shift;\r\n        quotent = '0.' + (new Array(shift)).join('0');\r\n\r\n    }\r\n\r\n    precission = precission + 2;\r\n\r\n    while (prec <= precission) {\r\n        let qt = 0;\r\n        while (parseInt(dvnd) >= parseInt(divisor)) {\r\n            dvnd = add(dvnd, '-' + divisor);\r\n            qt++;\r\n        }\r\n        quotent += qt;\r\n\r\n        if (!dividend) {\r\n            if (!prec)\r\n                quotent += '.';\r\n            prec++;\r\n            dvnd = dvnd + '0';\r\n        } else {\r\n            if (dividend[0] == '.') {\r\n                quotent += '.';\r\n                prec++;\r\n                dividend = dividend.substring(1);\r\n            }\r\n            dvnd = dvnd + dividend.substring(0, 1);\r\n            dividend = dividend.substring(1);\r\n        }\r\n    }\r\n\r\n    return ((neg == 1) ? '-' : '') + trim(roundOff(quotent, precission - 2, mode));\r\n}","import { add } from './add';\r\n\r\nexport function subtract(number1, number2) {\r\n\tnumber1 = number1.toString();\r\n\tnumber2 = number2.toString();\r\n\tnumber2 = negate(number2);\r\n\treturn add(number1, number2);\r\n}\r\n\r\nexport function negate(number : string){\r\n\tif(number[0] == '-'){\r\n\t\tnumber = number.substr(1);\r\n\t}else{\r\n\t\tnumber = '-' + number;\r\n\t}\r\n\treturn number;\r\n}","import { divide } from './divide';\r\nimport { roundOff } from './round';\r\nimport { multiply } from './multiply';\r\nimport { subtract } from './subtract';\r\nimport { RoundingModes } from './roundingModes';\r\n\r\nexport function modulus(dividend: number|string, divisor:number|string) {\r\n    if (divisor == 0) {\r\n        throw new Error('Cannot divide by 0');\r\n    }\r\n\r\n    dividend = dividend.toString();\r\n    divisor = divisor.toString();\r\n\r\n    validate(dividend);\r\n    validate(divisor);\r\n\r\n    let sign = '';\r\n    if(dividend[0] == '-'){\r\n        sign = '-';\r\n        dividend = dividend.substr(1);\r\n    }\r\n    if(divisor[0] == '-'){\r\n        divisor = divisor.substr(1);\r\n    }\r\n\r\n    let result = subtract(dividend, multiply(divisor, roundOff(divide(dividend, divisor), 0, RoundingModes.FLOOR)));\r\n    return sign+result;\r\n}\r\n\r\nfunction validate(oparand: string) {\r\n    if (oparand.indexOf('.') != -1) {\r\n        throw new Error('Modulus of non-integers not supported');\r\n    }\r\n}\r\n","import { pad } from './add';\r\nimport {stripTrailingZero} from './stripTrailingZero';\r\n\r\nexport function compareTo(number1 : string, number2 : string) {\r\n\tlet negative = false;\r\n\t[number1, number2] = [number1, number2].map(n => stripTrailingZero(n));\r\n\tif(number1[0] == '-' && number2[0] != \"-\"){\r\n\t\treturn -1;\r\n\t}else if(number1[0] != '-' && number2[0] == '-'){\r\n\t\treturn 1;\r\n\t}else if(number1[0] == '-' && number2[0] == '-'){\r\n\t\tnumber1 = number1.substr(1);\r\n\t\tnumber2 = number2.substr(1);\r\n\t\tnegative = true;\r\n\t}\r\n\t[number1, number2] = pad(number1, number2);\r\n\tif(number1.localeCompare(number2) == 0){\r\n\t\treturn 0;\r\n\t}\r\n\tfor(let i = 0 ; i < number1.length ; i++){\r\n\t\tif(number1[i] == number2[i]){\r\n\t\t\tcontinue;\r\n\t\t}else if(number1[i] > number2[i]){\r\n\t\t\tif(negative){\r\n\t\t\t\treturn -1;\r\n\t\t\t}else{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}else{\r\n\t\t\tif(negative){\r\n\t\t\t\treturn 1;\r\n\t\t\t}else{\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nfunction checkZero(number){\r\n\r\n}","import { add, trim } from \"./add\";\r\nimport { abs } from \"./abs\";\r\nimport { roundOff } from \"./round\";\r\nimport { multiply } from \"./multiply\";\r\nimport { divide } from \"./divide\";\r\nimport { modulus } from \"./modulus\";\r\nimport { compareTo } from \"./compareTo\";\r\nimport { subtract, negate } from \"./subtract\";\r\nimport { RoundingModes as Modes, RoundingModes } from \"./roundingModes\";\r\nimport { stripTrailingZero } from \"./stripTrailingZero\";\r\n\r\nclass bigDecimal {\r\n  private value: string;\r\n  static RoundingModes = Modes;\r\n\r\n  private static validate(number): string {\r\n    if (number) {\r\n      number = number.toString();\r\n      if (isNaN(number)) throw Error(\"Parameter is not a number: \" + number);\r\n\r\n      if (number[0] == \"+\") number = number.substring(1);\r\n    } else number = \"0\";\r\n\r\n    //handle missing leading zero\r\n    if (number.startsWith(\".\")) number = \"0\" + number;\r\n    else if (number.startsWith(\"-.\")) number = \"-0\" + number.substr(1);\r\n\r\n    //handle exponentiation\r\n    if (/e/i.test(number)) {\r\n      let [mantisa, exponent] = number.split(/[eE]/);\r\n      mantisa = trim(mantisa);\r\n\r\n      let sign = \"\";\r\n      if (mantisa[0] == \"-\") {\r\n        sign = \"-\";\r\n        mantisa = mantisa.substring(1);\r\n      }\r\n\r\n      if (mantisa.indexOf(\".\") >= 0) {\r\n        exponent = parseInt(exponent) + mantisa.indexOf(\".\");\r\n        mantisa = mantisa.replace(\".\", \"\");\r\n      } else {\r\n        exponent = parseInt(exponent) + mantisa.length;\r\n      }\r\n\r\n      if (mantisa.length < exponent) {\r\n        number =\r\n          sign + mantisa + new Array(exponent - mantisa.length + 1).join(\"0\");\r\n      } else if (mantisa.length >= exponent && exponent > 0) {\r\n        number =\r\n          sign +\r\n          trim(mantisa.substring(0, exponent)) +\r\n          (mantisa.length > exponent ? \".\" + mantisa.substring(exponent) : \"\");\r\n      } else {\r\n        number = sign + \"0.\" + new Array(-exponent + 1).join(\"0\") + mantisa;\r\n      }\r\n    }\r\n\r\n    return number;\r\n  }\r\n\r\n  constructor(number: number | string | bigint = \"0\") {\r\n    this.value = bigDecimal.validate(number);\r\n  }\r\n\r\n  getValue() {\r\n    return this.value;\r\n  }\r\n\r\n  setValue(num: number | string | bigint) {\r\n    this.value = bigDecimal.validate(num);\r\n  }\r\n\r\n  static getPrettyValue(number, digits = 3, separator = \",\"): string {\r\n    // if (!(digits || separator)) {\r\n    //     digits = 3;\r\n    //     separator = ',';\r\n    // } else if (!(digits && separator)) {\r\n    //     throw Error('Illegal Arguments. Should pass both digits and separator or pass none');\r\n    // }\r\n    number = bigDecimal.validate(number);\r\n    let neg = number.charAt(0) == \"-\";\r\n    if (neg) number = number.substring(1);\r\n    var len = number.indexOf(\".\");\r\n    len = len > 0 ? len : number.length;\r\n    var temp = \"\";\r\n    for (var i = len; i > 0; ) {\r\n      if (i < digits) {\r\n        digits = i;\r\n        i = 0;\r\n      } else i -= digits;\r\n\r\n      temp =\r\n        number.substring(i, i + digits) +\r\n        (i < len - digits && i >= 0 ? separator : \"\") +\r\n        temp;\r\n    }\r\n    return (neg ? \"-\" : \"\") + temp + number.substring(len);\r\n  }\r\n  getPrettyValue(digits = 3, separator = \",\") {\r\n    return bigDecimal.getPrettyValue(this.value, digits, separator);\r\n  }\r\n\r\n  static round(number, precision = 0, mode = Modes.HALF_EVEN) {\r\n    number = bigDecimal.validate(number);\r\n    // console.log(number)\r\n    if (isNaN(precision))\r\n      throw Error(\"Precision is not a number: \" + precision);\r\n    return roundOff(number, precision, mode);\r\n  }\r\n\r\n  round(precision = 0, mode = Modes.HALF_EVEN) {\r\n    if (isNaN(precision))\r\n      throw Error(\"Precision is not a number: \" + precision);\r\n\r\n    return new bigDecimal(roundOff(this.value, precision, mode));\r\n  }\r\n\r\n  static abs(number) {\r\n    number = bigDecimal.validate(number);\r\n    return abs(number);\r\n  }\r\n\r\n  abs() {\r\n    return new bigDecimal(abs(this.value));\r\n  }\r\n\r\n  static floor(number) {\r\n    number = bigDecimal.validate(number);\r\n    if (number.indexOf(\".\") === -1) return number;\r\n    return bigDecimal.round(number, 0, RoundingModes.FLOOR);\r\n  }\r\n\r\n  floor() {\r\n    if (this.value.indexOf(\".\") === -1) return new bigDecimal(this.value);\r\n    return new bigDecimal(this.value).round(0, RoundingModes.FLOOR);\r\n  }\r\n\r\n  static ceil(number) {\r\n    number = bigDecimal.validate(number);\r\n    if (number.indexOf(\".\") === -1) return number;\r\n    return bigDecimal.round(number, 0, RoundingModes.CEILING);\r\n  }\r\n\r\n  ceil() {\r\n    if (this.value.indexOf(\".\") === -1) return new bigDecimal(this.value);\r\n    return new bigDecimal(this.value).round(0, RoundingModes.CEILING);\r\n  }\r\n\r\n  static add(number1, number2) {\r\n    number1 = bigDecimal.validate(number1);\r\n    number2 = bigDecimal.validate(number2);\r\n    return add(number1, number2);\r\n  }\r\n\r\n  add(number: bigDecimal) {\r\n    return new bigDecimal(add(this.value, number.getValue()));\r\n  }\r\n\r\n  static subtract(number1, number2) {\r\n    number1 = bigDecimal.validate(number1);\r\n    number2 = bigDecimal.validate(number2);\r\n    return subtract(number1, number2);\r\n  }\r\n\r\n  subtract(number: bigDecimal) {\r\n    return new bigDecimal(subtract(this.value, number.getValue()));\r\n  }\r\n\r\n  static multiply(number1, number2) {\r\n    number1 = bigDecimal.validate(number1);\r\n    number2 = bigDecimal.validate(number2);\r\n    return multiply(number1, number2);\r\n  }\r\n\r\n  multiply(number: bigDecimal) {\r\n    return new bigDecimal(multiply(this.value, number.getValue()));\r\n  }\r\n\r\n  static divide(number1, number2, precision?: number, mode?: RoundingModes) {\r\n    number1 = bigDecimal.validate(number1);\r\n    number2 = bigDecimal.validate(number2);\r\n    return divide(number1, number2, precision, mode);\r\n  }\r\n\r\n  divide(number: bigDecimal, precision?: number, mode?: RoundingModes) {\r\n    return new bigDecimal(divide(this.value, number.getValue(), precision, mode));\r\n  }\r\n\r\n  static modulus(number1, number2) {\r\n    number1 = bigDecimal.validate(number1);\r\n    number2 = bigDecimal.validate(number2);\r\n    return modulus(number1, number2);\r\n  }\r\n\r\n  modulus(number: bigDecimal) {\r\n    return new bigDecimal(modulus(this.value, number.getValue()));\r\n  }\r\n\r\n  static compareTo(number1, number2) {\r\n    number1 = bigDecimal.validate(number1);\r\n    number2 = bigDecimal.validate(number2);\r\n    return compareTo(number1, number2);\r\n  }\r\n\r\n  compareTo(number: bigDecimal) {\r\n    return compareTo(this.value, number.getValue());\r\n  }\r\n\r\n  static negate(number) {\r\n    number = bigDecimal.validate(number);\r\n    return negate(number);\r\n  }\r\n\r\n  negate() {\r\n    return new bigDecimal(negate(this.value));\r\n  }\r\n\r\n  static stripTrailingZero(number) {\r\n    number = bigDecimal.validate(number);\r\n    return stripTrailingZero(number);\r\n  }\r\n\r\n  stripTrailingZero() {\r\n    return new bigDecimal(stripTrailingZero(this.value));\r\n  }\r\n}\r\n\r\nexport { bigDecimal };\r\nexport default bigDecimal;\r\n","import type {AccountIndexes, AccountKeys, AddressKey} from \"../../../models/wallet.entities\";\nimport {BaseAccount} from \"../interfaces/BaseAccountInterface\";\nimport {\n    AccountType,\n    fetchTotalBalanceAndAuthorities,\n    sumBalance,\n    sumTokensBalance\n} from \"../../../utils/WalletUtils\";\nimport type {TransactionEntity} from \"../../../models/transaction.entities\";\n\n/**\n * DAppAccount - Single permanent address account for dApps and multi-user systems\n *\n * Unlike DefaultAccount which manages multiple addresses, DAppAccount uses one permanent address.\n * Ideal for scenarios requiring stable addresses like dApp integrations and multi-user applications.\n *\n * **Key Features:**\n * - Single permanent address per account\n * - BIP44 path: m/44'/29223'/2'/0/index\n * - No change addresses (receive and change use same address)\n * - Sequential indexing: 2.0, 2.1, 2.2, etc.\n *\n * **Use Cases:**\n * - Multi-user applications (each user gets unique account)\n * - DApp integrations (stable address per dApp)\n * - Payment systems (unique address per invoice)\n *\n * @example\n * ```typescript\n * // Create DApp accounts for different users\n * wallet.forceSequentialIndexing = true\n * const user1 = await wallet.newAccount(AccountType.DAPP_ACCOUNT)\n * const user2 = await wallet.newAccount(AccountType.DAPP_ACCOUNT)\n *\n * // Each account has a permanent unique address\n * console.log(user1.getNewAddress()) // Always returns same address\n * console.log(user2.getNewAddress()) // Different from user1\n * ```\n *\n * @see {@link DefaultAccount} for multi-address accounts\n */\nexport default class DAppAccount extends BaseAccount {\n\n    private readonly _accountIndex: number;\n    private readonly _accountKey: AddressKey;\n\n    constructor(bip44Account: number, accountIndex: number, addressKey: AddressKey) {\n        super(bip44Account)\n        this._accountIndex = accountIndex;\n        this._accountKey = addressKey\n    }\n\n    // this is used in AccountStore.ts to get the key to be used in the map for this account\n    public getAccountStoreKey(): string {\n        return String(this._bip44Account + '.' + this._accountIndex);\n    }\n\n    public getAccountType(): AccountType {\n        return AccountType.DAPP_ACCOUNT;\n    }\n\n    public getNewAddress() {\n        return this._accountKey.address;\n    }\n\n    public getNewChangeAddress(): string {\n        return this.getNewAddress();\n    }\n\n    get accountIndexes(): AccountIndexes {\n        return {\n            rIndex: this._accountIndex,\n            cIndex: 0\n        };\n    }\n\n    get accountKeys(): AccountKeys {\n        return {\n            receiveKeys: [this._accountKey],\n            changeKeys: [] // Empty for single-key accounts\n        };\n    }\n\n    async loadBalances(): Promise<void> {\n        const {balances, authorities} = await fetchTotalBalanceAndAuthorities([this._accountKey]);\n        let tokenBalances = [this._accountKey].map(k => k.tokensBalance);\n        super.balance = sumBalance(balances)\n        super.tokenBalances = sumTokensBalance(tokenBalances)\n        super.tokenAuthorities = authorities\n    }\n\n    getKeyFromAddress(address: string): AddressKey {\n        if (address !== this._accountKey.address) {\n            throw new Error(`Address ${address} does not belong to this account`);\n        }\n        return this._accountKey;\n    }\n\n    async getTransactions(fromHeight?: number, address?: string): Promise<Map<string, TransactionEntity>> {\n        const transactionAddress = address ?? this._accountKey.address;\n        return this.fetchAndClassifyTransactions(transactionAddress, fromHeight);\n    }\n\n    public getAddresses(): AddressKey[] {\n        return [this._accountKey];\n    }\n\n    hasChangeAddresses(): boolean {\n        return false;\n    }\n\n    getPrimaryAddressKey(): AddressKey {\n        return this._accountKey;\n    }\n}\n","import type {AccountIndexes, AccountKeys, AddressKey, Balance} from \"../../../models/wallet.entities\";\nimport type {AccountType} from \"../../../utils/WalletUtils\";\nimport {classifyTransaction, fetchTransactionsHistory} from \"../../../utils/WalletUtils\";\nimport type {TransactionEntity} from \"../../../models/transaction.entities\";\nimport {ITokenUtxo} from \"../../../models/rostrum.entities\";\n\nexport abstract class BaseAccount {\n    get transactions(): Map<string, TransactionEntity> {\n        return this._transactions;\n    }\n\n    protected readonly _bip44Account: number;\n    private _balance?: Balance;\n    private _tokenBalances?: Record<string, Balance> = {};\n    private _tokenAuthorities?: Record<string, ITokenUtxo[]> = {};\n    private _transactions : Map<string, TransactionEntity> = new Map<string, TransactionEntity>()\n\n    protected constructor(_bip44Account: number) {\n        this._bip44Account = _bip44Account;\n        this._balance = {\n            confirmed: 0,\n            unconfirmed: 0\n        }\n        this._tokenBalances = {};\n        this._tokenAuthorities = {};\n    }\n\n    abstract get accountIndexes(): AccountIndexes;\n    abstract get accountKeys(): AccountKeys;\n    abstract getNewChangeAddress(): string | Promise<string>;\n    abstract getNewAddress(): string | Promise<string>;\n    abstract getAccountStoreKey(): string;\n    abstract getAccountType(): AccountType;\n    abstract loadBalances(): Promise<void>;\n    abstract getKeyFromAddress(address:string): AddressKey;\n    abstract getTransactions(fromHeight?: number, address?:string): Promise<Map<string, TransactionEntity>>;\n    abstract getAddresses(): AddressKey[];\n    abstract hasChangeAddresses(): boolean;\n    abstract getPrimaryAddressKey(): AddressKey;\n\n    get balance(): Balance {\n        return this._balance!;\n    }\n\n    set balance(value: Balance) {\n        this._balance = value;\n    }\n\n    get tokenBalances(): Record<string, Balance> {\n        return this._tokenBalances!;\n    }\n\n    set tokenBalances(value: Record<string, Balance>) {\n        this._tokenBalances = value;\n    }\n\n    get tokenAuthorities(): Record<string, ITokenUtxo[]> {\n        return this._tokenAuthorities!;\n    }\n\n    set tokenAuthorities(value: Record<string, ITokenUtxo[]>) {\n        this._tokenAuthorities = value;\n    }\n\n    protected async fetchAndClassifyTransactions(transactionAddress: string, fromHeight?: number): Promise<Map<string, TransactionEntity>> {\n        const transactions = await fetchTransactionsHistory([transactionAddress], fromHeight ?? 0);\n\n        const txPromises = Array.from(transactions.txs.values()).map(tx =>\n            classifyTransaction(tx, [transactionAddress])\n        );\n\n        const txEntities = await Promise.all(txPromises);\n\n        for (let txEntity of txEntities) {\n            this.transactions.set(txEntity.txId, txEntity);\n        }\n        return this.transactions;\n    }\n}\n","import type {AccountIndexes, AccountKeys, AddressKey} from \"../../../models/wallet.entities\";\nimport {BaseAccount} from \"../interfaces/BaseAccountInterface\";\nimport {\n    AccountType, classifyTransaction,\n    fetchTotalBalanceAndAuthorities,\n    fetchTransactionsHistory,\n    isAddressUsed,\n    sumBalance,\n    sumTokensBalance\n} from \"../../../utils/WalletUtils\";\nimport type {TransactionEntity} from \"../../../models/transaction.entities\";\nimport type {HDPrivateKey} from \"libnexa-ts\";\n\n/**\n * DefaultAccount represents a standard BIP44 hierarchical deterministic wallet account.\n *\n * This is the primary account type for most wallet operations, supporting both receive\n * and change addresses with automatic address generation and balance tracking.\n *\n * ## Key Features:\n * - **BIP44 Derivation Path**: m/44'/29223'/account'/chain/index\n * - **Dual Address Chains**: Separate receive (chain 0) and change (chain 1) addresses\n * - **Address Generation Modes**:\n *   - Discovery Mode (default): Reuses unused addresses to maintain privacy and reduce gaps\n *   - Sequential Mode: Always generates new addresses (useful for multi-user scenarios)\n * - **Automatic Balance Tracking**: Monitors both NEXA and token balances across all addresses\n * - **Transaction History**: Fetches and classifies transactions for all account addresses\n *\n * ## Address Generation Behavior:\n *\n * ### Discovery Mode (forceSequential = false)\n * In discovery mode, the account follows the BIP44 gap limit standard:\n * - When generating a new address, checks if the current latest address is unused\n * - If unused, returns the existing address instead of creating a new one\n * - Only creates a new address when the current one has been used\n * - Prevents large gaps in the address sequence\n * - Recommended for standard wallet use\n *\n * ### Sequential Mode (forceSequential = true)\n * In sequential mode, the account always generates new addresses:\n * - Each call to getNewAddress() creates a new address with incremented index\n * - Does not check if previous addresses are used\n * - Useful for scenarios like:\n *   - Multi-user applications where each user needs a unique address\n *   - Payment processors requiring unique addresses per invoice\n *   - Situations where address reuse must be avoided\n *\n * ## Usage Examples:\n *\n * ### Basic Address Generation (Discovery Mode)\n * ```typescript\n * const wallet = new Wallet();\n * await wallet.initialize();\n * const account = wallet.getAccount('0') as DefaultAccount;\n *\n * // Get receive address (reuses if unused)\n * const address = await account.getNewAddress();\n * console.log(`Receive: ${address}`);\n *\n * // Get change address (reuses if unused)\n * const changeAddr = await account.getNewChangeAddress();\n * console.log(`Change: ${changeAddr}`);\n * ```\n *\n * ### Sequential Mode for Multi-User Scenarios\n * ```typescript\n * const wallet = new Wallet();\n *\n * // Enable sequential mode BEFORE initialization\n * wallet.forceSequentialIndexing = true;\n * await wallet.initialize();\n *\n * const account = wallet.getAccount('0') as DefaultAccount;\n *\n * // Each user gets a unique address\n * const user1Addr = await account.getNewAddress();\n * const user2Addr = await account.getNewAddress();\n * const user3Addr = await account.getNewAddress();\n * // All addresses are guaranteed to be different\n * ```\n *\n * ### Checking Balances and Transactions\n * ```typescript\n * // Load current balances\n * await account.loadBalances();\n * console.log(`NEXA Balance: ${account.balance.confirmed}`);\n * console.log(`Token Balances:`, account.tokenBalances);\n *\n * // Get transaction history\n * const transactions = await account.getTransactions();\n * transactions.forEach((tx) => {\n *   console.log(`${tx.state} - ${tx.value} - ${tx.payTo}`);\n * });\n * ```\n *\n * @see {@link BaseAccount} for inherited functionality\n * @see {@link AccountKeys} for address key structure\n * @see {@link AccountIndexes} for index management\n */\nexport default class DefaultAccount extends BaseAccount {\n\n    private readonly _accountIndexes: AccountIndexes; // either a list of indexes or a single bip44 account index\n    private _accountKeys: AccountKeys; // either a list of keys or a single key\n    private _masterAccountKey: HDPrivateKey; // master account key for generating new addresses\n    private _forceSequential: boolean = false; // whether to use sequential indexing\n\n    constructor(bip44Account: number, accountIndexes: AccountIndexes, accountKeys: AccountKeys, masterAccountKey: HDPrivateKey, forceSequential: boolean = false) {\n        super(bip44Account)\n\n        if (accountIndexes.rIndex < 0) {\n            throw new Error(`Can not create nexa account with an rindex of ${accountIndexes.rIndex}. must be >= 0.`);\n        }\n\n        if (accountIndexes.cIndex < 0) {\n            throw new Error(`Can not create nexa account with an cindex of ${accountIndexes.cIndex}. must be >= 0.`);\n        }\n\n        this._accountIndexes = accountIndexes;\n        this._accountKeys = accountKeys;\n        this._masterAccountKey = masterAccountKey;\n        this._forceSequential = forceSequential;\n    }\n\n    // this is used in AccountStore.ts to get the key to be used in the map for this account\n    public getAccountStoreKey() {\n        return String(this._bip44Account);\n    }\n\n    public getAccountType(): AccountType {\n        return AccountType.NEXA_ACCOUNT;\n    }\n\n    /**\n     * Helper method to generate a new address for a given chain\n     * @param chain 0 for receive, 1 for change\n     * @returns The generated address string\n     */\n    private generateNewAddressForChain(chain: 0 | 1): string {\n        const isReceive = chain === 0;\n        const currentIndex = isReceive ? this._accountIndexes.rIndex : this._accountIndexes.cIndex;\n        const newIndex = currentIndex + 1;\n\n        const chainKey = this._masterAccountKey.deriveChild(chain, false);\n        const derivedKey = chainKey.deriveChild(newIndex, false);\n        const address = derivedKey.privateKey.toAddress().toString();\n\n        const addressKey: AddressKey = {\n            key: derivedKey,\n            address: address,\n            balance: \"0\",\n            tokensBalance: {}\n        };\n\n        if (isReceive) {\n            this._accountKeys.receiveKeys.push(addressKey);\n            this._accountIndexes.rIndex = newIndex;\n        } else {\n            this._accountKeys.changeKeys.push(addressKey);\n            this._accountIndexes.cIndex = newIndex;\n        }\n\n        return address;\n    }\n\n    /**\n     * Get a receive address for incoming payments\n     * In discovery mode: Returns current address if unused, generates new if used\n     * In sequential mode: Returns next available address from pool or generates new one\n     * @returns The address string\n     */\n    public async getNewAddress(): Promise<string> {\n        if (this._forceSequential) {\n            const lastGeneratedIndex = this._accountKeys.receiveKeys.length - 1;\n\n            // Use pre-generated address if available, otherwise generate new one\n            if (this._accountIndexes.rIndex < lastGeneratedIndex) {\n                this._accountIndexes.rIndex++;\n                return this._accountKeys.receiveKeys[this._accountIndexes.rIndex].address;\n            }\n\n            return this.generateNewAddressForChain(0);\n        }\n\n        // In discovery mode, return the next unused address after rIndex\n        // receiveKeys[rIndex + 1] is the first address after the last used one\n        if (this._accountKeys.receiveKeys.length > this._accountIndexes.rIndex + 1) {\n            const nextAddress = this._accountKeys.receiveKeys[this._accountIndexes.rIndex + 1].address;\n            const isUsed = await isAddressUsed(nextAddress);\n\n            // If next address is unused, return it\n            if (!isUsed) {\n                return nextAddress;\n            }\n        }\n\n        // Next address is used or doesn't exist, generate new one\n        return this.generateNewAddressForChain(0);\n    }\n\n    /**\n     * Get a change address for transaction outputs\n     * In discovery mode: Returns current address if unused, generates new if used\n     * In sequential mode: Always generates a new address\n     * @returns The address string\n     */\n    public async getNewChangeAddress(): Promise<string> {\n        if (this._forceSequential) {\n            return this.generateNewAddressForChain(1);\n        }\n\n        // In discovery mode, return the next unused change address after cIndex\n        // changeKeys[cIndex + 1] is the first address after the last used one\n        if (this._accountKeys.changeKeys.length > this._accountIndexes.cIndex + 1) {\n            const nextAddress = this._accountKeys.changeKeys[this._accountIndexes.cIndex + 1].address;\n            const isUsed = await isAddressUsed(nextAddress);\n\n            // If next address is unused, return it\n            if (!isUsed) {\n                return nextAddress;\n            }\n        }\n\n        // Next address is used or doesn't exist, generate new one\n        return this.generateNewAddressForChain(1);\n    }\n\n    get accountIndexes(): AccountIndexes {\n        return this._accountIndexes;\n    }\n\n    get accountKeys(): AccountKeys {\n        return this._accountKeys;\n    }\n\n    async loadBalances(): Promise<void> {\n        const {balances, authorities} = await fetchTotalBalanceAndAuthorities(this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys));\n        let tokenBalances = this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys).map(k => k.tokensBalance);\n        super.balance = sumBalance(balances)\n        super.tokenBalances = sumTokensBalance(tokenBalances)\n        super.tokenAuthorities = authorities\n    }\n\n    getKeyFromAddress(address: string): AddressKey {\n        const allKeys = this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys)\n        const keyFound = allKeys.find(key => key.address === address)\n        return keyFound!\n    }\n\n    async getTransactions(fromHeight?: number, address?: string): Promise<Map<string, TransactionEntity>> {\n\n        let receiveAddresses = this.accountKeys.receiveKeys.map(ak => ak.address);\n        let changeAddresses = this.accountKeys.changeKeys.map(ak => ak.address);\n        let allAddresses = receiveAddresses.concat(changeAddresses);\n\n        // If specific address provided, only fetch for that address\n        if (address != null) {\n            const transactions = await fetchTransactionsHistory([address], fromHeight ?? 0);\n\n            const txPromises = Array.from(transactions.txs.values()).map(tx =>\n                classifyTransaction(tx, allAddresses)\n            );\n            const txEntities = await Promise.all(txPromises);\n\n            for (let txEntity of txEntities){\n                this.transactions.set(txEntity.txId, txEntity)\n            }\n            return this.transactions;\n        }\n\n        // Fetch from both receive and change addresses\n        let rTxs = fetchTransactionsHistory(receiveAddresses, fromHeight ?? 0);\n        let cTxs = fetchTransactionsHistory(changeAddresses, fromHeight ?? 0);\n\n        let [rData, cData] = await Promise.all([rTxs, cTxs]);\n\n        // Combine transaction data, avoiding duplicates\n        let txHistory = rData.txs;\n        for (let tx of cData.txs.values()) {\n            txHistory.set(tx.tx_hash, tx);\n        }\n\n        // Classify all transactions in parallel\n        const txPromises = Array.from(txHistory.values()).map(tx =>\n            classifyTransaction(tx, allAddresses)\n        );\n        const txEntities = await Promise.all(txPromises);\n\n        for (let txEntity of txEntities){\n            this.transactions.set(txEntity.txId, txEntity)\n        }\n        return this.transactions\n    }\n\n    public getAddresses(): AddressKey[] {\n        return this._accountKeys.receiveKeys.concat(this._accountKeys.changeKeys);\n    }\n\n    hasChangeAddresses(): boolean {\n        return true; // BIP44 accounts always support change addresses\n    }\n\n    getPrimaryAddressKey(): AddressKey {\n        // For DefaultAccount, return the first receive key as the primary key\n        if (this._accountKeys.receiveKeys.length === 0) {\n            throw new Error(\"No receive keys available in account\");\n        }\n        return this._accountKeys.receiveKeys[0];\n    }\n}\n","import type {AccountIndexes, AccountKeys, AddressKey} from \"../../../models/wallet.entities\";\nimport {BaseAccount} from \"../interfaces/BaseAccountInterface\";\nimport {\n    AccountType, classifyTransaction,\n    fetchTotalBalanceAndAuthorities,\n    fetchTransactionsHistory,\n    sumBalance,\n    sumTokensBalance\n} from \"../../../utils/WalletUtils\";\nimport type {TransactionEntity} from \"../../../models/transaction.entities\";\n\nexport default class VaultAccount extends BaseAccount {\n\n    private readonly _accountIndex: number;\n    private readonly _accountKey: AddressKey;\n\n    constructor(bip44Account: number, accountIndex: number, addressKey: AddressKey) {\n        super(bip44Account)\n        this._accountIndex = accountIndex;\n        this._accountKey = addressKey;\n    }\n\n    // this is used in AccountStore.ts to get the key to be used in the map for this account\n    public getAccountStoreKey(): string {\n        return String(this._bip44Account + '.' + this._accountIndex);\n    }\n\n    public getAccountType(): AccountType {\n        return AccountType.VAULT_ACCOUNT\n    }\n\n    public getNewAddress() {\n        return this._accountKey.address\n    }\n\n    public getNewChangeAddress(): string {\n        return this.getNewAddress();\n    }\n\n    get accountIndexes(): AccountIndexes {\n        return {\n            rIndex: this._accountIndex,\n            cIndex: 0\n        };\n    }\n\n    get accountKeys(): AccountKeys {\n        return {\n            receiveKeys: [this._accountKey],\n            changeKeys: [] // Empty for single-key accounts\n        };\n    }\n\n    async loadBalances(): Promise<void> {\n        const {balances, authorities} = await fetchTotalBalanceAndAuthorities([this._accountKey]);\n        let tokenBalances = [this._accountKey].map(k => k.tokensBalance);\n        super.balance = sumBalance(balances)\n        super.tokenBalances = sumTokensBalance(tokenBalances)\n        super.tokenAuthorities = authorities\n    }\n\n    getKeyFromAddress(address: string): AddressKey {\n        if (address !== this._accountKey.address) {\n            throw new Error(`Address ${address} does not belong to this account`);\n        }\n        return this._accountKey;\n    }\n\n    async getTransactions(fromHeight?: number, address?: string): Promise<Map<string, TransactionEntity>> {\n        const transactionAddress = address ?? this._accountKey.address;\n        return this.fetchAndClassifyTransactions(transactionAddress, fromHeight);\n    }\n\n    public getAddresses(): AddressKey[] {\n        return [this._accountKey];\n    }\n\n    hasChangeAddresses(): boolean {\n        return false;\n    }\n\n    getPrimaryAddressKey(): AddressKey {\n        return this._accountKey;\n    }\n}\n","import bigDecimal from 'js-big-decimal';\nimport {Address, BufferUtils, BufferWriter, CommonUtils, Hash} from 'libnexa-ts';\n\n/** Maximum value for a 64-bit signed integer */\nexport const MAX_INT64 = 9223372036854775807n;\n\n/**\n * Get the current Unix timestamp in seconds\n *\n * @returns Current timestamp as number of seconds since Unix epoch\n *\n * @example\n * ```typescript\n * const now = currentTimestamp();\n * console.log('Current time:', now);\n * ```\n */\nexport function currentTimestamp() {\n    return Math.floor(Date.now() / 1000);\n}\n\n/**\n * Check if a value is null, undefined, or empty\n *\n * @param arg - The value to check\n * @returns true if the value is null, undefined, empty string, or empty array\n *\n * @example\n * ```typescript\n * isNullOrEmpty(''); // true\n * isNullOrEmpty([]); // true\n * isNullOrEmpty(null); // true\n * isNullOrEmpty('hello'); // false\n * ```\n */\nexport function isNullOrEmpty(arg?: string | any[] | null): arg is undefined | [] | null | '' {\n    return !arg || arg.length === 0;\n}\n\n/**\n * Parse an amount with decimal places and format it for display\n *\n * Converts a raw amount to a human-readable format by dividing by 10^decimals\n * and removing trailing zeros.\n *\n * @param amount - The raw amount to parse\n * @param decimals - Number of decimal places\n * @returns Formatted amount string\n *\n * @example\n * ```typescript\n * parseAmountWithDecimals(1000000, 6); // '1'\n * parseAmountWithDecimals(1500000, 6); // '1.5'\n * parseAmountWithDecimals(1000000n, 6); // '1'\n * ```\n */\nexport function parseAmountWithDecimals(amount: string | number | bigint, decimals: number) {\n    let val = new bigDecimal(amount).divide(new bigDecimal(Math.pow(10, decimals)), decimals).getPrettyValue();\n    if (val.match(/\\./)) {\n        val = val.replace(/\\.?0+$/, '');\n    }\n    return val;\n}\n\n/**\n * Convert a decimal amount to raw integer format\n *\n * Multiplies the amount by 10^decimals to get the raw integer representation\n * used in transactions.\n *\n * @param amount - The decimal amount to convert\n * @param decimals - Number of decimal places\n * @returns Raw amount as string\n *\n * @example\n * ```typescript\n * getRawAmount('1.5', 6); // '1500000'\n * getRawAmount(1.5, 6); // '1500000'\n * ```\n */\nexport function getRawAmount(amount: string | number | bigint, decimals: number) {\n    return new bigDecimal(amount).multiply(new bigDecimal(Math.pow(10, decimals))).getValue();\n}\n\n/**\n * Get the Uint8Array representation of an address\n *\n * @param address - The address string (hex or Nexa address format)\n * @returns Uint8Array containing the address data\n *\n * @example\n * ```typescript\n * const bytes = getAddressBuffer('nexatest:nqtsq5g5jsdmqqywaqd82lhnnk3a8wqunjz6gtxdtavnnekc');\n * const hexBytes = getAddressBuffer('a1b2c3d4e5f6');\n * ```\n */\nexport function getAddressBuffer(address: string): Uint8Array {\n    if (CommonUtils.isHexa(address)) {\n        return BufferUtils.hexToBuffer(address);\n    }\n    return Address.fromString(address).data;\n}\n\n/**\n * Convert a token ID to hex format\n *\n * @param token - The token ID (hex string or Nexa address format)\n * @returns Token ID in hex format\n *\n * @example\n * ```typescript\n * const hexId = tokenIdToHex('nexatest:tq8r37lcjlqazz7vuvug84q2ev50573hesrnxkv9y6hvhhl5k5qqqnmyf79mx');\n * const hexId2 = tokenIdToHex('a1b2c3d4e5f6'); // already hex, returns as-is\n * ```\n */\nexport function tokenIdToHex(token: string): string {\n    if (CommonUtils.isHexa(token)) {\n        return token;\n    }\n    return BufferUtils.bufferToHex(getAddressBuffer(token));\n}\nexport function calcOutpointHash(txIdem: string, outputIndex: number): string {\n    const writer = new BufferWriter(undefined)\n    const txBytes = BufferUtils.hexToBuffer(txIdem);\n    const reversedTx = new Uint8Array(txBytes).reverse();\n    const outpoint = writer.write(reversedTx).writeUInt32LE(outputIndex).toBuffer()\n    const hash = Hash.sha256(outpoint);\n    const reversedHash = new Uint8Array(hash).reverse();\n    return BufferUtils.bufferToHex(reversedHash);\n}\n\n","import type {PermissionLabel} from \"../models/transaction.entities\";\nimport {GroupToken} from \"libnexa-ts\";\n\nexport function isAuthFit(authFlags: bigint | number, permission: PermissionLabel): boolean {\n    if (authFlags > 0) {\n        return false;\n    }\n\n    let flags = BigInt.asUintN(64, BigInt(authFlags));\n    switch (permission) {\n        case 'authorise':\n            return GroupToken.allowsRenew(flags);\n        case 'mint':\n            return GroupToken.allowsMint(flags);\n        case 'melt':\n            return GroupToken.allowsMelt(flags);\n        case 'rescript':\n            return GroupToken.allowsRescript(flags);\n        case 'subgroup':\n            return GroupToken.allowsSubgroup(flags);\n        default:\n            return false;\n    }\n}\n\nexport function dupAuthority(authFlags: bigint | number, withSubgroup = true): bigint {\n    if (authFlags > 0) {\n        return 0n;\n    }\n\n    let flags = BigInt.asUintN(64, BigInt(authFlags));\n    let newFlags = GroupToken.authFlags.AUTHORITY;\n\n    if (GroupToken.allowsRenew(flags)) {\n        newFlags |= GroupToken.authFlags.BATON;\n    }\n    if (GroupToken.allowsMint(flags)) {\n        newFlags |= GroupToken.authFlags.MINT;\n    }\n    if (GroupToken.allowsMelt(flags)) {\n        newFlags |= GroupToken.authFlags.MELT;\n    }\n    if (GroupToken.allowsRescript(flags)) {\n        newFlags |= GroupToken.authFlags.RESCRIPT;\n    }\n    if (GroupToken.allowsSubgroup(flags) && withSubgroup) {\n        newFlags |= GroupToken.authFlags.SUBGROUP;\n    }\n\n    return newFlags;\n}\n\nexport function buildAuthority(perms: PermissionLabel[]): bigint {\n    let newFlags = GroupToken.authFlags.AUTHORITY;\n    for (let perm of perms) {\n        switch (perm) {\n            case 'authorise':\n                newFlags |= GroupToken.authFlags.BATON;\n                break;\n            case 'mint':\n                newFlags |= GroupToken.authFlags.MINT;\n                break;\n            case 'melt':\n                newFlags |= GroupToken.authFlags.MELT;\n                break;\n            case 'rescript':\n                newFlags |= GroupToken.authFlags.RESCRIPT;\n                break;\n            case 'subgroup':\n                newFlags |= GroupToken.authFlags.SUBGROUP;\n                break;\n        }\n    }\n    return newFlags;\n}\n\n/**\n * Extract permission labels from token authority flags\n * @param authFlags - Authority flags from token UTXO\n * @returns Array of permission labels\n */\nexport function getAuthorityPermissions(authFlags: bigint | number): PermissionLabel[] {\n    if (authFlags > 0) {\n        return [];\n    }\n\n    const permissions: PermissionLabel[] = [];\n    const flags = BigInt.asUintN(64, BigInt(authFlags));\n\n    if (GroupToken.allowsRenew(flags)) {\n        permissions.push('authorise');\n    }\n    if (GroupToken.allowsMint(flags)) {\n        permissions.push('mint');\n    }\n    if (GroupToken.allowsMelt(flags)) {\n        permissions.push('melt');\n    }\n    if (GroupToken.allowsRescript(flags)) {\n        permissions.push('rescript');\n    }\n    if (GroupToken.allowsSubgroup(flags)) {\n        permissions.push('subgroup');\n    }\n\n    return permissions;\n}\n","import {\n    AddressType,\n    BufferUtils, Opcode,\n    PrivateKey,\n    Script,\n    ScriptElement,\n    ScriptFactory,\n    ScriptTemplateInput,\n    TxSignature,\n    TxSigner\n} from \"libnexa-ts\";\nimport { TransactionBuilder, SighashType} from \"libnexa-ts\";\nimport {rostrumProvider} from \"../../network/RostrumProvider\";\nimport {\n    buildCreateGroupTransaction,\n    populateAndDuplicateTokenAuths,\n    populateNexaInputsAndChange,\n    populateTokenAuth,\n    populateTokenInputsAndChange,\n    populateTokenMint,\n    populateTokenMelt,\n    populateSendTokenAuth,\n    prepareDeleteTransaction\n} from \"../../utils/TXUtils\";\nimport type {BaseAccount} from \"../accounts/interfaces/BaseAccountInterface\";\nimport type {AccountKeys, AddressKey} from \"../../models/wallet.entities\";\nimport type {PermissionLabel} from \"../../models/transaction.entities\";\nimport {isValidNexaAddress} from \"../../utils/WalletUtils\";\nimport {TransactionCreator} from \"./interfaces/TransactionCreator\";\n\nexport default class WalletTransactionCreator extends TransactionCreator {\n\n    private  _keysToSign: PrivateKey[] = [];\n    private _account!: BaseAccount;\n    private _fromAddress?: string;\n\n    constructor(fromAccount: BaseAccount, tx?: TransactionBuilder | string | Buffer) {\n        super(tx)\n        this._account = fromAccount\n        this.validateAccount()\n    }\n\n    public fromAccount(fromAccount: BaseAccount): this {\n        this._account = fromAccount\n        return this\n    }\n\n    /**\n     * Restricts UTXO selection to a single address within the account.\n     * Useful in sequential mode where each user has a unique deposit address\n     * and you want to spend only from that address.\n     * @param address The address to restrict UTXO selection to\n     */\n    public fromAddress(address: string): this {\n        // Validate the address belongs to this account\n        const allAddresses = this._account.getAddresses();\n        const found = allAddresses.find(k => k.address === address);\n        if (!found) {\n            throw new Error(`Address ${address} does not belong to this account`);\n        }\n        this._fromAddress = address;\n        return this\n    }\n\n    public parseTxHex(tx: string): this {\n        // Call parent's parseTxHex which handles the common parsing logic\n        return super.parseTxHex(tx)\n    }\n\n    /**\n     * Handle wallet-specific logic for each parsed input (find and store private keys)\n     */\n    protected async handleParsedInput(input: any, utxo: any, index: number): Promise<void> {\n        // Find and store the private key for this input\n        const foundKey = this.findPrivateKeyFromAddress(utxo.addresses[0])\n        if(foundKey) {\n            this._keysToSign.push(foundKey.key.privateKey)\n        }\n    }\n\n    /**\n     * Handle wallet-specific post-processing after parsing is complete\n     */\n    protected async handleParsingComplete(): Promise<void> {\n        // If no keys found, use the primary account key as fallback\n        if(this._keysToSign.length == 0) {\n            this._keysToSign.push(this._account.getPrimaryAddressKey().key.privateKey)\n        }\n    }\n\n    public parseTxBuffer(tx: Buffer): this {\n        // Clear any existing builder operations since we're dealing with a pre-built transaction\n        this.builder = []\n\n        // For buffer, we can parse immediately since it doesn't require async operations\n        this.transactionBuilder = new TransactionBuilder(tx)\n\n        // Extract all possible keys from the account that might be needed for signing\n        // Since we don't have UTXO data, we'll add all account keys\n        const addresses = this._account.getAddresses()\n        for (const addressKey of addresses) {\n            if (!this._keysToSign.includes(addressKey.key.privateKey)) {\n                this._keysToSign.push(addressKey.key.privateKey)\n            }\n        }\n\n        // If no keys found, use the primary account key as fallback\n        if(this._keysToSign.length == 0) {\n            this._keysToSign.push(this._account.getPrimaryAddressKey().key.privateKey)\n        }\n\n        return this\n    }\n\n    public mint(token: string, amount: string, parent?: string): this {\n        this.builder.push(async() => {\n            let toAddr = this._account.accountKeys.receiveKeys.at(-1)!.address;\n            this.tokenAction(toAddr, amount, token, 'mint', parent)\n        })\n\n        return this\n    }\n\n    public melt(token: string, amount: string, parent?: string): this {\n        this.builder.push(async() => {\n            let toAddr = this._account.accountKeys.receiveKeys.at(-1)!.address;\n            this.tokenAction(toAddr, amount, token, 'melt', parent)\n        })\n\n        return this\n    }\n\n    public sendAuthority(token: string, perms: PermissionLabel[], toAddr: string): this {\n        this.builder.push(async() => {\n            // Validate destination address\n            if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n                throw new Error('Invalid Address.');\n            }\n\n            const tokenAction = {\n                token: token,\n                action: 'sendAuthority',\n                amount: 0n,\n                extraData: {\n                    perms: perms,\n                    address: toAddr\n                }\n            };\n            this.tokens.add(tokenAction);\n        })\n\n        return this\n    }\n\n    public populate(): this {\n        this.validateAccount();\n        this.builder.push(async () => {\n            // If fromAddress is set, filter keys to only that address\n            const keys = this._fromAddress\n                ? this.filterKeysToAddress(this._fromAddress)\n                : this._account.accountKeys;\n\n            let tK: PrivateKey[] = []\n            let nK: PrivateKey[] = []\n            if(this.tokens.size > 0) {\n                for (const tokenAction of this.tokens) {\n                    if(tokenAction.action == 'mint') {\n                        tK = tK.concat(await populateTokenMint(this.transactionBuilder, keys, tokenAction.token!, tokenAction.amount, tokenAction.parentToken, this.spentOutpoints))\n                    } else if(tokenAction.action == 'melt') {\n                        tK = tK.concat(await populateTokenMelt(this.transactionBuilder, keys, tokenAction.token!, tokenAction.amount, tokenAction.parentToken))\n                    } else if (tokenAction.action == 'group') {\n                        tK = tK.concat(await buildCreateGroupTransaction(this.transactionBuilder, keys, tokenAction.extraData?.opReturnData!, this.network, this.spentOutpoints))\n                    } else if (tokenAction.action == 'subgroup') {\n                       tK = tK.concat(await populateTokenAuth(this.transactionBuilder, keys, tokenAction.parentToken!, 'subgroup', tokenAction.token, keys.receiveKeys.at(-1)!.address, tokenAction.extraData?.quantity, this.spentOutpoints));\n                    } else if(tokenAction.action == 'renew') {\n                        tK = tK.concat(await populateAndDuplicateTokenAuths(this.transactionBuilder, keys, tokenAction.token!, tokenAction.extraData!.perms!, tokenAction.extraData!.address!))\n                    } else if(tokenAction.action == 'sendAuthority') {\n                        tK = tK.concat(await populateSendTokenAuth(this.transactionBuilder, keys, tokenAction.token!, tokenAction.extraData!.perms!, tokenAction.extraData!.address!))\n                    } else if(tokenAction.action == 'delete') {\n                        tK = tK.concat(await prepareDeleteTransaction(this.transactionBuilder, keys, tokenAction.extraData!.outpoint!))\n                    } else {\n                        tK = tK.concat(await populateTokenInputsAndChange(this.transactionBuilder, keys, tokenAction.token!, tokenAction.amount))\n                    }\n\n                    this._keysToSign!.concat(tK)\n                }\n            }\n\n            nK = nK.concat(await populateNexaInputsAndChange(this.transactionBuilder, keys, this.totalValue, this.txOptions))\n            this._keysToSign! = tK.concat(nK)\n        })\n\n        return this\n    }\n\n    public sign(): this {\n        this.builder.push(async () => {\n\n            // Process each transaction input using placeholder-based signing\n            const inputs = this.transactionBuilder.transaction.inputs\n\n            for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) {\n                const input = inputs[inputIndex];\n\n                // Analyze the scriptSig to determine signing strategy\n                const analysis = this.analyzeScriptSig(input.scriptSig);\n\n                if (analysis.strategy === 'skip') {\n                    continue;\n                }\n\n                // Determine sighash type from placeholder bytes (or default to SIGHASH_ALL)\n                const sighashType = analysis.sighashType || new SighashType();\n\n                // Try signing with all available keys until one works\n                let signed = false;\n                const allAddressKeys = this._account.getAddresses();\n\n                for (const addressKey of allAddressKeys) {\n                    try {\n                        // Sign the input\n                        const sig = TxSigner.sign(\n                            this.transactionBuilder.transaction,\n                            inputIndex,\n                            sighashType,\n                            this.transactionBuilder.transaction.inputs[inputIndex]!.getSubscript(),\n                            addressKey.key.privateKey\n                        );\n\n                        // Create signature buffer (Schnorr signature for Nexa)\n                        const signatureBuffer = new TxSignature({\n                            publicKey: addressKey.key.publicKey,\n                            sigType: sighashType,\n                            signature: sig,\n                            subscript: this.transactionBuilder.transaction.inputs[inputIndex]!.getSubscript(),\n                            inputIndex: inputIndex\n                        }).toTxSatisfier()\n\n\n                        if (analysis.strategy === 'sign_all') {\n                            this.transactionBuilder.signInput(inputIndex, addressKey.key.privateKey, sighashType)\n                        } else if (analysis.strategy === 'replace_placeholder' && analysis.placeholderIndex !== undefined) {\n                            // Handle script template with mixed satisfier elements\n                            if (input instanceof ScriptTemplateInput && analysis.satisfierElements && analysis.satisfierElements.length > 0) {\n                                // Reconstruct script template with preserved satisfier elements plus signature\n                                const templateInput = input as ScriptTemplateInput;\n                                const allSatisfierElements = [...analysis.satisfierElements];\n\n                                // Insert signature at the correct position (where placeholder was)\n                                const relativeIndex = analysis.placeholderIndex - 2; // Adjust for template and constraint chunks\n                                allSatisfierElements.splice(relativeIndex, 0, signatureBuffer);\n\n                                this.transactionBuilder.transaction.inputs[inputIndex]!.scriptSig = this.buildScriptSig(\n                                    templateInput.templateScript,\n                                    templateInput.constraintScript,\n                                    allSatisfierElements\n                                );\n                            } else if (input instanceof ScriptTemplateInput) {\n                                // Script template with only placeholder (no other satisfier elements)\n                                const templateInput = input as ScriptTemplateInput;\n                                this.transactionBuilder.transaction.inputs[inputIndex]!.scriptSig = this.buildScriptSig(\n                                    templateInput.templateScript,\n                                    templateInput.constraintScript,\n                                    [signatureBuffer]\n                                );\n                            } else {\n                                // P2PKH script: signature placeholder + public key\n                                this.transactionBuilder.transaction.inputs[inputIndex]!.scriptSig =\n                                    ScriptFactory.buildPublicKeyHashIn(addressKey.key.publicKey, sig);\n                            }\n                        }\n                        signed = true;\n                        break;\n                    } catch (error) {\n                        // console.log(`Key for address ${addressKey.address} failed to sign input ${inputIndex}:`, (error as Error).message)\n                    }\n                }\n\n                if (!signed) {\n                    // console.warn(`Failed to sign input ${inputIndex} with any available key`)\n                }\n            }\n        })\n\n        return this\n    }\n\n    public buildSatisfier(elements: ScriptElement[]): Script {\n        let script = new Script()\n        for (const element of elements) {\n            script = script.add(element)\n        }\n        return script\n    }\n\n    public buildScriptSig(template: Script, constraint: Script | undefined, satisfierElements: ScriptElement[]): Script {\n        const satisfierScript = this.buildSatisfier(satisfierElements)\n        return ScriptFactory.buildScriptTemplateIn(\n            template,\n            constraint,\n            satisfierScript\n        )\n    }\n\n    /**\n     * Check if a buffer is a 64-byte placeholder (all zeros)\n     * @param buf - Uint8Array to check\n     * @returns true if it's a 64-byte zero placeholder\n     */\n    private isPlaceholder(buf: Uint8Array | undefined): boolean {\n        if (!buf || buf.length < 64) return false;\n        const first64 = buf.subarray(0, 64);\n        // Check if all bytes are zero\n        return first64.every(byte => byte === 0);\n    }\n\n    /**\n     * Extract sighash type from placeholder buffer (bytes after the 64-byte placeholder)\n     * @param buf - Uint8Array that may contain sighash type after placeholder\n     * @returns SighashType or null if using default SIGHASH_ALL (empty sighash = 0)\n     */\n    private extractSighashFromPlaceholder(buf: Uint8Array): SighashType | null {\n        if (buf.length <= 64) {\n            // Empty SigHash - use single byte 0 (sign all inputs and outputs)\n            return SighashType.ALL; // Use default SIGHASH_ALL\n        }\n\n        // Parse the sighash bytes starting at offset 64\n        const sighashBytes = buf.subarray(64);\n\n        if (sighashBytes.length === 0) {\n            return SighashType.ALL; // Default SIGHASH_ALL\n        }\n\n        // Get the sighashtype flag byte\n        const flagByte = sighashBytes[0];\n\n        // Upper 4 bits = input type, Lower 4 bits = output type\n        const inputType = (flagByte >> 4) & 0x0F;\n        const outputType = flagByte & 0x0F;\n\n        const sighashType = new SighashType();\n        let byteIndex = 1;\n\n        // Parse input type flags\n        switch (inputType) {\n            case 0: // All inputs\n                sighashType.inType = 0; // ALL\n                break;\n            case 1: // First N inputs\n                sighashType.inType = 1; // FIRST_N\n                if (byteIndex < sighashBytes.length) {\n                    sighashType.inData = [sighashBytes[byteIndex]];\n                    byteIndex++;\n                }\n                break;\n            case 2: // This input\n                sighashType.inType = 2; // THIS\n                break;\n            default:\n                // Unknown input type, default to ALL\n                sighashType.inType = 0;\n        }\n\n        // Parse output type flags\n        switch (outputType) {\n            case 0: // All outputs\n                sighashType.outType = 0; // ALL\n                break;\n            case 1: // First N outputs\n                sighashType.outType = 1; // FIRST_N\n                if (byteIndex < sighashBytes.length) {\n                    sighashType.outData = [sighashBytes[byteIndex]];\n                    byteIndex++;\n                }\n                break;\n            case 2: // Two outputs N, M\n                sighashType.outType = 2; // TWO_OUTPUTS (if supported)\n                const outData: number[] = [];\n                if (byteIndex < sighashBytes.length) {\n                    outData.push(sighashBytes[byteIndex]);\n                    byteIndex++;\n                }\n                if (byteIndex < sighashBytes.length) {\n                    outData.push(sighashBytes[byteIndex]);\n                    byteIndex++;\n                }\n                sighashType.outData = outData;\n                break;\n            default:\n                // Unknown output type, default to ALL\n                sighashType.outType = 0;\n        }\n\n        return sighashType;\n    }\n\n    /**\n     * Determine signing behavior based on scriptSig content\n     * @param scriptSig - The scriptSig to analyze\n     * @returns Object with signing strategy and sighash type\n     */\n    private analyzeScriptSig(scriptSig: Script): {\n        strategy: 'skip' | 'sign_all' | 'replace_placeholder',\n        sighashType: SighashType | null,\n        placeholderIndex?: number,\n        satisfierElements?: ScriptElement[]\n    } {\n        const chunks = scriptSig.chunks;\n\n        // Empty scriptSig - sign with SIGHASH_ALL\n        if (chunks.length === 0) {\n            return { strategy: 'sign_all', sighashType: SighashType.ALL };\n        }\n\n        // Single chunk\n        if (chunks.length === 1) {\n            const chunk = chunks[0];\n            if (chunk.buf && this.isPlaceholder(chunk.buf)) {\n                // Single placeholder - treat same as empty, sign with SIGHASH_ALL or extract sighash\n                const sighashType = this.extractSighashFromPlaceholder(chunk.buf);\n                return { strategy: 'sign_all', sighashType };\n            }\n            // Single non-placeholder chunk - skip signing\n            return { strategy: 'skip', sighashType: null };\n        }\n\n\n        // For script templates, check if this follows the 3-part structure: template, constraint, satisfier elements\n        // If chunks.length >= 3, assume it's a script template where chunks[2:] are satisfier elements\n        if (chunks.length >= 3) {\n            // Extract satisfier elements (chunks starting from index 2)\n            const satisfierElements: ScriptElement[] = [];\n            let placeholderIndex: number | undefined;\n            let sighashType: SighashType | null = null;\n\n            for (let i = 2; i < chunks.length; i++) {\n                const chunk = chunks[i];\n                if (chunk.buf && this.isPlaceholder(chunk.buf)) {\n                    // Found placeholder in satisfier elements\n                    placeholderIndex = i;\n                    sighashType = this.extractSighashFromPlaceholder(chunk.buf);\n                } else {\n                    // Non-placeholder satisfier element - preserve it\n                    satisfierElements.push(chunk);\n                }\n            }\n\n            if (placeholderIndex !== undefined) {\n                return {\n                    strategy: 'replace_placeholder',\n                    sighashType,\n                    placeholderIndex,\n                    satisfierElements\n                };\n            }\n        }\n\n        // Multiple chunks - look for placeholder (fallback for non-template scripts)\n        for (let i = 0; i < chunks.length; i++) {\n            const chunk = chunks[i];\n            if (chunk.buf && this.isPlaceholder(chunk.buf)) {\n                const sighashType = this.extractSighashFromPlaceholder(chunk.buf);\n                return { strategy: 'replace_placeholder', sighashType, placeholderIndex: i };\n            }\n        }\n\n        // Multiple chunks without placeholder - skip signing\n        return { strategy: 'skip', sighashType: null };\n    }\n\n    /**\n     * Validates that the account has the necessary keys before performing operations\n     * @throws Error if account or keys are not properly initialized\n     */\n    private validateAccount(): void {\n        if (!this._account) {\n            throw new Error('Account must be set before performing transactions');\n        }\n        if (!this._account.accountKeys) {\n            throw new Error('Account keys are not initialized');\n        }\n        if (!this._account.accountKeys.receiveKeys || this._account.accountKeys.receiveKeys.length === 0) {\n            throw new Error('No receive keys available in account');\n        }\n    }\n\n    private findPrivateKeyFromAddress(addr: string): AddressKey | undefined {\n        const keys: AddressKey[] = this._account.getAddresses()\n        return keys.find(key => key.address === addr)\n    }\n\n    private filterKeysToAddress(address: string): AccountKeys {\n        const accountKeys = this._account.accountKeys;\n        const matchReceive = accountKeys.receiveKeys.filter(k => k.address === address);\n        const matchChange = accountKeys.changeKeys.filter(k => k.address === address);\n        if (matchReceive.length === 0 && matchChange.length === 0) {\n            throw new Error(`Address ${address} not found in account keys`);\n        }\n        // Use matched address as both receive and change so change goes back to the same address\n        const matched = matchReceive.length > 0 ? matchReceive : matchChange;\n        return {\n            receiveKeys: matched,\n            changeKeys: matched\n        };\n    }\n}\n","import {rostrumProvider} from '../network/RostrumProvider';\nimport type {AccountKeys} from '../models/wallet.entities';\nimport {AccountKeysUtils} from '../models/wallet.entities';\nimport {isNullOrEmpty, MAX_INT64} from './CommonUtils';\nimport {\n    Networkish,\n    PrivateKey,\n    TransactionBuilder,\n    UTXO\n} from \"libnexa-ts\";\nimport {\n    Address,\n    AddressType,\n    BNExtended,\n    BufferUtils,\n    GroupToken,\n    Transaction,\n    UnitUtils\n} from \"libnexa-ts\";\nimport type {PermissionLabel, TxOptions} from \"../models/transaction.entities\";\nimport {buildAuthority, dupAuthority, isAuthFit} from \"./TokenUtils\";\n\n/** Maximum number of inputs/outputs allowed in a single transaction */\nconst MAX_INPUTS_OUTPUTS = 250;\n\n/**\n * Populate a transaction with Nexa UTXO inputs and set change output if needed\n *\n * This function automatically selects and adds UTXOs from the provided account keys\n * to satisfy the transaction's Nexa amount requirements. It handles change calculation\n * and can consolidate UTXOs when requested.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys containing receive and change addresses with balances\n * @param totalTxValue - Total amount of Nexa required for the transaction (in satoshis)\n * @param options - Transaction options including consolidation settings and change address\n * @returns Promise resolving to array of private keys needed for signing\n * @throws {Error} If insufficient balance or too many inputs required\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await populateNexaInputsAndChange(\n *   txBuilder,\n *   keys,\n *   1000000n, // 1 NEXA\n *   { isConsolidate: false, feeFromAmount: false }\n * );\n * ```\n */\nexport async function populateNexaInputsAndChange(txBuilder: TransactionBuilder, keys: AccountKeys, totalTxValue: bigint, options: TxOptions): Promise<PrivateKey[]> {\n    let rKeys = keys.receiveKeys.filter(k => BigInt(k.balance) > 0n);\n    let cKeys = keys.changeKeys.filter(k => BigInt(k.balance) > 0n);\n    let allKeys = rKeys.concat(cKeys);\n    if (isNullOrEmpty(allKeys)) {\n        throw new Error(\"Not enough Nexa balance.\");\n    }\n\n    let usedKeys = new Map<string, PrivateKey>();\n    let origAmount = options.isConsolidate ? 0 : Number(totalTxValue);\n\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getNexaUtxos(key.address);\n        for (let utxo of utxos) {\n            let input: UTXO = {\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value,\n                templateData: options.templateData\n            }\n            txBuilder.from(input);\n\n            if (!usedKeys.has(key.address)) {\n                usedKeys.set(key.address, key.key.privateKey);\n            }\n\n            if (options.isConsolidate) {\n                txBuilder.change(options.toChange ?? keys.receiveKeys[keys.receiveKeys.length - 1].address);\n                if (txBuilder.transaction.inputs.length > MAX_INPUTS_OUTPUTS) {\n                    return Array.from(usedKeys.values());\n                }\n            } else {\n                let tx = txBuilder.transaction;\n                if (tx.inputs.length > MAX_INPUTS_OUTPUTS) {\n                    throw new Error(\"Too many inputs. Consider consolidate transactions or reduce the send amount.\");\n                }\n\n                let unspent = tx.getUnspentValue();\n                if (unspent < 0n) {\n                    continue;\n                }\n\n                if (unspent == 0n && options.feeFromAmount) {\n                    let txFee = tx.estimateRequiredFee();\n                    tx.updateOutputAmount(0, origAmount - txFee);\n                    return Array.from(usedKeys.values());\n                }\n\n                const changeAddress = options.toChange ??\n                    (keys.changeKeys.length > 0 ? keys.changeKeys[keys.changeKeys.length - 1].address : keys.receiveKeys[keys.receiveKeys.length - 1].address);\n                txBuilder.change(changeAddress);\n                if (options.feeFromAmount) {\n                    let hasChange = tx.getChangeOutput();\n                    let txFee = tx.estimateRequiredFee();\n                    tx.updateOutputAmount(0, origAmount - txFee);\n\n                    // edge case where change added after update\n                    if (!hasChange && tx.getChangeOutput()) {\n                        txFee = tx.estimateRequiredFee();\n                        tx.updateOutputAmount(0, origAmount - txFee);\n                    }\n                }\n\n                // check again after change output manipulation\n                if (tx.getUnspentValue() < tx.estimateRequiredFee()) {\n                    // try to add more utxos to satisfy the minimum fee\n                    continue;\n                }\n                return Array.from(usedKeys.values());\n            }\n        }\n    }\n\n    if (options.isConsolidate) {\n        if (usedKeys.size > 0) {\n            return Array.from(usedKeys.values());\n        }\n        throw new Error(\"Not enough Nexa balance.\");\n    }\n\n    let err = {\n        errorMsg: \"Not enough Nexa balance.\",\n        amount: UnitUtils.formatNEXA(txBuilder.transaction.outputs[0].value),\n        fee: UnitUtils.formatNEXA(txBuilder.transaction.estimateRequiredFee())\n    }\n\n    throw new Error(JSON.stringify(err));\n}\n\n/**\n * Populate a transaction with token UTXO inputs and set token change output if needed\n *\n * This function selects and adds token UTXOs from the provided account keys\n * to satisfy the transaction's token amount requirements. It automatically\n * handles token change calculation.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys containing addresses with token balances\n * @param token - The token ID to spend\n * @param outTokenAmount - Amount of tokens required for the transaction\n * @param spentOutpoints\n * @returns Promise resolving to array of private keys needed for signing\n * @throws {Error} If insufficient token balance or too many inputs required\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await populateTokenInputsAndChange(\n *   txBuilder,\n *   keys,\n *   'token_id_hex',\n *   1000n // Amount of tokens\n * );\n * ```\n */\nexport async function populateTokenInputsAndChange(txBuilder: TransactionBuilder, keys: AccountKeys, token: string, outTokenAmount: bigint): Promise<PrivateKey[]> {\n    let allKeys = keys.receiveKeys.concat(keys.changeKeys);\n\n    if (isNullOrEmpty(allKeys)) {\n        throw new Error(\"Not enough token balance.\");\n    }\n\n    let usedKeys = new Map<string, PrivateKey>();\n    let inTokenAmount = 0n;\n\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getTokenUtxos(key.address, token);\n        for (let utxo of utxos) {\n            if (utxo.token_amount < 0) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value,\n                groupId: utxo.group,\n                groupAmount: BigInt(utxo.token_amount),\n            });\n\n            inTokenAmount = inTokenAmount + BigInt(utxo.token_amount);\n            if (!usedKeys.has(key.address)) {\n                usedKeys.set(key.address, key.key.privateKey);\n            }\n\n            if (inTokenAmount > MAX_INT64) {\n                throw new Error(\"Token inputs exceeded max amount. Consider sending in small chunks\");\n            }\n            if (txBuilder.transaction.inputs.length > MAX_INPUTS_OUTPUTS) {\n                throw new Error(\"Too many inputs. Consider consolidating transactions or reduce the send amount.\");\n            }\n\n            if (inTokenAmount == outTokenAmount) {\n                return Array.from(usedKeys.values());\n            }\n            if (inTokenAmount > outTokenAmount) {\n                const tokenChangeAddress = keys.changeKeys.length > 0 ?\n                    keys.changeKeys[keys.changeKeys.length - 1].address :\n                    keys.receiveKeys[keys.receiveKeys.length - 1].address;\n                txBuilder.to(tokenChangeAddress, Transaction.DUST_AMOUNT, token, inTokenAmount - outTokenAmount);\n                return Array.from(usedKeys.values());\n            }\n        }\n    }\n\n    throw new Error(\"Not enough token balance\");\n}\n\n/**\n * Build a transaction to create a new token group\n *\n * This function creates a group token by using the first UTXO's outpoint\n * to generate a unique group ID. The group token represents the authority\n * to create fungible tokens within this group.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys to use for funding the transaction\n * @param opReturnData - Optional data to include in the group creation\n * @param network - Network to create the group on\n * @param spentOutpoints\n * @returns Promise resolving to array of private keys needed for signing\n * @throws {Error} If insufficient balance for group creation\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await buildCreateGroupTransaction(\n *   txBuilder,\n *   keys,\n *   'my_token_data',\n *   Networks.mainnet\n * );\n * ```\n */\nexport async function buildCreateGroupTransaction(\n    txBuilder: TransactionBuilder,\n    keys: AccountKeys,\n    opReturnData: string,\n    network: Networkish,\n    spentOutpoints?: Set<string>\n): Promise<PrivateKey[]> {\n    // TODO validate opreturn data\n    const allKeys = AccountKeysUtils.getAllKeys(keys)\n    let outpoint = '';\n    let usedKeys: PrivateKey[] = [];\n    let signKey: PrivateKey | undefined = undefined;\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getNexaUtxos(key.address);\n        for (let utxo of utxos) {\n            if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value\n            });\n\n            if (spentOutpoints) {\n                spentOutpoints.add(utxo.outpoint_hash);\n            }\n\n            if (isNullOrEmpty(outpoint)) {\n                outpoint = utxo.outpoint_hash;\n                const opReturnBytes = BufferUtils.hexToBuffer(opReturnData);\n                let id = GroupToken.findGroupId(outpoint, opReturnBytes, GroupToken.authFlags.ACTIVE_FLAG_BITS);\n                const groupId = new Address(id.hashBuffer, network, AddressType.GroupIdAddress).toString()\n                txBuilder.to(keys.receiveKeys.at(-1)!.address, Transaction.DUST_AMOUNT, groupId, GroupToken.authFlags.ACTIVE_FLAG_BITS | id.nonce)\n                signKey = key.key.privateKey\n                usedKeys.push(signKey);\n                return usedKeys\n            }\n        }\n    }\n\n    throw new Error(\"Not enough Nexa balance.\");\n}\n\n/**\n * Prepare a transaction to delete/spend a specific UTXO\n *\n * This function adds a specific UTXO as input to the transaction.\n * It's commonly used for spending token authority UTXOs or consolidating specific outputs.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys to find the private key for the UTXO\n * @param outpoint - The outpoint (txid:vout) of the UTXO to spend\n * @returns Promise resolving to array containing the private key for the UTXO\n * @throws {Error} If the UTXO is not found or the associated key is not in the wallet\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await prepareDeleteTransaction(\n *   txBuilder,\n *   keys,\n *   'txid:0'\n * );\n * ```\n */\nexport async function prepareDeleteTransaction(txBuilder: TransactionBuilder, keys: AccountKeys, outpoint: string): Promise<PrivateKey[]> {\n    let utxo = await rostrumProvider.getUtxo(outpoint);\n    let address = utxo.addresses[0];\n\n    txBuilder.from({\n        outpoint: outpoint,\n        address: address,\n        satoshis: utxo.amount\n    });\n\n    let allKeys = AccountKeysUtils.getAllKeys(keys);\n    let addrKey = allKeys.find(k => k.address === address);\n\n    if (!addrKey) {\n        throw new Error('UTXO associated key not found in the wallet');\n    }\n    return [addrKey.key.privateKey];\n}\n\n/**\n * Populate a transaction with token authority inputs for specific permissions\n *\n * This function finds and adds token authority UTXOs that have the required\n * permissions for token operations like minting, melting, or creating subgroups.\n * It automatically handles authority renewal if the authority allows it.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys containing addresses with token authorities\n * @param token - The token ID to find authorities for\n * @param perm - The permission type required ('mint', 'melt', 'subgroup', etc.)\n * @param subgroup - Optional subgroup token ID for subgroup operations\n * @param subgroupAddr - Optional address to receive subgroup authority\n * @param quantity - Optional quantity for subgroup operations, defaults to authority amount if not provided\n * @param spentOutpoints\n * @returns Promise resolving to array of private keys needed for signing\n * @throws {Error} If the required authority is not found\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await populateTokenAuth(\n *   txBuilder,\n *   keys,\n *   'token_id_hex',\n *   'mint'\n * );\n * ```\n */\nexport async function populateTokenAuth(txBuilder: TransactionBuilder, keys: AccountKeys, token: string, perm: PermissionLabel, subgroup = '', subgroupAddr = '', quantity?: bigint, spentOutpoints?: Set<string>): Promise<PrivateKey[]> {\n    let allKeys = AccountKeysUtils.getAllKeys(keys);\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getTokenUtxos(key.address, token);\n        for (let utxo of utxos) {\n            if (!isAuthFit(utxo.token_amount, perm)) {\n                continue;\n            }\n\n            if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value\n            });\n\n            if (spentOutpoints) {\n                spentOutpoints.add(utxo.outpoint_hash);\n            }\n\n            if (perm === 'subgroup') {\n                const subgroupQuantity = quantity ?? dupAuthority(utxo.token_amount, false);\n                txBuilder.to(subgroupAddr, Transaction.DUST_AMOUNT, subgroup, subgroupQuantity);\n            }\n\n            // if renew flag included, we don't want to burn it\n            if (GroupToken.allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) {\n                const authChangeAddress = keys.changeKeys.length > 0 ?\n                    keys.changeKeys[keys.changeKeys.length - 1].address :\n                    keys.receiveKeys[keys.receiveKeys.length - 1].address;\n                txBuilder.to(authChangeAddress, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n            }\n\n            return [key.key.privateKey];\n        }\n    }\n\n    throw new Error(\"The requested authority not found\");\n}\n\n/**\n * Populate a transaction with mint authority and create token outputs\n *\n * This function handles minting tokens for both groups and subgroups.\n * For groups, it uses mint authority to create new tokens.\n * For subgroups (NFTs/SFTs), it uses parent group authority.\n *\n * @param txBuilder - Transaction builder to populate\n * @param keys - Account keys for finding UTXOs\n * @param token - Token ID to mint (for subgroups, this is the NFT token ID)\n * @param amount - Amount of tokens to mint\n * @param parentToken - Optional parent token for subgroup minting\n * @param spentOutpoints - Optional set of already spent outpoints to avoid double-spending\n * @returns Array of private keys needed for signing\n */\nexport async function populateTokenMint(\n    txBuilder: TransactionBuilder,\n    keys: AccountKeys,\n    token: string,\n    amount: bigint,\n    parentToken?: string,\n    spentOutpoints?: Set<string>\n): Promise<PrivateKey[]> {\n    const privateKeys: PrivateKey[] = [];\n    const allKeys = AccountKeysUtils.getAllKeys(keys);\n\n    // Determine which token to look for authority\n    const authTokenId = parentToken || token;\n\n    // Find and add mint authority\n    let mintAuthorityFound = false;\n    for (let key of allKeys) {\n        if (mintAuthorityFound) break;\n\n        let authUtxos = await rostrumProvider.getTokenUtxos(key.address, authTokenId);\n        for (let utxo of authUtxos) {\n            if (!isAuthFit(utxo.token_amount, 'mint')) {\n                continue;\n            }\n\n            // Skip if already spent\n            if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n                continue;\n            }\n\n            // Add mint authority as input\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value\n            });\n\n            if (spentOutpoints) {\n                spentOutpoints.add(utxo.outpoint_hash);\n            }\n\n            // Create the minted tokens output\n            const mintAddress = keys.receiveKeys[keys.receiveKeys.length - 1].address;\n            txBuilder.to(mintAddress, Transaction.DUST_AMOUNT, token, amount);\n\n            // Preserve the mint authority for future use\n            if (GroupToken.allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) {\n                const authChangeAddress = keys.changeKeys.length > 0 ?\n                    keys.changeKeys[keys.changeKeys.length - 1].address :\n                    keys.receiveKeys[keys.receiveKeys.length - 1].address;\n                txBuilder.to(authChangeAddress, Transaction.DUST_AMOUNT, authTokenId, dupAuthority(utxo.token_amount));\n            }\n\n            privateKeys.push(key.key.privateKey);\n            mintAuthorityFound = true;\n            break;\n        }\n    }\n\n    if (!mintAuthorityFound) {\n        throw new Error(`Mint authority not found for token ${authTokenId}`);\n    }\n\n    return privateKeys;\n}\n\n/**\n * Populate a transaction with tokens to melt and the melt authority\n *\n * This function handles melting tokens for both groups and subgroups.\n * It finds tokens to melt and adds them as inputs, along with the melt authority.\n * Only creates outputs for change if melting less than the full amount.\n *\n * @param txBuilder - Transaction builder to populate\n * @param keys - Account keys for finding UTXOs\n * @param token - Token ID to melt\n * @param amount - Amount of tokens to melt\n * @param parentToken - Optional parent token for subgroup melting\n * @param spentOutpoints - Optional set of already spent outpoints to avoid double-spending\n * @returns Array of private keys needed for signing\n */\nexport async function populateTokenMelt(\n    txBuilder: TransactionBuilder,\n    keys: AccountKeys,\n    token: string,\n    amount: bigint,\n    parentToken?: string\n): Promise<PrivateKey[]> {\n    const privateKeys: PrivateKey[] = [];\n    const allKeys = AccountKeysUtils.getAllKeys(keys);\n\n    const authTokenId = parentToken || token;\n\n    // First, find and add melt authority\n    let meltAuthorityFound = false;\n    for (let key of allKeys) {\n        if (meltAuthorityFound) break;\n\n        let authUtxos = await rostrumProvider.getTokenUtxos(key.address, authTokenId);\n        for (let utxo of authUtxos) {\n            if (!isAuthFit(utxo.token_amount, 'melt')) {\n                continue;\n            }\n\n            // Add melt authority as input\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value\n            });\n\n            // Preserve the melt authority for future use\n            if (GroupToken.allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) {\n                const authChangeAddress = keys.changeKeys.length > 0 ?\n                    keys.changeKeys[keys.changeKeys.length - 1].address :\n                    keys.receiveKeys[keys.receiveKeys.length - 1].address;\n                txBuilder.to(authChangeAddress, Transaction.DUST_AMOUNT, authTokenId, dupAuthority(utxo.token_amount));\n            }\n\n            privateKeys.push(key.key.privateKey);\n            meltAuthorityFound = true;\n            break;\n        }\n    }\n\n    if (!meltAuthorityFound) {\n        throw new Error(\"Melt authority not found for token\");\n    }\n\n    // Now find and add token UTXOs to melt\n    let inTokenAmount = 0n;\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getTokenUtxos(key.address, token);\n        for (let utxo of utxos) {\n            // Skip authorities (negative amounts)\n            if (utxo.token_amount < 0) {\n                continue;\n            }\n\n            // Add token UTXO as input\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value,\n                groupId: utxo.group,\n                groupAmount: BigInt(utxo.token_amount)\n            });\n\n            inTokenAmount += BigInt(utxo.token_amount);\n\n            if (!privateKeys.includes(key.key.privateKey)) {\n                privateKeys.push(key.key.privateKey);\n            }\n\n            // Check if we have enough tokens to melt\n            if (inTokenAmount >= amount) {\n                // Create change output if melting less than full amount\n                if (inTokenAmount > amount) {\n                    const changeAddress = keys.changeKeys.length > 0 ?\n                        keys.changeKeys[keys.changeKeys.length - 1].address :\n                        keys.receiveKeys[keys.receiveKeys.length - 1].address;\n                    txBuilder.to(changeAddress, Transaction.DUST_AMOUNT, token, inTokenAmount - amount);\n                }\n                return privateKeys;\n            }\n        }\n    }\n\n    throw new Error(`Not enough token balance to melt. Required: ${amount}, Available: ${inTokenAmount}`);\n}\n\n/**\n * Send token authority to another address\n *\n * This function finds and transfers a token authority UTXO that contains all the\n * specified permissions to a target address. It's used to transfer control/permissions\n * of a token to another wallet.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys containing addresses with token authorities\n * @param token - The token ID to find authority for\n * @param perms - Array of permission types required in the authority\n * @param toAddr - The address to send the authority to\n * @returns Promise resolving to array of private keys needed for signing\n * @throws {Error} If the required authority is not found\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await populateSendTokenAuth(\n *   txBuilder,\n *   keys,\n *   'token_id_hex',\n *   ['mint', 'melt'],\n *   'nexa:recipient_address'\n * );\n * ```\n */\nexport async function populateSendTokenAuth(txBuilder: TransactionBuilder, keys: AccountKeys, token: string, perms: PermissionLabel[], toAddr: string): Promise<PrivateKey[]> {\n    let allKeys = AccountKeysUtils.getAllKeys(keys);\n\n    let requiredPerms = new Set(perms);\n    requiredPerms.add('authorise');\n\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getTokenUtxos(key.address, token);\n        for (let utxo of utxos) {\n            if (utxo.token_amount > 0) {\n                continue;\n            }\n\n            // Check if this authority has all required permissions\n            let hasAllPerms = true;\n            for (let perm of requiredPerms) {\n                if (!isAuthFit(utxo.token_amount, perm)) {\n                    hasAllPerms = false;\n                    break;\n                }\n            }\n\n            if (!hasAllPerms) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value\n            });\n\n            // Send authority to target address\n            txBuilder.to(toAddr, Transaction.DUST_AMOUNT, token, BigInt(utxo.token_amount));\n\n            return [key.key.privateKey];\n        }\n    }\n\n    throw new Error(`The required authority with permissions [${perms.join(', ')}] not found for token ${token}`);\n}\n\n/**\n * Populate a transaction with multiple token authorities and create duplicates\n *\n * This function finds token authority UTXOs for multiple permissions and\n * creates duplicate outputs for each authority. This is useful for complex\n * token operations that require multiple permissions while preserving the authorities.\n *\n * @param txBuilder - The transaction builder to populate\n * @param keys - Account keys containing addresses with token authorities\n * @param token - The token ID to find authorities for\n * @param perms - Array of permission types required\n * @param toAddr\n * @returns Promise resolving to array of private keys needed for signing\n * @throws {Error} If any required authority is not found\n *\n * @example\n * ```typescript\n * const txBuilder = new TransactionBuilder();\n * const keys = await account.getKeys();\n * const privateKeys = await populateAndDuplicateTokenAuths(\n *   txBuilder,\n *   keys,\n *   'token_id_hex',\n *   ['mint', 'melt']\n * );\n * ```\n */\nexport async function populateAndDuplicateTokenAuths(txBuilder: TransactionBuilder, keys: AccountKeys, token: string, perms: PermissionLabel[], toAddr?: string): Promise<PrivateKey[]> {\n    let allKeys = AccountKeysUtils.getAllKeys(keys);\n    let usedKeys: PrivateKey[] = [];\n\n    let reqiredPerms = new Set(perms);\n    reqiredPerms.add('authorise');\n\n    for (let key of allKeys) {\n        let utxos = await rostrumProvider.getTokenUtxos(key.address, token);\n        for (let utxo of utxos) {\n            if (utxo.token_amount > 0) {\n                continue;\n            }\n\n            let found = false;\n            for (let perm of reqiredPerms) {\n                if (isAuthFit(utxo.token_amount, perm)) {\n                    reqiredPerms.delete(perm);\n                    found = true;\n                }\n            }\n\n            if (!found) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: key.address,\n                satoshis: utxo.value\n            });\n            usedKeys.push(key.key.privateKey);\n\n            const receiveAddress = toAddr ?? (keys.changeKeys.length > 0 ? keys.changeKeys[keys.changeKeys.length - 1].address : keys.receiveKeys[keys.receiveKeys.length - 1].address);\n\n            // duplicate existing authority\n            txBuilder.to((keys.changeKeys.length > 0 ? keys.changeKeys[keys.changeKeys.length - 1].address : keys.receiveKeys[keys.receiveKeys.length - 1].address), Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n\n            if (reqiredPerms.size === 0) {\n                // create new authority with the specified permissions\n                txBuilder.to(receiveAddress, Transaction.DUST_AMOUNT, token, buildAuthority(perms));\n                return usedKeys;\n            }\n        }\n    }\n\n    throw new Error(\"The required authorities not found\");\n}\n\n/**\n * Interface for token output data extracted from a transaction\n */\nexport interface TokenOutput {\n    /** Token ID as a string address */\n    tokenId: string;\n    /** Token amount as a string */\n    amount: string;\n}\n\n/**\n * Extract token outputs from a transaction hex string\n *\n * This function parses a transaction and extracts all token outputs,\n * returning their token IDs and amounts. Useful for testing and\n * transaction analysis.\n *\n * @param txHex - Transaction hex string to parse\n * @param network - Network to use for address creation\n * @returns Array of token outputs with tokenId and amount\n *\n * @example\n * ```typescript\n * const { Networks } = await import('libnexa-ts');\n * const tokenOutputs = getTokenOutputsFromTx(txHex, Networks.testnet);\n * console.log(tokenOutputs); // [{ tokenId: 'nexatest:...', amount: '1000' }]\n * ```\n */\nexport function getTokenOutputsFromTx(txHex: string, network: Networkish): TokenOutput[] {\n    const tokenOutputs: TokenOutput[] = [];\n\n    try {\n        const transaction = new Transaction(txHex);\n\n        for (const output of transaction.outputs) {\n            if (output.type !== 0 && output.scriptPubKey.chunks[0]?.opcodenum >= 32) {\n                const tokenIdBytes = output.scriptPubKey.chunks[0].buf;\n                if (tokenIdBytes && output.scriptPubKey.chunks[1]?.buf) {\n                    // Create Address directly from Uint8Array\n                    const tokenAddress = new Address(\n                        tokenIdBytes,\n                        network,\n                        AddressType.GroupIdAddress\n                    );\n\n                    const tokenAddressStr = tokenAddress.toString();\n\n                    // Extract token amount\n                    const tokenAmount = BNExtended.fromScriptNumBuffer(\n                        output.scriptPubKey.chunks[1].buf,\n                        false,\n                        8\n                    ).toBigInt();\n\n                    tokenOutputs.push({\n                        tokenId: tokenAddressStr,\n                        amount: tokenAmount.toString()\n                    });\n                }\n            }\n        }\n    } catch (_) {\n        // Failed to extract token data — return empty array\n    }\n\n    return tokenOutputs;\n}\n","import type bigDecimal from \"js-big-decimal\";\nimport type {HDPrivateKey, PublicKey} from \"libnexa-ts\"\n\nexport interface AccountKeys {\n    receiveKeys: AddressKey[];\n    changeKeys: AddressKey[];\n}\nexport interface WatchOnlyAddress {\n    address: string,\n    xPub? :PublicKey,\n    derivationPath?: string\n}\n\n\nexport interface AccountIndexes {\n    rIndex: number;\n    cIndex: number;\n}\n\nexport interface TxStatus {\n    height: number;\n}\n\nexport interface HodlStatus {\n    idx: number;\n}\n\nexport interface AddressKey {\n    key: HDPrivateKey;\n    address: string;\n    balance: string;\n    tokensBalance: Record<string, Balance>;\n}\n\nexport interface Balance {\n    confirmed: string | number;\n    unconfirmed: string | number;\n}\n\nexport interface Price {\n    value: bigDecimal;\n    change: bigDecimal;\n}\nexport class AccountKeysUtils {\n    static getAllKeys(keys: AccountKeys): AddressKey[] {\n        return keys.receiveKeys.concat(keys.changeKeys);\n    }\n\n    static getAllAddresses(keys: AccountKeys): string[] {\n        return AccountKeysUtils.getAllKeys(keys).map(key => key.address);\n    }\n}","import {\n    Address,\n    AddressType,\n    BufferUtils,\n    GroupToken,\n    Networkish,\n    Networks,\n    Opcode,\n    Output,\n    PublicKey,\n    Script,\n    ScriptFactory,\n    ScriptTemplateInput,\n    Transaction,\n    TransactionBuilder\n} from \"libnexa-ts\";\nimport type {\n    PermissionLabel,\n    TokenAction,\n    TxOptions,\n    GroupOptions,\n    NftSubgroupOptions,\n    SftSubgroupOptions,\n    GenericSubgroupOptions\n} from \"../../../models/transaction.entities\";\nimport {GroupType, SubgroupType} from \"../../../models/transaction.entities\";\nimport {isValidNexaAddress} from \"../../../utils/WalletUtils\";\nimport {parseInt} from \"lodash-es\";\nimport {MAX_INT64} from \"../../../utils/CommonUtils\";\nimport {rostrumProvider} from \"../../../network/RostrumProvider\";\n\n/**\n * Abstract base class for creating and managing transactions in the NEXA blockchain.\n * Provides common functionality for transaction building including token operations,\n * address validation, and output creation.\n */\nexport abstract class TransactionCreator {\n\n    /** The underlying transaction builder instance */\n    private _transactionBuilder!: TransactionBuilder;\n    /** Set of token actions to be performed in this transaction */\n    private _tokens!: Set<TokenAction>;\n    /** Array of async functions to execute when building the transaction */\n    private _builder: (() => Promise<any>)[] = [];\n    /** Total value of NEXA being sent in this transaction */\n    private _totalValue = BigInt(0);\n    /** Network this transaction will be broadcast on */\n    private _network: Networkish = Networks.mainnet\n    /** Transaction options for customizing behavior */\n    private _txOptions: TxOptions = {}\n    /** Set of outpoints already spent in this transaction to prevent double-spending */\n    private _spentOutpoints: Set<string> = new Set()\n\n    /**\n     * Creates a new TransactionCreator instance\n     * @param tx Optional existing TransactionBuilder, hex string, or buffer\n     */\n    protected constructor(tx?: TransactionBuilder | string | Buffer) {\n        if (tx instanceof TransactionBuilder) {\n            this.transactionBuilder = tx;\n        }\n        this.tokens = new Set<TokenAction>()\n        this.transactionBuilder = new TransactionBuilder();\n    }\n\n    /**\n     * Parse transaction from hex string with common logic\n     * @param tx Transaction hex string\n     * @returns This instance for chaining\n     */\n    public parseTxHex(tx: string): this {\n        // Clear any existing builder operations since we're dealing with a pre-built transaction\n        this.builder = []\n\n        // Add the parsing operation to the builder queue\n        this.builder.push(async () => {\n            try {\n                const txBuilder = new TransactionBuilder(tx)\n                const newTxBuilder = new TransactionBuilder()\n                const oldInputs = txBuilder.transaction.inputs\n\n                // Reconstruct inputs with proper script template data if needed\n                for (let i = 0; i < oldInputs.length; i++) {\n                    const input = oldInputs[i]\n                    const utxo = await rostrumProvider.getUtxo(BufferUtils.bufferToHex(input.outpoint))\n                    const scriptPubkey = Script.fromHex(utxo.scriptpubkey)\n\n                    if(scriptPubkey.isScriptTemplateOut()) {\n                        const scriptSig = input.scriptSig\n                        newTxBuilder.transaction.addInput(new ScriptTemplateInput({\n                            amount: input.amount,\n                            outpoint: BufferUtils.bufferToHex(input.outpoint),\n                            scriptSig: input.scriptSig,\n                            templateData: {\n                                templateScript: BufferUtils.isHashBuffer(scriptPubkey.getTemplateHash()) ? Script.fromBuffer(scriptSig.chunks[0].buf!) : Script.empty(),\n                                constraintScript: BufferUtils.isHashBuffer(scriptPubkey.getConstraintHash()) ? Script.fromBuffer(scriptSig.chunks[1].buf!) : undefined\n                            },\n                            output: {\n                                type: input.type,\n                                value: utxo.amount,\n                                scriptPubKey: utxo.scriptpubkey\n                            }\n                        }))\n                    } else {\n                        // For non-template inputs, add them normally\n                        newTxBuilder.from({\n                            outpoint: BufferUtils.bufferToHex(input.outpoint),\n                            satoshis: input.amount,\n                            address: utxo.addresses[0],\n                            scriptPubKey: utxo.scriptpubkey\n                        })\n                    }\n\n                    // Hook for subclasses to handle input-specific logic (like key management)\n                    await this.handleParsedInput(input, utxo, i)\n                }\n\n                // Copy the outputs from the original transaction\n                newTxBuilder.transaction.outputs = txBuilder.transaction.outputs\n                this.transactionBuilder = newTxBuilder\n\n                // Hook for subclasses to perform post-processing\n                await this.handleParsingComplete()\n            } catch (error) {\n                throw error\n            }\n        })\n\n        return this\n    }\n\n    /**\n     * Hook for subclasses to handle individual parsed inputs\n     * @param input The original input from the transaction\n     * @param utxo UTXO data for this input\n     * @param index Input index\n     */\n    protected async handleParsedInput(input: any, utxo: any, index: number): Promise<void> {\n        // Default implementation does nothing - subclasses can override\n    }\n\n    /**\n     * Hook for subclasses to perform post-processing after parsing is complete\n     */\n    protected async handleParsingComplete(): Promise<void> {\n        // Default implementation does nothing - subclasses can override\n    }\n\n    /** Parse transaction from buffer - must be implemented by subclasses */\n    public abstract parseTxBuffer(tx: Buffer): this\n\n    /**\n     * Sets the network for this transaction\n     * @param network Network name or Networkish object\n     * @returns This instance for chaining\n     */\n    public onNetwork(network: string | Networkish) {\n        this.network = Networks.get(network)!\n        return this\n    }\n\n    /** Gets transaction options */\n    get txOptions(): TxOptions {\n        return this._txOptions;\n    }\n\n    /** Sets transaction options */\n    set txOptions(value: TxOptions) {\n        this._txOptions = value;\n    }\n\n    /** Gets the network for this transaction */\n    get network(): Networkish {\n        return this._network;\n    }\n\n    /** Sets the network for this transaction */\n    set network(value: Networkish) {\n        this._network = value;\n    }\n\n    /** Gets the builder function array */\n    get builder(): (() => Promise<any>)[] {\n        return this._builder;\n    }\n\n    /** Sets the builder function array */\n    set builder(value: (() => Promise<any>)[]) {\n        this._builder = value;\n    }\n\n    /** Gets the underlying transaction builder */\n    get transactionBuilder(): TransactionBuilder {\n        return this._transactionBuilder;\n    }\n\n    /** Sets the underlying transaction builder */\n    set transactionBuilder(value: TransactionBuilder) {\n        this._transactionBuilder = value;\n    }\n\n    /** Gets the set of token actions */\n    get tokens(): Set<TokenAction> {\n        return this._tokens;\n    }\n\n    /** Sets the set of token actions */\n    set tokens(value: Set<TokenAction>) {\n        this._tokens = value;\n    }\n\n    /** Gets the total NEXA value being sent */\n    get totalValue(): bigint {\n        return this._totalValue;\n    }\n\n    /** Sets the total NEXA value being sent */\n    set totalValue(value: bigint) {\n        this._totalValue = value;\n    }\n\n    /** Gets the set of spent outpoints */\n    get spentOutpoints(): Set<string> {\n        return this._spentOutpoints;\n    }\n\n    /**\n     * Updates the spent outpoints set with current transaction inputs\n     * @returns Set of outpoint hashes that are already spent\n     */\n    protected updateSpentOutpoints(): Set<string> {\n        this._spentOutpoints.clear();\n        for (const input of this.transactionBuilder.transaction.inputs) {\n            this._spentOutpoints.add(BufferUtils.bufferToHex(input.outpoint));\n        }\n        return this._spentOutpoints;\n    }\n\n    /**\n     * Validates and creates a token action\n     * @param toAddr Destination address\n     * @param amount Amount to send\n     * @param token Token ID\n     * @param action Action type (mint, melt, send, etc.)\n     * @param parent Optional parent token ID (for NFT/SFT minting)\n     * @throws Error if validation fails\n     */\n    protected tokenAction(toAddr: string, amount: string, token: string, action: string, parent?: string){\n        // Validate destokenActiontination address\n        if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n            throw new Error('Invalid Address.');\n        }\n\n        // Validate amount ranges\n        if ((token && BigInt(amount) < 1n) || (!token && parseInt(amount) < Transaction.DUST_AMOUNT)) {\n            throw new Error(\"The amount is too low.\");\n        }\n        if ((token && BigInt(amount) > MAX_INT64) || (!token && parseInt(amount) > Transaction.MAX_MONEY)) {\n            throw new Error(\"The amount is too high.\");\n        }\n\n        // Validate token ID\n        if (!isValidNexaAddress(token, this.network, AddressType.GroupIdAddress)) {\n            throw new Error('Invalid Token ID');\n        }\n\n        // Ensure tokens are sent to script template addresses\n        if (Address.getOutputType(toAddr) === 0) {\n            throw new Error('Token must be sent to script template address');\n        }\n\n        // For mint and melt operations, don't add output here - specialized functions will handle it\n        if (action !== 'mint' && action !== 'melt') {\n            // Add output to transaction for regular token operations (send, etc.)\n            this.transactionBuilder.to(toAddr, Transaction.DUST_AMOUNT, token, BigInt(amount))\n        }\n\n        // Record the token action\n        this.tokens.add({\n            token: token,\n            parentToken: parent,\n            amount: BigInt(amount),\n            action: action\n        })\n    }\n\n    /**\n     * Configures transaction to consolidate UTXOs to a single address\n     * @param toAddr Address to consolidate funds to\n     * @returns This instance for chaining\n     */\n    public consolidate(toAddr: string): this {\n        this.builder.push(async () => {\n            if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n                throw new Error('Invalid Address.');\n            }\n            this._txOptions.isConsolidate = true\n            this._txOptions.toChange = toAddr\n        })\n        return this\n    }\n\n    /**\n     * Configures transaction to deduct fee from the send amount\n     * @returns This instance for chaining\n     */\n    public feeFromAmount(): this{\n        this.builder.push(async () => {\n            this._txOptions.feeFromAmount = true\n        })\n        return this\n    }\n\n    /**\n     * Adds a token send operation to the transaction\n     * @param toAddr Destination address\n     * @param amount Amount of tokens to send\n     * @param token Token ID\n     * @param dustAmount Optional dust amount for the output (defaults to Transaction.DUST_AMOUNT)\n     * @returns This instance for chaining\n     */\n    public sendToToken(toAddr: string, amount: string, token: string, dustAmount: number = Transaction.DUST_AMOUNT): this {\n        this.builder.push(async () => {\n            // Validate destination address\n            if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n                throw new Error('Invalid Address.');\n            }\n\n            // Validate amount ranges\n            if (BigInt(amount) < 1n) {\n                throw new Error(\"The amount is too low.\");\n            }\n            if (BigInt(amount) > MAX_INT64) {\n                throw new Error(\"The amount is too high.\");\n            }\n\n            // Validate token ID\n            if (!isValidNexaAddress(token, this.network, AddressType.GroupIdAddress)) {\n                throw new Error('Invalid Token ID');\n            }\n\n            // Ensure tokens are sent to script template addresses\n            if (Address.getOutputType(toAddr) === 0) {\n                throw new Error('Token must be sent to script template address');\n            }\n\n            // Add output to transaction with configurable dust amount\n            this.transactionBuilder.to(toAddr, dustAmount, token, BigInt(amount))\n\n            // Record the token action\n            this.tokens.add({\n                token: token,\n                amount: BigInt(amount),\n                action: 'send'\n            })\n        })\n\n        return this;\n    }\n\n    /**\n     * Adds a NEXA send operation to the transaction\n     * @param toAddr Destination address\n     * @param amount Amount of NEXA to send\n     * @returns This instance for chaining\n     */\n    public sendTo(toAddr: string, amount: string){\n        this.builder.push(async () => {\n            if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n                throw new Error('Invalid Address.');\n            }\n            this.transactionBuilder.to(toAddr, amount);\n            this.totalValue = BigInt(this.totalValue + amount)\n        })\n        return this;\n    }\n\n    /**\n     * Adds a token authority renewal operation\n     * @param token Token ID to renew authority for\n     * @param perms Permissions to renew\n     * @param toAddr\n     * @returns This instance for chaining\n     */\n    public renewAuthority(token: string, perms: PermissionLabel[], toAddr?: string): this {\n        this.builder.push(async() => {\n            if(toAddr != null) {\n                if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n                    throw new Error('Invalid Address.');\n                }\n            }\n\n            this.tokens.add({\n                token: token,\n                action: 'renew',\n                amount: BigInt(Transaction.DUST_AMOUNT),\n                parentToken: undefined,\n                extraData: {\n                    perms: perms,\n                    address: toAddr\n                }\n            })\n        })\n        return this\n    }\n\n    /**\n     * Adds a token authority deletion operation\n     * @param token Token ID to delete authority for\n     * @param outpoint Outpoint of the authority to delete\n     * @returns This instance for chaining\n     */\n    public deleteAuthority(token:string, outpoint: string): this {\n        this.builder.push(async () => {\n            this.tokens.add({\n                token: token,\n                action: 'delete',\n                amount: BigInt(Transaction.DUST_AMOUNT),\n                parentToken: undefined,\n                extraData: {\n                    outpoint: outpoint\n                }\n            })\n        })\n        return this\n    }\n\n    /**\n     * Creates a new token group on-chain.\n     * @param type The type of group to create (TOKEN, COLLECTION, or TOKEN_V1)\n     * @param options Group configuration (name, ticker, docUrl, docHash, optional decimals)\n     * @returns This instance for chaining\n     */\n    public createGroup(type: GroupType, options: GroupOptions): this {\n        this.builder.push(async () => {\n            let opReturn: Script;\n            switch (type) {\n                case GroupType.TOKEN:\n                    opReturn = ScriptFactory.buildTokenDescription(\n                        options.ticker, options.name, options.docUrl, options.docHash, options.decimals ?? 0\n                    );\n                    break;\n                case GroupType.COLLECTION:\n                    opReturn = ScriptFactory.buildNFTCollectionDescription(\n                        options.ticker, options.name, options.docUrl, options.docHash\n                    );\n                    break;\n                case GroupType.TOKEN_V1:\n                    opReturn = ScriptFactory.buildTokenDescriptionLegacy(\n                        options.ticker, options.name, options.docUrl, options.docHash, options.decimals\n                    );\n                    break;\n            }\n            this.transactionBuilder.addData(opReturn, true)\n            this.tokens.add({\n                action: 'group',\n                amount: BigInt(Transaction.DUST_AMOUNT),\n                extraData: {\n                    opReturnData: opReturn.toHex()\n                }\n            })\n        })\n        return this\n    }\n\n    /**\n     * Creates a subgroup token under a parent group.\n     * @param type The type of subgroup to create (NFT, SFT, or GENERIC)\n     * @param options Subgroup configuration (varies by type)\n     * @returns This instance for chaining\n     */\n    public createSubgroup(type: SubgroupType, options: NftSubgroupOptions | SftSubgroupOptions | GenericSubgroupOptions): this {\n        this.builder.push(async () => {\n            let identifier: string;\n            let quantity: bigint;\n\n            switch (type) {\n                case SubgroupType.NFT: {\n                    const opts = options as NftSubgroupOptions;\n                    const opReturn = ScriptFactory.buildNFTDescription(opts.zipUrl, opts.zipHash);\n                    this.transactionBuilder.addData(opReturn, true);\n                    identifier = opts.zipHash;\n                    quantity = 1n;\n                    break;\n                }\n                case SubgroupType.SFT: {\n                    const opts = options as SftSubgroupOptions;\n                    const opReturn = ScriptFactory.buildNFTDescription(opts.zipUrl, opts.zipHash);\n                    this.transactionBuilder.addData(opReturn, true);\n                    identifier = opts.zipHash;\n                    quantity = opts.quantity;\n                    break;\n                }\n                case SubgroupType.GENERIC: {\n                    const opts = options as GenericSubgroupOptions;\n                    if (opts.opReturnData) {\n                        this.transactionBuilder.addData(opts.opReturnData, true);\n                    }\n                    identifier = opts.identifier;\n                    quantity = opts.quantity ?? 1n;\n                    break;\n                }\n            }\n\n            const subGroupBuffer = GroupToken.generateSubgroupId(options.parent, identifier);\n            const subGroupAddress = new Address(subGroupBuffer, Networks.get(this.network) || Networks.mainnet, AddressType.GroupIdAddress).toString()\n            this.tokens.add({\n                token: subGroupAddress,\n                parentToken: options.parent,\n                amount: BigInt(Transaction.DUST_AMOUNT),\n                action: 'subgroup',\n                extraData: {\n                    quantity: quantity\n                }\n            })\n        })\n        return this\n    }\n\n    /**\n     * Adds an OP_RETURN output to the transaction\n     * @param data Data to include in the OP_RETURN\n     * @param isFullScript Whether the data is already a complete script\n     * @returns This instance for chaining\n     */\n    public addOpReturn(data: Buffer | string | Script, isFullScript = false) {\n        this.builder.push(async () => {\n            let script = isFullScript ? new Script(data) : ScriptFactory.buildDataOut(data);\n            let output = new Output(0, script);\n            this.transactionBuilder.transaction.addOutput(output);\n        })\n\n        return this;\n    }\n\n    /**\n     * Adds nexa contract constraint to spending inputs\n     * @param templateScript\n     * @param constraintScript\n     * @param visibleArgs\n     * @param pubKey\n     * @returns This instance for chaining\n     */\n    public addContract(templateScript: Script, constraintScript: Script, visibleArgs: any[], pubKey?: PublicKey):this {\n        this.builder.push(async () => {\n           this.txOptions.templateData = {\n               publicKey: pubKey,\n               templateScript: templateScript,\n               constraintScript: constraintScript,\n               visibleArgs: visibleArgs\n           }\n        })\n        return this;\n    }\n\n    /** Populates the transaction with inputs and outputs - must be implemented by subclasses */\n    abstract populate(): this\n\n    /**\n     * Builds the transaction by executing all queued operations\n     * @returns Promise resolving to the serialized transaction hex\n     */\n    public async build(): Promise<string>{\n        for (const task of this.builder) {\n            await task();\n        }\n        return this.transactionBuilder.transaction.serialize(({disableAll: true}));\n    }\n\n}\n","import type {PublicKey, Script} from \"libnexa-ts\";\n\nexport type PermissionLabel = 'authorise' | 'mint' | 'melt' | 'rescript' | 'subgroup';\n\nexport enum GroupType {\n    /** NRC1 (88888890) — Fungible token with decimals */\n    TOKEN = 'TOKEN',\n    /** NRC2 (88888891) — NFT/SFT collection */\n    COLLECTION = 'COLLECTION',\n    /** Legacy (88888888) — V1 token, decimals optional */\n    TOKEN_V1 = 'TOKEN_V1',\n}\n\nexport enum SubgroupType {\n    /** NRC3 (88888892) — Unique token, qty=1 */\n    NFT = 'NFT',\n    /** NRC3 (88888892) — Semi-fungible token, qty=N */\n    SFT = 'SFT',\n    /** Generic subgroup — any identifier, works with any group type */\n    GENERIC = 'GENERIC',\n}\n\nexport interface GroupOptions {\n    name: string;\n    ticker: string;\n    docUrl: string;\n    docHash: string;\n    decimals?: number;\n}\n\nexport interface NftSubgroupOptions {\n    parent: string;\n    zipUrl: string;\n    zipHash: string;\n}\n\nexport interface SftSubgroupOptions {\n    parent: string;\n    zipUrl: string;\n    zipHash: string;\n    quantity: bigint;\n}\n\nexport interface GenericSubgroupOptions {\n    parent: string;\n    identifier: string;\n    quantity?: bigint;\n    opReturnData?: import(\"libnexa-ts\").Script;\n}\n\nexport type TxEntityState = 'incoming' | 'outgoing' | 'both'\n\nexport interface TxTemplateData {\n    templateScript: Script;\n    constraintScript: Script;\n    visibleArgs: any[];\n    publicKey?: PublicKey;\n}\n\nexport interface TxOptions {\n    isConsolidate?: boolean;\n    toChange?: string;\n    templateData?: TxTemplateData;\n    feeFromAmount?: boolean;\n}\nexport interface TokenAction {\n    token?: string\n    parentToken?: string\n    amount: bigint;\n    action: string;\n    extraData?: {\n        perms?: PermissionLabel[],\n        outpoint?: string\n        opReturnData?: string\n        address?: string\n        quantity?: bigint\n    }\n}\n\nexport interface TransactionEntity {\n    txIdem: string\n    txId: string\n    time: number\n    height: number\n    payTo: string\n    state: TxEntityState\n    value: string\n    fee: number\n    token: string\n    extraGroup: string\n    txGroupType: number\n    tokenAmount: string\n}\n","import type {BaseAccount} from \"./interfaces/BaseAccountInterface\";\nimport {\n    AccountType,\n    generateAccountKey,\n    generateKeyAndAddress, generateKeysAndAddresses,\n    getNextAccountIndex\n} from \"../../utils/WalletUtils\";\nimport type {HDPrivateKey} from \"libnexa-ts\";\nimport DAppAccount from \"./models/DappAccount\";\nimport VaultAccount from \"./models/VaultAccount\";\nimport DefaultAccount from \"./models/DefaultAccount\";\nimport type {AccountIndexes, AddressKey} from \"../../models/wallet.entities\";\n\n/**\n * AccountStore manages a collection of wallet accounts of different types.\n * It provides functionality to create, import, export, and manage accounts\n * including DApp accounts, Vault accounts, and Default NEXA accounts.\n */\nexport default class AccountStore {\n\n    /** Map storing all accounts indexed by their unique store key */\n    private readonly _accounts: Map<string, BaseAccount>\n\n    /**\n     * Creates a new AccountStore instance\n     * Initializes an empty map to store accounts\n     */\n    public constructor() {\n        this._accounts = new Map<string, BaseAccount>()\n    }\n\n    /**\n     * Generates a unique store key for an account based on its type and index\n     * @param accountType The type of account (DAPP, VAULT, or DEFAULT)\n     * @param index The account index\n     * @returns Unique string key for storing the account\n     */\n    private getAccountStoreKey(accountType: AccountType, index: number): string {\n        switch (accountType){\n            case AccountType.DAPP_ACCOUNT:\n                // DApp accounts use format: \"2.index\"\n                return String(accountType + '.' + index);\n            case AccountType.VAULT_ACCOUNT:\n                // Vault accounts use format: \"1.index\"\n                return String(accountType + '.' + index);\n            default:\n                // Default accounts use just the index\n                return String(index)\n        }\n    }\n\n    /**\n     * Creates a new account of the specified type\n     * @param accountType Type of account to create (DAPP, VAULT, or DEFAULT)\n     * @param masterKey Master HD private key for deriving account keys\n     * @param forceNextIndex If true, forces the next sequential index regardless of blockchain usage\n     * @returns Promise resolving to the created account\n     */\n    async createAccount(accountType: AccountType, masterKey: HDPrivateKey, forceNextIndex: boolean = false): Promise<BaseAccount> {\n        let nextIndex: number;\n\n        if (forceNextIndex) {\n            // Force next sequential index considering both blockchain and store\n            nextIndex = await this.getNextSequentialIndex(accountType, masterKey);\n        } else {\n            // Get the next available index for this account type (discovery-based)\n            nextIndex = await getNextAccountIndex(accountType, masterKey);\n        }\n\n        const accountStoreKey = this.getAccountStoreKey(accountType, nextIndex)\n\n        // Check if account already exists\n        const indexExists = this._accounts.get(String(accountStoreKey))\n        if(indexExists) {\n            return indexExists\n        }\n\n        switch (accountType){\n            case AccountType.DAPP_ACCOUNT:\n                // Create DApp account (purpose 2)\n                let dappAccountKey = generateAccountKey(masterKey, 2);\n                const dAppAccount = new DAppAccount(2, nextIndex, generateKeyAndAddress(dappAccountKey, nextIndex))\n                await dAppAccount.loadBalances();\n                this._accounts.set(dAppAccount.getAccountStoreKey(), dAppAccount)\n                return dAppAccount\n            case AccountType.VAULT_ACCOUNT:\n                // Create Vault account (purpose 1)\n                let vaultAccountKey = generateAccountKey(masterKey, 1);\n                const vaultAccount = new VaultAccount(1, nextIndex, generateKeyAndAddress(vaultAccountKey, nextIndex))\n                await vaultAccount.loadBalances();\n                this._accounts.set(vaultAccount.getAccountStoreKey(), vaultAccount)\n                return vaultAccount\n            default:\n                // Create default NEXA account with receive and change addresses\n                let nexaAccountKey = generateAccountKey(masterKey, nextIndex);\n                const nexaAccountIndexes: AccountIndexes = { rIndex: 0, cIndex: 0 };\n                const nexaAccount = new DefaultAccount(nextIndex, nexaAccountIndexes, generateKeysAndAddresses(nexaAccountKey, nexaAccountIndexes.rIndex + 1, nexaAccountIndexes.rIndex + 20, nexaAccountIndexes.cIndex + 1, nexaAccountIndexes.cIndex + 20), nexaAccountKey, forceNextIndex)\n                await nexaAccount.loadBalances()\n                this._accounts.set(nexaAccount.getAccountStoreKey(), nexaAccount)\n                return nexaAccount;\n        }\n    }\n\n    /**\n     * Finds the private key associated with a given address across all accounts\n     * @param address The address to search for\n     * @returns The AddressKey containing the private key, or null if not found\n     */\n    public findKeyForAddress(address: string): AddressKey | null {\n        // Search through all accounts\n        for (const [_, account] of this._accounts.entries()) {\n            // Get all addresses for this account\n            const allKeys = account.getAddresses()\n\n            // Check each key for a matching address\n            for(const key of allKeys){\n                if(key.address == address) {\n                    return key\n                }\n            }\n        }\n        return null\n    }\n\n    /**\n     * Imports an existing account into the store\n     * @param accountData The account data to import\n     * @throws Error if an account with the same key already exists\n     */\n    importAccount(accountData: BaseAccount): void {\n        let index: string = accountData.getAccountStoreKey()\n        if(this._accounts.get(index)) {\n            throw Error('Account already exists!')\n        }\n        this._accounts.set(String(index), accountData)\n    }\n\n    /**\n     * Exports account data by index\n     * @param accountIndex The account index to export\n     * @returns The account data\n     * @throws Error if the account doesn't exist\n     */\n    exportAccount(accountIndex: string): BaseAccount {\n        if(!this._accounts.get(accountIndex)) {\n            throw Error('Cannot find account!')\n        }\n\n        return this._accounts.get(accountIndex)!\n    }\n\n    /**\n     * Removes an account from the store\n     * @param accountIndex The account index to remove\n     * @throws Error if the account doesn't exist\n     */\n    removeAccount(accountIndex: string): void {\n        if(!this._accounts.get(accountIndex)) {\n            throw Error('Cannot find account!')\n        }\n        this._accounts.delete(accountIndex)\n    }\n\n    /**\n     * Returns all accounts in the store\n     * @returns Map of account store keys to BaseAccount objects\n     */\n    listAccounts(): Map<string, BaseAccount> {\n        return this._accounts\n    }\n\n    /**\n     * Retrieves a specific account by its index\n     * @param index The account index to retrieve\n     * @returns The account if found, undefined otherwise\n     */\n    getAccount(index:string): BaseAccount | undefined {\n        return this._accounts.get(index)\n    }\n\n    /**\n     * Retrieves all accounts of a specific type\n     * @param accountType The type of accounts to retrieve\n     * @returns Array of accounts matching the specified type\n     */\n    getAccountsByType(accountType: AccountType): BaseAccount[] {\n        const accounts: BaseAccount[] = [];\n        \n        for (const [key, account] of this._accounts) {\n            // Check account type based on store key pattern\n            switch (accountType) {\n                case AccountType.DAPP_ACCOUNT:\n                    // DApp accounts have keys like \"2.0\", \"2.1\", etc.\n                    if (key.startsWith('2.')) {\n                        accounts.push(account);\n                    }\n                    break;\n                case AccountType.VAULT_ACCOUNT:\n                    // Vault accounts have keys like \"1.0\", \"1.1\", etc.\n                    if (key.startsWith('1.')) {\n                        accounts.push(account);\n                    }\n                    break;\n                case AccountType.NEXA_ACCOUNT:\n                    // Default accounts have numeric keys like \"0\", \"100\", etc. (no dot)\n                    if (!key.includes('.')) {\n                        accounts.push(account);\n                    }\n                    break;\n            }\n        }\n        \n        return accounts;\n    }\n\n    /**\n     * Gets the next sequential index for an account type, considering both blockchain\n     * discovery and accounts already in the store\n     * @param accountType The account type to get the next index for\n     * @param masterKey Master HD private key for blockchain discovery\n     * @returns Promise resolving to the next safe sequential index\n     */\n    private async getNextSequentialIndex(accountType: AccountType, masterKey: HDPrivateKey): Promise<number> {\n        // First, get the discovery-based index (what exists on blockchain)\n        const discoveryIndex = await getNextAccountIndex(accountType, masterKey);\n\n        // Then, check what's the next index based on current store\n        const storeBasedIndex = this.getNextStoreIndex(accountType);\n\n        // Use whichever is higher to ensure we don't conflict with either\n        return Math.max(discoveryIndex, storeBasedIndex);\n    }\n\n    /**\n     * Gets the next index based only on accounts currently in the store\n     * @param accountType The account type to check\n     * @returns The next available index in the store\n     */\n    private getNextStoreIndex(accountType: AccountType): number {\n        const indexes: number[] = [];\n\n        for (const [key, _] of this._accounts) {\n            switch (accountType) {\n                case AccountType.DAPP_ACCOUNT:\n                    if (key.startsWith('2.')) {\n                        indexes.push(parseInt(key.split('.')[1]));\n                    }\n                    break;\n                case AccountType.VAULT_ACCOUNT:\n                    if (key.startsWith('1.')) {\n                        indexes.push(parseInt(key.split('.')[1]));\n                    }\n                    break;\n                case AccountType.NEXA_ACCOUNT:\n                    if (!key.includes('.')) {\n                        indexes.push(parseInt(key));\n                    }\n                    break;\n            }\n        }\n\n        if (indexes.length === 0) {\n            return 0; // First account of this type\n        }\n\n        // Return the next sequential index after the highest existing one\n        return Math.max(...indexes) + 1;\n    }\n}\n","import { isString } from 'lodash-es';\n\n/** Type definition for constructor functions */\ntype Class<T> = new (...args: any[]) => T; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n/**\n * Utility class for validating arguments and state conditions\n * \n * Provides methods to validate function arguments and application state\n * with consistent error handling and messaging.\n */\nexport default class ValidationUtils {\n\n    /**\n     * Validate that a state condition is true\n     * \n     * @param condition - The condition to validate\n     * @param message - Error message to throw if condition is false\n     * @throws {Error} If condition is false\n     * \n     * @example\n     * ```typescript\n     * ValidationUtils.validateState(wallet.isInitialized, 'Wallet must be initialized');\n     * ```\n     */\n    public static validateState(condition: boolean, message: string): void {\n        if (!condition) {\n            throw new Error(`Invalid State: ${message}`);\n        }\n    }\n\n    /**\n     * Validate that an argument condition is true\n     * \n     * @param condition - The condition to validate\n     * @param argumentName - Name of the argument being validated\n     * @param message - Optional additional error message\n     * @throws {Error} If condition is false\n     * \n     * @example\n     * ```typescript\n     * ValidationUtils.validateArgument(\n     *   typeof amount === 'number',\n     *   'amount',\n     *   'must be a number'\n     * );\n     * ```\n     */\n    public static validateArgument(condition: boolean, argumentName: string, message = \"\"): void {\n        if (!condition) {\n            throw new Error(`Invalid Argument: ${argumentName}. ${message}`);\n        }\n    }\n\n    /**\n     * Validate that an argument is of the expected type\n     * \n     * @param argument - The argument to validate\n     * @param type - Expected type (string name or constructor function)\n     * @param argumentName - Name of the argument being validated\n     * @throws {TypeError} If argument is not of expected type\n     * \n     * @example\n     * ```typescript\n     * ValidationUtils.validateArgumentType(buffer, 'Buffer', 'data');\n     * ValidationUtils.validateArgumentType(wallet, Wallet, 'wallet');\n     * ValidationUtils.validateArgumentType(amount, 'number', 'amount');\n     * ```\n     */\n    public static validateArgumentType<T>(argument: unknown, type: string | Class<T>, argumentName?: string): void {\n        argumentName = argumentName || '(unknown name)';\n        if (isString(type)) {\n            if (type === 'Buffer' || type === 'Uint8Array') {\n                if (!(argument instanceof Uint8Array)) {\n                    throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`);\n                }\n            } else if (typeof argument !== type) {\n                throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`);\n            }\n        } else {\n            if (!(argument instanceof type)) {\n                throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`);\n            }\n        }\n    }\n}\n","import type {Networkish} from \"libnexa-ts\";\nimport { Networks, TransactionBuilder} from \"libnexa-ts\";\nimport WatchOnlyTransactionCreator from \"./transactions/WatchOnlyTransactionCreator\";\nimport {rostrumProvider} from \"../network/RostrumProvider\";\nimport type {Balance, WatchOnlyAddress} from \"../models/wallet.entities\";\nimport {isArray, isBuffer, isNil, isObject, isString} from \"lodash-es\";\nimport ValidationUtils from \"../utils/ValidationUtils\";\nimport {isValidNexaAddress} from \"../utils/WalletUtils\";\nimport type {SubscribeCallback} from \"@vgrunner/electrum-cash\";\n\n/**\n * WatchOnlyWallet provides functionality for monitoring and creating transactions\n * for an address without storing private keys. This allows users to track balances\n * and create unsigned transactions that can be signed elsewhere.\n */\nexport default class WatchOnlyWallet {\n    /** The blockchain network this wallet operates on */\n    private readonly _network: Networkish\n    /** The address to monitor without the private key */\n    private readonly _addressToWatch: WatchOnlyAddress;\n\n    /**\n     * Creates a new WatchOnlyWallet instance\n     * @param addressToWatch The addresses to monitor\n     * @param network Optional network name (defaults to mainnet)\n     * @throws Error if validation fails\n     */\n    constructor(addressToWatch: WatchOnlyAddress, network?: string) {\n        // Validate network parameter\n        if (network !== undefined && !isString(network)) {\n            throw new Error('Network must be a string');\n        }\n\n        if (network !== undefined && isString(network)) {\n            const n = Networks.get(network)\n            if (n === undefined) {\n                throw new Error(`Invalid network: ${network}`);\n            }\n        }\n\n        this._network = Networks.get(network) ?? Networks.mainnet;\n        // Validate addressesToWatch parameter\n        this._addressToWatch = this.validateAddressToWatch(addressToWatch);\n    }\n\n    /**\n     * Validates the address to watch\n     * @param addressToWatch The address to validate\n     * @returns Validated array of WatchOnlyAddress objects\n     * @throws Error if validation fails\n     */\n    private validateAddressToWatch(addressToWatch: WatchOnlyAddress): WatchOnlyAddress {\n        if (addressToWatch === null || addressToWatch === undefined) {\n            throw new Error('addresesToWatch is required');\n        }\n\n        // Validate each address object\n        const addr = addressToWatch;\n\n        // Check if address is an object\n        if (!isObject(addr) || isArray(addr)) {\n            throw new Error(`addressToWatch must be an object`);\n        }\n\n        // Check if address property exists and is a string\n        if (!addr.hasOwnProperty('address') || !isString(addr.address)) {\n            throw new Error(`addressToWatch.address must be a string`);\n        }\n\n        // Check if address is not empty\n        if (addr.address.trim() === '') {\n            throw new Error(`addressToWatch.address cannot be empty`);\n        }\n\n        // Validate address format\n        if (!isValidNexaAddress(addr.address, this._network)) {\n            throw new Error(`addressToWatch.address is not a valid NEXA address: ${addr.address}`);\n        }\n\n        // Validate optional xPub property\n        if (addr.xPub !== undefined && !isObject(addr.xPub)) {\n            throw new Error(`addressToWatch.xPub must be a PublicKey object`);\n        }\n\n        // Validate optional derivationPath property\n        if (addr.derivationPath !== undefined && !isString(addr.derivationPath)) {\n            throw new Error(`addressToWatch.derivationPath must be a string`);\n        }\n\n        const validatedAddress = {\n            address: addr.address.trim(),\n            xPub: addr.xPub,\n            derivationPath: addr.derivationPath\n        };\n\n        return validatedAddress;\n    }\n\n    /**\n     * Creates a new transaction creator for this watch-only wallet\n     * @param x Optional transaction data - can be a TransactionBuilder, hex string, or Buffer\n     * @returns WatchOnlyTransactionCreator configured with wallet's addresses and network\n     */\n    public newTransaction(x?: TransactionBuilder | string | Buffer): WatchOnlyTransactionCreator {\n        let tx: WatchOnlyTransactionCreator;\n\n        // Handle different input types for creating transactions\n        if (x instanceof TransactionBuilder) {\n            // Use existing TransactionBuilder instance\n            tx = new WatchOnlyTransactionCreator(x);\n        } else if (isString(x)) {\n            // Parse transaction from hex string\n            tx = new WatchOnlyTransactionCreator().parseTxHex(x);\n        } else if (isBuffer(x) && !isNil(x)) {\n            // Parse transaction from buffer\n            tx = new WatchOnlyTransactionCreator().parseTxBuffer(x);\n        } else {\n            // Create new empty transaction\n            tx = new WatchOnlyTransactionCreator();\n        }\n\n        // Configure transaction with wallet's addresses and network\n        return tx.from(this._addressToWatch).onNetwork(this._network);\n    }\n\n    /**\n     * Broadcasts a signed transaction to the network\n     * @param transaction Hex-encoded signed transaction\n     * @returns Promise resolving to transaction ID\n     * @throws Error if transaction is invalid or broadcast fails\n     */\n    public async sendTransaction(transaction: string): Promise<string> {\n        ValidationUtils.validateArgument(isString(transaction), 'transaction must be present and valid')\n        return rostrumProvider.broadcast(transaction)\n    }\n\n    public async subscribeToAddressNotifications(callback: SubscribeCallback): Promise<void>{\n        await rostrumProvider.subscribeToAddresses([this._addressToWatch.address], callback)\n    }\n\n    /**\n     * Unsubscribe from address notifications to prevent memory leaks\n     *\n     * This method stops listening for notifications on the watched address.\n     * The callback parameter must be the exact same function reference that was\n     * used in the subscribeToAddressNotifications call.\n     *\n     * @param callback - The exact same callback function used in subscribeToAddressNotifications\n     *\n     * @example\n     * ```typescript\n     * const myCallback = (notification) => console.log(notification);\n     * await watchOnlyWallet.subscribeToAddressNotifications(myCallback);\n     *\n     * // Later, to prevent memory leaks:\n     * await watchOnlyWallet.unsubscribeFromAddressNotifications(myCallback);\n     * ```\n     */\n    public async unsubscribeFromAddressNotifications(callback: SubscribeCallback): Promise<void>{\n        await rostrumProvider.unsubscribeFromAddresses([this._addressToWatch.address], callback)\n    }\n\n    /**\n     * Gets the address being watched\n     * @returns The addresses being watched (copy to prevent mutation)\n     */\n    public getWatchedAddress(): WatchOnlyAddress {\n        return { ...this._addressToWatch };\n    }\n\n    /**\n     * Gets the balance for the watched address\n     * @returns Promise resolving to the balance object with confirmed and unconfirmed amounts\n     */\n    public async getBalance(): Promise<Balance> {\n        return await rostrumProvider.getBalance(this._addressToWatch.address);\n    }\n\n    /**\n     * Gets token balances for the watched address\n     * @returns Promise resolving to a record of token group IDs to balances\n     */\n    public async getTokenBalances(): Promise<Record<string, Balance>> {\n        const tokensBalance = await rostrumProvider.getTokensBalance(this._addressToWatch.address);\n        const balance: Record<string, Balance> = {};\n\n        // Get all unique token IDs from both confirmed and unconfirmed\n        const allTokenIds = new Set([\n            ...Object.keys(tokensBalance.confirmed),\n            ...Object.keys(tokensBalance.unconfirmed)\n        ]);\n\n        // Process each token to aggregate confirmed and unconfirmed balances\n        for (const tokenId of allTokenIds) {\n            const confirmedAmount = tokensBalance.confirmed[tokenId] || 0;\n            const unconfirmedAmount = tokensBalance.unconfirmed[tokenId] || 0;\n\n            // Add to balance if non-zero\n            if (confirmedAmount !== 0 || unconfirmedAmount !== 0) {\n                balance[tokenId] = {\n                    confirmed: BigInt(confirmedAmount).toString(),\n                    unconfirmed: BigInt(unconfirmedAmount).toString()\n                };\n            }\n        }\n\n        return balance;\n    }\n}\n","import {\n    AddressType,\n    TransactionBuilder,\n} from \"libnexa-ts\";\nimport type {WatchOnlyAddress} from \"../../models/wallet.entities\";\nimport type {PermissionLabel} from \"../../models/transaction.entities\";\nimport {TransactionCreator} from \"./interfaces/TransactionCreator\";\nimport {\n    watchOnlyBuildCreateGroupTransaction, watchOnlyPopulateAndDuplicateTokenAuths,\n    watchOnlyPopulateNexaInputsAndChange,\n    watchOnlyPopulateTokenAuth, watchOnlyPopulateTokenInputsAndChange, watchOnlyPopulateTokenMelt,\n    watchOnlyPopulateTokenMint, watchOnlyPopulateSendTokenAuth, watchOnlyPrepareDeleteTransaction\n} from \"../../utils/WatchOnlyTXUtils\";\nimport {isString} from \"lodash-es\";\nimport {isValidNexaAddress} from \"../../utils/WalletUtils\";\n\n/**\n * WatchOnlyTransactionCreator extends TransactionCreator to handle transaction creation\n * for watch-only wallets. It manages addresses without private keys and delegates\n * UTXO selection and input population to specialized utility functions.\n */\nexport default class WatchOnlyTransactionCreator extends TransactionCreator {\n\n\n    /** Addresses that need to be signed with (populated during transaction building) */\n    private _addressesToSignWith: string[] = [];\n    /** Available addresses for input selection and change */\n    private _availableAddresses: WatchOnlyAddress[] = []\n\n    /**\n     * Creates a new WatchOnlyTransactionCreator\n     * @param tx Optional existing transaction builder or transaction data\n     */\n    constructor(tx?: TransactionBuilder | string | Buffer) {\n        super(tx)\n    }\n\n    /**\n     * Sets the source addresses for transaction inputs\n     * @param address Single address string, array of addresses, or WatchOnlyAddress objects\n     * @returns This instance for chaining\n     */\n    public from(address: string | string[] | WatchOnlyAddress[] | WatchOnlyAddress): this {\n        if (isString(address)) {\n\n            if (!isValidNexaAddress(address, this.network) && !isValidNexaAddress(address, this.network, AddressType.PayToPublicKeyHash)) {\n                throw new Error('Invalid Address.');\n            }\n            // Single address string\n            this._availableAddresses.push({address: address});\n        } else if(Array.isArray(address)) {\n            // Array of addresses or WatchOnlyAddress objects\n            address.forEach((addr) => {\n                if (isString(addr)) {\n                    if (!isValidNexaAddress(addr, this.network) && !isValidNexaAddress(addr, this.network, AddressType.PayToPublicKeyHash)) {\n                        throw new Error('Invalid Address.');\n                    }\n                    // String address\n                    this._availableAddresses.push({address: addr});\n                } else if (addr && typeof addr === 'object' && 'address' in addr) {\n                    // WatchOnlyAddress object\n                    this._availableAddresses.push(<WatchOnlyAddress>addr);\n                }\n            })\n        } else if(address.address != null) {\n            // Single WatchOnlyAddress object\n            this._availableAddresses.push(<WatchOnlyAddress>address)\n        }\n        return this\n    }\n\n    /**\n     * Adds a token minting operation to the transaction\n     * @param token Token ID to mint\n     * @param amount Amount to mint\n     * @param toAddr Destination address for minted tokens\n     * @param parent Optional parent token ID (for NFT/SFT minting)\n     * @returns This instance for chaining\n     */\n    public mint(token: string, amount: string, toAddr:string, parent?: string): this {\n        this.builder.push(async() => {\n            this.tokenAction(toAddr, amount, token, 'mint', parent)\n        })\n\n        return this\n    }\n\n    /**\n     * Adds a token melting operation to the transaction\n     * @param token Token ID to melt\n     * @param amount Amount to melt\n     * @param toAddr Destination address for change of melted tokens\n     * @param parent Optional parent token ID (for NFT/SFT melting)\n     * @returns This instance for chaining\n     */\n    public melt(token: string, amount: string, toAddr:string, parent?: string): this {\n        this.builder.push(async() => {\n            this.tokenAction(toAddr, amount, token, 'melt', parent)\n        })\n\n        return this\n    }\n\n    public sendAuthority(token: string, perms: PermissionLabel[], toAddr: string): this {\n        this.builder.push(async() => {\n            // Validate destination address\n            if (!isValidNexaAddress(toAddr, this.network) && !isValidNexaAddress(toAddr, this.network, AddressType.PayToPublicKeyHash)) {\n                throw new Error('Invalid Address.');\n            }\n\n            const tokenAction = {\n                token: token,\n                action: 'sendAuthority',\n                amount: 0n,\n                extraData: {\n                    perms: perms,\n                    address: toAddr\n                }\n            };\n            this.tokens.add(tokenAction);\n        })\n\n        return this\n    }\n\n    /**\n     * Populates the transaction with inputs and outputs based on the configured actions.\n     * Handles different token operations (mint, melt, group creation, etc.) and\n     * populates NEXA inputs for transaction fees.\n     * @returns This instance for chaining\n     */\n    public populate(): this {\n        this.builder.push(async () => {\n            let tokenAddresses: string[] = []\n            let nexaAddresses: string[] = []\n\n            // Process token operations if any are configured\n            if(this.tokens.size > 0) {\n                for (const tokenAction of this.tokens) {\n                    if(tokenAction.action == 'mint') {\n                        // Use specialized mint function for groups and subgroups\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPopulateTokenMint(this.transactionBuilder, this._availableAddresses, tokenAction.token!, tokenAction.amount, tokenAction.parentToken, this.spentOutpoints))\n                    } else if(tokenAction.action == 'melt') {\n                        // Use specialized melt function for groups and subgroups\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPopulateTokenMelt(this.transactionBuilder, this._availableAddresses, tokenAction.token!, tokenAction.amount, tokenAction.parentToken))\n                    } else if (tokenAction.action == 'group') {\n                        // Handle group token creation\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyBuildCreateGroupTransaction(this.transactionBuilder, this._availableAddresses, tokenAction.extraData?.opReturnData!, this.network, this.spentOutpoints))\n                    } else if (tokenAction.action == 'subgroup') {\n                        // Handle subgroup token creation\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPopulateTokenAuth(this.transactionBuilder, this._availableAddresses, tokenAction.parentToken!, tokenAction.action, tokenAction.token, this._availableAddresses[0]?.address, tokenAction.extraData?.quantity, this.spentOutpoints));\n                    } else if(tokenAction.action == 'renew') {\n                        // Handle authority renewal\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPopulateAndDuplicateTokenAuths(this.transactionBuilder, this._availableAddresses, tokenAction.token!, tokenAction.extraData!.perms!, tokenAction.extraData?.address!))\n                    } else if(tokenAction.action == 'sendAuthority') {\n                        // Handle authority send/transfer\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPopulateSendTokenAuth(this.transactionBuilder, this._availableAddresses, tokenAction.token!, tokenAction.extraData!.perms!, tokenAction.extraData!.address!))\n                    } else if(tokenAction.action == 'delete') {\n                        // Handle authority deletion\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPrepareDeleteTransaction(this.transactionBuilder, this._availableAddresses, tokenAction.extraData!.outpoint!))\n                    } else {\n                        // Handle regular token transfers\n                        tokenAddresses = tokenAddresses.concat(await watchOnlyPopulateTokenInputsAndChange(this.transactionBuilder, this._availableAddresses, tokenAction.token!, tokenAction.amount))\n                    }\n\n                    // Accumulate addresses that need signing\n                    this._addressesToSignWith!.concat(tokenAddresses)\n                }\n            }\n\n            // Populate NEXA inputs for transaction fees and change\n            nexaAddresses = nexaAddresses.concat(await watchOnlyPopulateNexaInputsAndChange(this.transactionBuilder, this._availableAddresses, this.totalValue, this.txOptions))\n\n            // Combine all addresses that need signing\n            this._addressesToSignWith! = tokenAddresses.concat(nexaAddresses)\n        })\n\n        return this\n    }\n\n    /**\n     * Parse transaction from buffer (not implemented for watch-only)\n     * @param tx Transaction buffer\n     * @returns This instance for chaining\n     * @throws Error indicating method not implemented\n     */\n    public parseTxBuffer(tx: Buffer): this {\n        this.builder.push(async () => {\n            this.transactionBuilder = new TransactionBuilder(tx);\n        })\n        return this\n    }\n\n    /**\n     * Parse transaction from hex string using enhanced base class implementation\n     * @param tx Transaction hex string\n     * @returns This instance for chaining\n     */\n    public parseTxHex(tx: string): this {\n        // Call parent's parseTxHex which handles script template reconstruction\n        return super.parseTxHex(tx)\n    }\n\n    /**\n     * Handle watch-only specific logic for each parsed input (track addresses for signing)\n     */\n    protected async handleParsedInput(_input: any, utxo: any, _index: number): Promise<void> {\n        // Track addresses that will need to be signed with external wallet\n        if (utxo.addresses && utxo.addresses.length > 0) {\n            const address = utxo.addresses[0]\n            if (!this._addressesToSignWith.includes(address)) {\n                this._addressesToSignWith.push(address)\n            }\n        }\n    }\n}\n","import { rostrumProvider } from '../network/RostrumProvider';\nimport type { WatchOnlyAddress } from '../models/wallet.entities';\nimport { MAX_INT64, isNullOrEmpty } from './CommonUtils';\nimport type {\n    Networkish,\n    TransactionBuilder,\n    UTXO\n} from \"libnexa-ts\";\nimport {\n    Address,\n    AddressType,\n    BufferUtils,\n    GroupToken,\n    Transaction,\n    UnitUtils\n} from \"libnexa-ts\";\nimport type { PermissionLabel, TxOptions } from \"../models/transaction.entities\";\nimport {buildAuthority, dupAuthority, isAuthFit} from \"./TokenUtils\";\n\nconst MAX_INPUTS_OUTPUTS = 250;\n\nexport async function watchOnlyPopulateNexaInputsAndChange(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], totalTxValue: bigint, options: TxOptions): Promise<string[]> {\n    if (isNullOrEmpty(addresses)) {\n        throw new Error(\"Not enough Nexa balance.\");\n    }\n\n    let usedAddresses = new Set<string>();\n    let origAmount = options.isConsolidate ? 0 : Number(totalTxValue);\n\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getNexaUtxos(item.address);\n        for (let utxo of utxos) {\n            let input: UTXO = {\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value,\n                templateData: options.templateData\n            }\n            txBuilder.from(input);\n\n            if (!usedAddresses.has(item.address)) {\n                usedAddresses.add(item.address);\n            }\n\n            if (options.isConsolidate) {\n                // need to handle change\n                txBuilder.change(options.toChange ?? item.address);\n\n                if (txBuilder.transaction.inputs.length > MAX_INPUTS_OUTPUTS) {\n                    return Array.from(usedAddresses.values());\n                }\n            } else {\n                let tx = txBuilder.transaction;\n                if (tx.inputs.length > MAX_INPUTS_OUTPUTS) {\n                    throw new Error(\"Too many inputs. Consider consolidate transactions or reduce the send amount.\");\n                }\n\n                let unspent = tx.getUnspentValue();\n                if (unspent < 0n) {\n                    continue;\n                }\n\n                if (unspent == 0n && options.feeFromAmount) {\n                    let txFee = tx.estimateRequiredFee();\n                    tx.updateOutputAmount(0, origAmount - txFee);\n                    return Array.from(usedAddresses.values());\n                }\n\n                txBuilder.change(options.toChange ?? item.address);\n                if (options.feeFromAmount) {\n                    let hasChange = tx.getChangeOutput();\n                    let txFee = tx.estimateRequiredFee();\n                    tx.updateOutputAmount(0, origAmount - txFee);\n\n                    // edge case where change added after update\n                    if (!hasChange && tx.getChangeOutput()) {\n                        txFee = tx.estimateRequiredFee();\n                        tx.updateOutputAmount(0, origAmount - txFee);\n                    }\n                }\n\n                // check again after change output manipulation\n                if (tx.getUnspentValue() < tx.estimateRequiredFee()) {\n                    // try to add more utxos to satisfy the minimum fee\n                    continue;\n                }\n                return Array.from(usedAddresses.values());\n            }\n        }\n    }\n\n    if (options.isConsolidate) {\n        if (usedAddresses.size > 0) {\n            return Array.from(usedAddresses.values());\n        }\n        throw new Error(\"Not enough Nexa balance.\");\n    }\n\n    let err = {\n        errorMsg: \"Not enough Nexa balance.\",\n        amount: UnitUtils.formatNEXA(Number(totalTxValue)),\n        fee: UnitUtils.formatNEXA(txBuilder.transaction.estimateRequiredFee())\n    }\n\n    throw new Error(JSON.stringify(err));\n}\n\nexport async function watchOnlyPopulateTokenInputsAndChange(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], token: string, outTokenAmount: bigint): Promise<string[]> {\n    if (isNullOrEmpty(addresses)) {\n        throw new Error(\"Not enough token balance.\");\n    }\n\n    let usedKeys = new Set<string>();\n    let inTokenAmount = 0n;\n\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getTokenUtxos(item.address, token);\n        for (let utxo of utxos) {\n            if (utxo.token_amount < 0) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value,\n                groupId: utxo.group,\n                groupAmount: BigInt(utxo.token_amount),\n            });\n\n            inTokenAmount = inTokenAmount + BigInt(utxo.token_amount);\n            if (!usedKeys.has(item.address)) {\n                usedKeys.add(item.address);\n            }\n\n            if (inTokenAmount > MAX_INT64) {\n                throw new Error(\"Token inputs exceeded max amount. Consider sending in small chunks\");\n            }\n            if (txBuilder.transaction.inputs.length > MAX_INPUTS_OUTPUTS) {\n                throw new Error(\"Too many inputs. Consider consolidating transactions or reduce the send amount.\");\n            }\n\n            if (inTokenAmount == outTokenAmount) {\n                return Array.from(usedKeys.values());\n            }\n            if (inTokenAmount > outTokenAmount) {\n                // change\n                txBuilder.to(item.address, Transaction.DUST_AMOUNT, token, inTokenAmount - outTokenAmount);\n                return Array.from(usedKeys.values());\n            }\n        }\n    }\n\n    throw new Error(\"Not enough token balance\");\n}\n\nexport async function watchOnlyBuildCreateGroupTransaction(\n    txBuilder: TransactionBuilder,\n    addresses: WatchOnlyAddress[],\n    opReturnData: string,\n    network: Networkish,\n    spentOutpoints?: Set<string>\n): Promise<string[]> {\n    let outpoint = '';\n    let usedKeys: string[] = [];\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getNexaUtxos(item.address);\n        for (let utxo of utxos) {\n            // Skip if this outpoint is already spent\n            if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value\n            });\n\n            // Add to spent outpoints set\n            if (spentOutpoints) {\n                spentOutpoints.add(utxo.outpoint_hash);\n            }\n\n            if (isNullOrEmpty(outpoint) && !utxo.has_token) {\n                outpoint = utxo.outpoint_hash;\n                const opReturnBytes = BufferUtils.hexToBuffer(opReturnData);\n                let id = GroupToken.findGroupId(outpoint, opReturnBytes, GroupToken.authFlags.ACTIVE_FLAG_BITS);\n                const groupId = new Address(id.hashBuffer, network, AddressType.GroupIdAddress).toString()\n                txBuilder.to(item.address, Transaction.DUST_AMOUNT, groupId, GroupToken.authFlags.ACTIVE_FLAG_BITS | id.nonce)\n                usedKeys.push(item.address);\n                return usedKeys\n            }\n        }\n    }\n\n    throw new Error(\"Not enough Nexa balance.\");\n}\n\nexport async function watchOnlyPrepareDeleteTransaction(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], outpoint: string): Promise<string[]> {\n    let utxo = await rostrumProvider.getUtxo(outpoint);\n    let address = utxo.addresses[0];\n\n    txBuilder.from({\n        outpoint: outpoint,\n        address: address,\n        satoshis: utxo.amount\n    });\n\n    let addrKey = addresses.find(k => k.address === address);\n\n    if (!addrKey) {\n        throw new Error('UTXO associated key not found in the wallet');\n    }\n    return [addrKey.address];\n}\n\nexport async function watchOnlyPopulateTokenAuth(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], token: string, perm: PermissionLabel, subgroup = '', subgroupAddr = '', quantity?: bigint, spentOutpoints?: Set<string>): Promise<string[]> {\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getTokenUtxos(item.address, token);\n        for (let utxo of utxos) {\n            if (!isAuthFit(utxo.token_amount, perm)) {\n                continue;\n            }\n\n            // Skip if this outpoint is already spent\n            if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value\n            });\n\n            // Add to spent outpoints set\n            if (spentOutpoints) {\n                spentOutpoints.add(utxo.outpoint_hash);\n            }\n\n            if (perm === 'subgroup') {\n                const subgroupQuantity = quantity ?? dupAuthority(utxo.token_amount, false);\n                txBuilder.to(subgroupAddr, Transaction.DUST_AMOUNT, subgroup, subgroupQuantity);\n            }\n\n            // if renew flag included, we don't want to burn it\n            if (GroupToken.allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) {\n                txBuilder.to(item.address, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n            }\n\n            return [item.address];\n        }\n    }\n\n    throw new Error(\"The requested authority not found\");\n}\n\nexport async function watchOnlyPopulateTokenMint(\n    txBuilder: TransactionBuilder,\n    addresses: WatchOnlyAddress[],\n    token: string,\n    amount: bigint,\n    parentToken?: string,\n    spentOutpoints?: Set<string>\n): Promise<string[]> {\n    const usedAddresses: string[] = [];\n\n    // Determine which token to look for authority\n    const authTokenId = parentToken || token;\n\n    // Find and add mint authority\n    let mintAuthorityFound = false;\n    for (let item of addresses) {\n        if (mintAuthorityFound) break;\n\n        let authUtxos = await rostrumProvider.getTokenUtxos(item.address, authTokenId);\n        for (let utxo of authUtxos) {\n            if (!isAuthFit(utxo.token_amount, 'mint')) {\n                continue;\n            }\n\n            // Skip if already spent\n            if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n                continue;\n            }\n\n            // Add mint authority as input\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value\n            });\n\n            if (spentOutpoints) {\n                spentOutpoints.add(utxo.outpoint_hash);\n            }\n\n            // Create the minted tokens output\n            txBuilder.to(item.address, Transaction.DUST_AMOUNT, token, amount);\n\n            // Preserve the mint authority for future use if renewable\n            if (GroupToken.allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) {\n                txBuilder.to(item.address, Transaction.DUST_AMOUNT, authTokenId, dupAuthority(utxo.token_amount));\n            }\n\n            usedAddresses.push(item.address);\n            mintAuthorityFound = true;\n            break;\n        }\n    }\n\n    if (!mintAuthorityFound) {\n        throw new Error(`Mint authority not found for token ${authTokenId}`);\n    }\n\n    return usedAddresses;\n}\n\nexport async function watchOnlyPopulateTokenMelt(\n    txBuilder: TransactionBuilder,\n    addresses: WatchOnlyAddress[],\n    token: string,\n    amount: bigint,\n    parentToken?: string\n): Promise<string[]> {\n    const usedAddresses: string[] = [];\n\n    // Determine which token to look for melt authority\n    const authTokenId = parentToken || token;\n\n    // Find and add melt authority first\n    let meltAuthorityFound = false;\n    for (let item of addresses) {\n        if (meltAuthorityFound) break;\n\n        let authUtxos = await rostrumProvider.getTokenUtxos(item.address, authTokenId);\n        for (let utxo of authUtxos) {\n            if (!isAuthFit(utxo.token_amount, 'melt')) {\n                continue;\n            }\n\n            // Add melt authority as input\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value\n            });\n\n            // Preserve the melt authority for future use if renewable\n            if (GroupToken.allowsRenew(BigInt.asUintN(64, BigInt(utxo.token_amount)))) {\n                txBuilder.to(item.address, Transaction.DUST_AMOUNT, authTokenId, dupAuthority(utxo.token_amount));\n            }\n\n            usedAddresses.push(item.address);\n            meltAuthorityFound = true;\n            break;\n        }\n    }\n\n    if (!meltAuthorityFound) {\n        throw new Error(\"Melt authority not found for token\");\n    }\n\n    // Now find and add token UTXOs to melt\n    let inTokenAmount = 0n;\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getTokenUtxos(item.address, token);\n        for (let utxo of utxos) {\n            // Skip authorities (negative amounts)\n            if (utxo.token_amount < 0) {\n                continue;\n            }\n\n            // Add token UTXO as input\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value,\n                groupId: utxo.group,\n                groupAmount: BigInt(utxo.token_amount)\n            });\n\n            inTokenAmount += BigInt(utxo.token_amount);\n\n            if (!usedAddresses.includes(item.address)) {\n                usedAddresses.push(item.address);\n            }\n\n            // Check if we have enough tokens to melt\n            if (inTokenAmount >= amount) {\n                // Create change output if melting less than full amount\n                if (inTokenAmount > amount) {\n                    txBuilder.to(item.address, Transaction.DUST_AMOUNT, token, inTokenAmount - amount);\n                }\n                return usedAddresses;\n            }\n        }\n    }\n\n    throw new Error(`Not enough token balance to melt. Required: ${amount}, Available: ${inTokenAmount}`);\n}\n\n/**\n * Send token authority to another address\n *\n * This function finds and transfers a token authority UTXO that contains all the\n * specified permissions to a target address. It's used to transfer control/permissions\n * of a token to another wallet.\n *\n * @param txBuilder - The transaction builder to populate\n * @param addresses - Watch-only addresses containing token authorities\n * @param token - The token ID to find authority for\n * @param perms - Array of permission types required in the authority\n * @param toAddr - The address to send the authority to\n * @returns Promise resolving to array of addresses that need signing\n * @throws {Error} If the required authority is not found\n */\nexport async function watchOnlyPopulateSendTokenAuth(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], token: string, perms: PermissionLabel[], toAddr: string): Promise<string[]> {\n    let requiredPerms = new Set(perms);\n    requiredPerms.add('authorise');\n\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getTokenUtxos(item.address, token);\n        for (let utxo of utxos) {\n            if (utxo.token_amount > 0) {\n                continue;\n            }\n\n            // Check if this authority has all required permissions\n            let hasAllPerms = true;\n            for (let perm of requiredPerms) {\n                if (!isAuthFit(utxo.token_amount, perm)) {\n                    hasAllPerms = false;\n                    break;\n                }\n            }\n\n            if (!hasAllPerms) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value\n            });\n\n            // Send authority to target address\n            txBuilder.to(toAddr, Transaction.DUST_AMOUNT, token, BigInt(utxo.token_amount));\n\n            return [item.address];\n        }\n    }\n\n    throw new Error(`The required authority with permissions [${perms.join(', ')}] not found for token ${token}`);\n}\n\nexport async function watchOnlyPopulateAndDuplicateTokenAuths(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], token: string, perms: PermissionLabel[], toAddr?: string): Promise<string[]> {\n    let usedAddresses: string[] = [];\n\n    let reqiredPerms = new Set(perms);\n    reqiredPerms.add('authorise');\n\n    for (let item of addresses) {\n        let utxos = await rostrumProvider.getTokenUtxos(item.address, token);\n        for (let utxo of utxos) {\n            if (utxo.token_amount > 0) {\n                continue;\n            }\n\n            let found = false;\n            for (let perm of reqiredPerms) {\n                if (isAuthFit(utxo.token_amount, perm)) {\n                    reqiredPerms.delete(perm);\n                    found = true;\n                }\n            }\n\n            if (!found) {\n                continue;\n            }\n\n            txBuilder.from({\n                outpoint: utxo.outpoint_hash,\n                address: item.address,\n                satoshis: utxo.value\n            });\n            usedAddresses.push(item.address);\n\n            // duplicate existing authority back to original address\n            txBuilder.to(item.address, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n\n            if (reqiredPerms.size === 0) {\n                // create new authority with the specified permissions to target address\n                txBuilder.to(toAddr ?? item.address, Transaction.DUST_AMOUNT, token, buildAuthority(perms));\n                return usedAddresses;\n            }\n        }\n    }\n\n    throw new Error(\"The required authorities not found\");\n}\n"],"names":["Modes"],"version":3,"file":"index.mjs.map","sourceRoot":"../"}