nexa-wallet-sdk 0.5.3 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,oCAAoC,GACpC,IAAI,cAAc,AAA8B,WAAW,CAAC,QAAQ,QAAQ,IAAI;AAEhF,mCAAmC,GACnC,IAAI,aAAa,eAAe,QAA6B,UAAU,CAAC,OAAO,QAAQ,IAAI;AAE3F,4DAA4D,GAC5D,IAAI,gBAAgB,cAAc,WAAW,OAAO,KAAK;AAEzD,+BAA+B,GAC/B,IAAI,SAAS,gBAAgB,CAAA,GAAA,cAAG,EAAE,MAAM,GAAG;AAE3C,sFAAsF,GACtF,IAAI,iBAAiB,SAAS,OAAO,QAAQ,GAAG;AAEhD;;;;;;;;;;;;;;;;CAgBC,GACD,IAAI,WAAW,kBAAkB,CAAA,GAAA,cAAQ;IAEzC,2CAAe;;;;;;;;ACnCf,iCAAiC,GACjC,IAAI,iCAAW,OAAO,QAAQ,YAAY,QAAQ,KAAK,MAAM,KAAK,UAAU;AAE5E,8CAA8C,GAC9C,IAAI,6BAAO,CAAA,GAAA,cAAS,KAAK,kCAAY,SAAS;IAE9C,2CAAe;;;;;;ACRf,gDAAgD,GAChD,IAAI,mCAAa,OAAO,kBAAU,YAAY,kBAAU,eAAO,MAAM,KAAK,UAAU;IAEpF,2CAAe;;;;;;;;ACHf;;;;;;;;;;;;CAYC,GACD,SAAS;IACP,OAAO;AACT;IAEA,2CAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACjBf,aAAa;;ACAb,4BAAiB,KAAK,KAAK,CAAC;;;;;;AGErB,MAAM,2CAAgB;IACzB,IAAI;IACJ,KAAK;IACL,KAAK;IACL,SAAS;AACb;;;;ADaO,MAAM;IAIT,aAAqB,CAAC;IAEtB;;KAEC,GACD,MAAa,a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C,GACD,qBAA6C;QACzC,OAAO,IAAI,CAAC,eAAe;IAC/B;IAEA;;KAEC,GACD,aAAmB;QACf,IAAI,CAAC,QAAQ,CAAC,UAAU;QACxB,IAAI,CAAC,eAAe,GAAG;QACvB,IAAI,CAAC,sBAAsB,GAAG;IAClC;IAEA;;;;KAIC,GACD,GAAG,KAAa,EAAE,QAAkC,EAAQ;QACxD,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,OAAO;IAC5B;IAEA;;;KAGC,GACD,IAAI,KAAa,EAAQ;QACrB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;IACtB;IAEA;;;KAGC,GACD,mBAAmB,QAAoB,EAAQ;QAC3C,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC;YAC3B,IAAI,CAAC,eAAe,GAAG;YACvB,IAAI,CAAC,sBAAsB,GAAG;YAC9B;QACJ;IACJ;IAEA;;;KAGC,GACD,kBAAkB,QAAoB,EAAQ;QAC1C,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YAClB,IAAI,CAAC,eAAe,GAAG;YACvB,IAAI,CAAC,sBAAsB,GAAG;YAC9B;QACJ;IACJ;AACJ;IAEA,2CAAe;;;;;;ArCjnBf;;;;;CAKC,GACD,SAAS,mCAAa,OAAe;IACjC,IAAI,YAAY,WAAW;QACvB,IAAI,UAAU;QAGd,MAAM,IAAI,MAAM;IACpB;AACJ;AAEA,mCAAa,AAAC,eAAe,cAAc;AAC1C,eAAe,cAAc,GAAG,CAAC,CAAC,EAAE,GAAA,mCAAS;AAE9C;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,MAAM,kCAAY;kBACd;IACA,SAAS,CAAC,CAAC,EAAE,CAAA,GAAA,iCAAM,GAAG;YACtB;AACJ;IAEA,2CAAe","sources":["node_modules/lodash-es/isBuffer.js","node_modules/lodash-es/_root.js","node_modules/lodash-es/_freeGlobal.js","node_modules/lodash-es/stubFalse.js","src/index.ts","package.json","src/wallet/Wallet.ts","src/network/RostrumProvider.ts","src/models/rostrum.entities.ts","src/utils/WalletUtils.ts","node_modules/lodash-es/isNil.js","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","node_modules/lodash-es/isArray.js","node_modules/lodash-es/isString.js","node_modules/lodash-es/_baseGetTag.js","node_modules/lodash-es/_Symbol.js","node_modules/lodash-es/_getRawTag.js","node_modules/lodash-es/_objectToString.js","node_modules/lodash-es/isObjectLike.js","src/wallet/transactions/WalletTransactionCreator.ts","src/utils/TXUtils.ts","src/models/wallet.entities.ts","src/wallet/transactions/interfaces/TransactionCreator.ts","node_modules/lodash-es/parseInt.js","node_modules/lodash-es/toString.js","node_modules/lodash-es/_baseToString.js","node_modules/lodash-es/_arrayMap.js","node_modules/lodash-es/isSymbol.js","src/wallet/accounts/AccountStore.ts","src/utils/ValidationUtils.ts","src/wallet/WatchOnlyWallet.ts","src/wallet/transactions/WatchOnlyTransactionCreator.ts","src/utils/WatchOnlyTXUtils.ts","node_modules/lodash-es/isObject.js","src/comms/WalletCommsIntegration.ts","src/comms/ApprovalInterfaces.ts","src/comms/DAppCommsProvider.ts"],"sourcesContent":["import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","// @ts-ignore\nimport { version } from '../package.json';\nimport Wallet from \"./wallet/Wallet\";\n\n/**\n * Guards against multiple instances of the wallet SDK being loaded.\n * This prevents conflicts and ensures only one version is active at a time.\n * @param version - The version string to check\n * @throws {Error} When multiple instances are detected\n */\nfunction versionGuard(version: string): void {\n if (version !== undefined) {\n let message = 'More than one instance of Wallet SDK' +\n 'Please make sure to require Wallet SDK and check that submodules do' +\n ' not also include their own Wallet SDK dependency.';\n throw new Error(message);\n }\n}\n\nversionGuard((global as any)._walletSdk_ver);\n(global as any)._walletSdk_ver = `v${version}`;\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 versionGuard,\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 WalletComms integration\nexport { WalletCommsIntegration } from './comms/WalletCommsIntegration'\nexport { DAppCommsProvider } from './comms/DAppCommsProvider'\nexport type {\n ApprovalCallbacks,\n TransactionApprovalDetails,\n MessageApprovalDetails,\n SendTransactionApprovalDetails,\n NetworkSwitchApprovalDetails,\n AddTokenApprovalDetails\n} from './comms/ApprovalInterfaces'\nexport { AUTO_APPROVE_CALLBACKS } from './comms/ApprovalInterfaces'\n\n// Re-export wallet-comms-sdk types for convenience\nexport type {\n DAppInfo,\n SignMessageRequest,\n SignTransactionRequest,\n SendTransactionRequest,\n AddTokenRequest,\n SwitchNetworkRequest,\n TransactionRecipient,\n SessionDetails,\n JsonRpcErrorCode\n} from 'wallet-comms-sdk'\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 type {\n TxEntityState,\n TxTemplateData,\n TxOptions,\n TokenAction,\n PermissionLabel,\n TransactionEntity\n} from './models/transaction.entities'\n","{\n \"name\": \"nexa-wallet-sdk\",\n \"version\": \"0.5.3\",\n \"type\": \"module\",\n \"source\": \"src/index.ts\",\n \"types\": \"dist/index.d.ts\",\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.mjs\",\n \"browser\": \"dist/index.web.mjs\",\n \"exports\": {\n \"types\": \"./dist/index.d.ts\",\n \"node\": {\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.cjs\"\n },\n \"browser\": \"./dist/index.web.mjs\",\n \"default\": \"./dist/index.mjs\"\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\",\n \"docs:serve\": \"typedoc && npx serve docs -l 8080\",\n \"docs:mkdocs\": \"typedoc && mkdocs serve\",\n \"docs:build\": \"typedoc && mkdocs build\",\n \"docs:setup\": \"./scripts/setup-docs.sh\",\n \"wallet-cli\": \"node examples/wallet-cli.cjs\"\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/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\": \"commonjs\",\n \"distDir\": \"dist\",\n \"isLibrary\": true,\n \"includeNodeModules\": [\n \"lodash-es\"\n ]\n },\n \"module\": {\n \"context\": \"node\",\n \"outputFormat\": \"esmodule\",\n \"distDir\": \"dist\",\n \"isLibrary\": true\n },\n \"browser\": {\n \"context\": \"browser\",\n \"outputFormat\": \"esmodule\",\n \"distDir\": \"dist\",\n \"isLibrary\": true\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\": \"^1.0.5\",\n \"lodash-es\": \"^4.17.21\",\n \"prompt-sync\": \"^4.2.0\",\n \"wallet-comms-sdk\": \"^0.6.1\"\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 {AddressKey} from \"../models/wallet.entities\";\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)\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 * @param transaction - The signed transaction in hex format\n * @returns Promise that resolves to the transaction ID (txid)\n * @throws {Error} If the transaction is invalid or broadcast fails\n *\n * @example\n * ```typescript\n * const tx = wallet.newTransaction(account)\n * .to('nexa:address', 1000000)\n * .sign();\n *\n * const txId = await wallet.sendTransaction(tx.toHex());\n * console.log('Transaction sent:', txId);\n * ```\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 /**\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 ValidationUtils.validateArgument(!isNil(addressKey), \"You dont own this private key\")\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(): any {\n return {\n phrase: this.phrase,\n masterKey: this.masterKey,\n accounts: this._accountStore.listAccounts(),\n // accountIndexes: this.accountStore.listAccounts().keys()\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 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 */\n public async getTransactionHistory(address: string) {\n return await this.execute<ITXHistory[]>('blockchain.address.get_history', address);\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 if (e instanceof Error) {\n console.info(e.message);\n } else {\n console.error(e);\n }\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 (e) {\n console.log(e)\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 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) {\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, indexes.rIndex + 1, indexes.rIndex + 20, indexes.cIndex + 1, indexes.cIndex + 20))\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))\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) {\n let accounts: BaseAccount[] = [];\n // accounts 0, 100+\n const nexaAccounts = await discoverNexaAccounts(masterKey);\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\nasync 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 (error) {\n console.warn(`Error checking authorities for token ${tokenId} on address ${address}:`, error);\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\nasync function rescanAddressesHistory(addresses: string[]) {\n let index = 0, i = 0, minHeight = Number.MAX_SAFE_INTEGER;\n\n for (let address of addresses) {\n i++;\n let txHistory = await rostrumProvider.getTransactionHistory(address);\n if (!isNil(txHistory)) {\n index = i;\n let heights = txHistory.filter(tx => tx.height > 0).map(h => h.height);\n if (!isNil(heights)) {\n minHeight = Math.min(minHeight, ...heights);\n }\n }\n }\n\n return {index: (index > 0 ? index + 1 : 0), height: (minHeight == Number.MAX_SAFE_INTEGER ? 0 : minHeight)};\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","/**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\nfunction isNil(value) {\n return value == null;\n}\n\nexport default isNil;\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 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;\n abstract getNewAddress(): 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 sumBalance,\n sumTokensBalance\n} from \"../../../utils/WalletUtils\";\nimport type {TransactionEntity} from \"../../../models/transaction.entities\";\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\n constructor(bip44Account: number, accountIndexes: AccountIndexes, accountKeys: AccountKeys) {\n super(bip44Account)\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 if (accountIndexes.cIndex < 0) {\n throw new Error(`Can not create nexa account with an cindex of ${accountIndexes.cIndex}. must be >= 0.`);\n }\n this._accountIndexes = accountIndexes;\n this._accountKeys = accountKeys;\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 public getNewAddress() {\n return this._accountKeys.receiveKeys[this._accountKeys.receiveKeys.length - 1]?.address ?? '';\n }\n\n public getNewChangeAddress(): string {\n return this._accountKeys.changeKeys[this._accountKeys.changeKeys.length - 1]?.address ?? ''\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, 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 buffer representation of an address\n *\n * @param address - The address string (hex or Nexa address format)\n * @returns Buffer containing the address data\n *\n * @example\n * ```typescript\n * const buffer = getAddressBuffer('nexatest:nqtsq5g5jsdmqqywaqd82lhnnk3a8wqunjz6gtxdtavnnekc');\n * const hexBuffer = getAddressBuffer('a1b2c3d4e5f6');\n * ```\n */\nexport function getAddressBuffer(address: string) {\n if (CommonUtils.isHexa(address)) {\n return Buffer.from(address, 'hex') ;\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) {\n if (CommonUtils.isHexa(token)) {\n return token;\n }\n return getAddressBuffer(token).toString('hex');\n}\nexport function calcOutpointHash(txIdem: string, outputIndex: number) {\n const writer = new BufferWriter(undefined)\n const outpoint = writer.write(Buffer.from(txIdem, 'hex').reverse()).writeUInt32LE(outputIndex).toBuffer()\n return Hash.sha256(outpoint).reverse().toString('hex')\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","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","import baseGetTag from './_baseGetTag.js';\nimport isArray from './isArray.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nexport default isString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","import {\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 prepareDeleteTransaction\n} from \"../../utils/TXUtils\";\nimport type {BaseAccount} from \"../accounts/interfaces/BaseAccountInterface\";\nimport type {AddressKey} from \"../../models/wallet.entities\";\nimport {TransactionCreator} from \"./interfaces/TransactionCreator\";\n\nexport default class WalletTransactionCreator extends TransactionCreator {\n\n private _keysToSign: PrivateKey[] = [];\n private _account!: BaseAccount;\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 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 populate(): this {\n this.validateAccount();\n this.builder.push(async () => {\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, this._account.accountKeys, tokenAction.token!, tokenAction.amount, tokenAction.parentToken, this.spentOutpoints))\n } else if(tokenAction.action == 'melt') {\n tK = tK.concat(await populateTokenMelt(this.transactionBuilder, this._account.accountKeys, tokenAction.token!, tokenAction.amount, tokenAction.parentToken, this.spentOutpoints))\n } else if (tokenAction.action == 'group') {\n tK = tK.concat(await buildCreateGroupTransaction(this.transactionBuilder, this._account.accountKeys, tokenAction.extraData?.opReturnData!, this.network, this.spentOutpoints))\n } else if (tokenAction.action == 'subgroup') {\n tK = tK.concat(await populateTokenAuth(this.transactionBuilder, this._account.accountKeys, tokenAction.parentToken!, 'subgroup', tokenAction.token, this._account.accountKeys.receiveKeys.at(-1)!.address, tokenAction.extraData?.quantity, this.spentOutpoints));\n } else if(tokenAction.action == 'renew') {\n tK = tK.concat(await populateAndDuplicateTokenAuths(this.transactionBuilder, this._account.accountKeys, tokenAction.token!, tokenAction.extraData!.perms!, tokenAction.extraData!.address!, this.spentOutpoints))\n } else if(tokenAction.action == 'delete') {\n tK = tK.concat(await prepareDeleteTransaction(this.transactionBuilder, this._account.accountKeys, tokenAction.extraData!.outpoint!))\n } else {\n tK = tK.concat(await populateTokenInputsAndChange(this.transactionBuilder, this._account.accountKeys, tokenAction.token!, tokenAction.amount, this.spentOutpoints))\n }\n\n this._keysToSign!.concat(tK)\n }\n }\n\n nK = nK.concat(await populateNexaInputsAndChange(this.transactionBuilder, this._account.accountKeys, this.totalValue, this.txOptions, this.spentOutpoints))\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 console.log(`Skipping input ${inputIndex} - no placeholder found`)\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 | Opcode, 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 - Buffer to check\n * @returns true if it's a 64-byte zero placeholder\n */\n private isPlaceholder(buf: Buffer | undefined): boolean {\n if (!buf || buf.length < 64) return false;\n const placeholderBytes = Buffer.alloc(64, 0);\n return buf.subarray(0, 64).equals(placeholderBytes);\n }\n\n /**\n * Extract sighash type from placeholder buffer (bytes after the 64-byte placeholder)\n * @param buf - Buffer 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: Buffer): 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","import {rostrumProvider} from '../network/RostrumProvider';\nimport type {AccountKeys} from '../models/wallet.entities';\nimport {AccountKeysUtils} from '../models/wallet.entities';\nimport {isNullOrEmpty, MAX_INT64, tokenIdToHex} from './CommonUtils';\nimport {\n Networkish,\n PrivateKey,\n TransactionBuilder,\n UTXO\n} from \"libnexa-ts\";\nimport {\n Address,\n AddressType,\n BNExtended,\n GroupToken,\n Transaction,\n UnitUtils\n} from \"libnexa-ts\";\nimport type {PermissionLabel, TxOptions} from \"../models/transaction.entities\";\nimport {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, spentOutpoints?: Set<string>): 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 if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n continue;\n }\n\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 (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\n }\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, spentOutpoints?: Set<string>): 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 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 groupId: utxo.group,\n groupAmount: BigInt(utxo.token_amount),\n });\n\n if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\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 let id = GroupToken.findGroupId(outpoint, Buffer.from(opReturnData, 'hex'), 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 const isSubgroupMint = !!parentToken;\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 spentOutpoints?: Set<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 // Skip if already spent\n if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\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 if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\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 // Skip if already spent\n if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\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 if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\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 * 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, spentOutpoints?: Set<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 if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\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 if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\n }\n\n // duplicate\n const duplicateAddress = toAddr != null ? toAddr :\n (keys.changeKeys.length > 0 ? keys.changeKeys[keys.changeKeys.length - 1].address : keys.receiveKeys[keys.receiveKeys.length - 1].address);\n txBuilder.to(duplicateAddress, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n\n if (reqiredPerms.size === 0) {\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 tokenIdHex = output.scriptPubKey.chunks[0].buf?.toString('hex');\n if (tokenIdHex && output.scriptPubKey.chunks[1]?.buf) {\n const tokenAddress = Address.fromObject({\n data: tokenIdHex,\n network: network.toString(),\n type: AddressType.GroupIdAddress\n });\n\n if (tokenAddress !== null) {\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 }\n } catch (error) {\n console.warn('Failed to extract token data from transaction:', error);\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 {PermissionLabel, TokenAction, TxOptions} 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(input.outpoint.toString('hex'))\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: input.outpoint.toString('hex'),\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!) : Opcode.OP_FALSE\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: input.outpoint.toString('hex'),\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 console.error('parseTxHex: Error parsing transaction:', 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(input.outpoint.toString('hex'));\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 legacy token (not implemented)\n * @returns This instance for chaining\n */\n public legacyToken(name: string, ticker: string, decimals: number, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildTokenDescriptionLegacy(\n ticker,\n name,\n docUrl,\n docHash,\n decimals\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 legacy group (not implemented)\n * @returns This instance for chaining\n */\n public legacyGroup(name: string, ticker: string, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildTokenDescriptionLegacy(\n ticker,\n name,\n docUrl,\n docHash,\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 token with metadata\n * @param name Token name\n * @param ticker Token ticker symbol\n * @param decimals Number of decimal places\n * @param docUrl URL to token documentation\n * @param docHash Hash of token documentation\n * @returns This instance for chaining\n */\n public token(name: string, ticker: string, decimals: number, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildTokenDescription(\n ticker,\n name,\n docUrl,\n docHash,\n decimals\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 an NFT collection with metadata\n * @param name Collection name\n * @param ticker Collection ticker symbol\n * @param docUrl URL to collection documentation\n * @param docHash Hash of collection documentation\n * @returns This instance for chaining\n */\n public collection(name: string, ticker: string, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildNFTCollectionDescription(\n ticker,\n name,\n docUrl,\n docHash\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\n return this\n }\n\n /**\n * Creates an NFT within a collection\n * @param parent Parent collection token ID\n * @param zipUrl URL to NFT content ZIP file\n * @param zipHash Hash of NFT content ZIP file\n * @returns This instance for chaining\n */\n public nft(parent: string, zipUrl: string, zipHash: string) {\n this.builder.push(async () => {\n // add op_return for the nft\n let opReturn = ScriptFactory.buildNFTDescription(zipUrl, zipHash);\n this.transactionBuilder.addData(opReturn, true);\n // generate subgroup ID\n const subGroupBuffer = GroupToken.generateSubgroupId(parent, zipHash);\n const subGroupAddress = new Address(subGroupBuffer, Networks.get(this.network) || Networks.mainnet, AddressType.GroupIdAddress).toString()\n this.tokens.add({\n token: subGroupAddress,\n parentToken: parent,\n amount: BigInt(Transaction.DUST_AMOUNT),\n action: 'subgroup',\n extraData: {\n quantity: 1n\n }\n })\n })\n return this\n }\n\n /**\n * Creates an SFT (Semi-Fungible Token) within a collection with specified quantity\n * @param parent Parent collection token ID\n * @param zipUrl URL to SFT content ZIP file\n * @param zipHash Hash of SFT content ZIP file\n * @param quantity Quantity of SFTs to create\n * @returns This instance for chaining\n */\n public sft(parent: string, zipUrl: string, zipHash: string, quantity: bigint) {\n this.builder.push(async () => {\n // add op_return for the sft\n let opReturn = ScriptFactory.buildNFTDescription(zipUrl, zipHash);\n this.transactionBuilder.addData(opReturn, true);\n // generate subgroup ID\n const subGroupBuffer = GroupToken.generateSubgroupId(parent, zipHash)\n const subGroupAddress = new Address(subGroupBuffer, Networks.get(this.network) || Networks.mainnet, AddressType.GroupIdAddress).toString()\n this.tokens.add({\n token: subGroupAddress,\n parentToken: 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 root from './_root.js';\nimport toString from './toString.js';\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeParseInt = root.parseInt;\n\n/**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\nfunction parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n}\n\nexport default parseInt;\n","import baseToString from './_baseToString.js';\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n","import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default baseToString;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n","import type {BaseAccount} from \"./interfaces/BaseAccountInterface\";\nimport {\n AccountType,\n discoverNexaAccount,\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))\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') {\n if (!Buffer.isBuffer(argument)) {\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 {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\";\nimport {isNullOrEmpty} from \"../utils/CommonUtils\";\n\n/**\n * WatchOnlyWallet provides functionality for monitoring and creating transactions\n * for addresses 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 /** Array of addresses to monitor without their private keys */\n private readonly _addressesToWatch: WatchOnlyAddress[];\n\n /**\n * Creates a new WatchOnlyWallet instance\n * @param addressesToWatch Array of addresses to monitor\n * @param network Optional network name (defaults to mainnet)\n * @throws Error if validation fails\n */\n constructor(addressesToWatch: 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._addressesToWatch = this.validateAddressesToWatch(addressesToWatch);\n }\n\n /**\n * Validates the addresses to watch array\n * @param addressesToWatch Array of addresses to validate\n * @returns Validated array of WatchOnlyAddress objects\n * @throws Error if validation fails\n */\n private validateAddressesToWatch(addressesToWatch: WatchOnlyAddress[]): WatchOnlyAddress[] {\n if (addressesToWatch === null || addressesToWatch === undefined) {\n throw new Error('addresesToWatch is required');\n }\n \n if (!isArray(addressesToWatch)) {\n throw new Error('addressesToWatch must be an array');\n }\n\n // Check if array is not empty\n if (addressesToWatch.length === 0) {\n throw new Error('addressesToWatch cannot be empty');\n }\n\n // Validate each address object\n const validatedAddresses: WatchOnlyAddress[] = [];\n\n for (let i = 0; i < addressesToWatch.length; i++) {\n const addr = addressesToWatch[i];\n\n // Check if address is an object\n if (!isObject(addr) || isArray(addr)) {\n throw new Error(`addressesToWatch[${i}] 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(`addressesToWatch[${i}].address must be a string`);\n }\n\n // Check if address is not empty\n if (addr.address.trim() === '') {\n throw new Error(`addressesToWatch[${i}].address cannot be empty`);\n }\n\n // Validate address format\n if (!isValidNexaAddress(addr.address, this._network)) {\n throw new Error(`addressesToWatch[${i}].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(`addressesToWatch[${i}].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(`addressesToWatch[${i}].derivationPath must be a string`);\n }\n\n // Check for duplicate addresses\n const isDuplicate = validatedAddresses.some(existingAddr =>\n existingAddr.address === addr.address\n );\n if (isDuplicate) {\n throw new Error(`Duplicate address found: ${addr.address}`);\n }\n\n validatedAddresses.push({\n address: addr.address.trim(),\n xPub: addr.xPub,\n derivationPath: addr.derivationPath\n });\n }\n\n return validatedAddresses;\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._addressesToWatch).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._addressesToWatch.map(addr => addr.address), callback)\n }\n\n /**\n * Unsubscribe from address notifications to prevent memory leaks\n * \n * This method stops listening for notifications on all watched addresses.\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._addressesToWatch.map(addr => addr.address), callback)\n }\n\n /**\n * Gets the list of addresses being watched\n * @returns Array of watched addresses (copy to prevent mutation)\n */\n public getWatchedAddresses(): WatchOnlyAddress[] {\n return [...this._addressesToWatch];\n }\n}\n","import {\n AddressType,\n TransactionBuilder,\n} from \"libnexa-ts\";\nimport type {WatchOnlyAddress} from \"../../models/wallet.entities\";\nimport {TransactionCreator} from \"./interfaces/TransactionCreator\";\nimport {\n watchOnlyBuildCreateGroupTransaction, watchOnlyPopulateAndDuplicateTokenAuths,\n watchOnlyPopulateNexaInputsAndChange,\n watchOnlyPopulateTokenAuth, watchOnlyPopulateTokenInputsAndChange, watchOnlyPopulateTokenMelt,\n watchOnlyPopulateTokenMint, 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 /**\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, this.spentOutpoints))\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!, this.spentOutpoints))\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, this.spentOutpoints))\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, this.spentOutpoints))\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 GroupToken,\n Transaction,\n UnitUtils\n} from \"libnexa-ts\";\nimport type { PermissionLabel, TxOptions } from \"../models/transaction.entities\";\nimport {dupAuthority, isAuthFit} from \"./TokenUtils\";\n\nconst MAX_INPUTS_OUTPUTS = 250;\n\nexport async function watchOnlyPopulateNexaInputsAndChange(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], totalTxValue: bigint, options: TxOptions, spentOutpoints?: Set<string>): 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 // Skip if this outpoint is already spent\n if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\n continue;\n }\n\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 // Add to spent outpoints set\n if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\n }\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, spentOutpoints?: Set<string>): 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 // 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 groupId: utxo.group,\n groupAmount: BigInt(utxo.token_amount),\n });\n\n // Add to spent outpoints set\n if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\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 let id = GroupToken.findGroupId(outpoint, Buffer.from(opReturnData, 'hex'), 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 spentOutpoints?: Set<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 // Skip if already spent\n if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\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 if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\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 // Skip if already spent\n if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\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 if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\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\nexport async function watchOnlyPopulateAndDuplicateTokenAuths(txBuilder: TransactionBuilder, addresses: WatchOnlyAddress[], token: string, perms: PermissionLabel[], toAddr?: string, spentOutpoints?: Set<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 // Skip if this outpoint is already spent\n if (spentOutpoints && spentOutpoints.has(utxo.outpoint_hash)) {\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 // Add to spent outpoints set\n if (spentOutpoints) {\n spentOutpoints.add(utxo.outpoint_hash);\n }\n\n // duplicate\n txBuilder.to(toAddr != null ? toAddr : item.address, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n\n if (reqiredPerms.size === 0) {\n return usedAddresses;\n }\n }\n }\n\n throw new Error(\"The required authorities not found\");\n}\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import {\n type AddTokenRequest,\n type DAppInfo,\n DAppProvider,\n JsonRpcError,\n JsonRpcErrorCode,\n type SendTransactionRequest,\n type SignMessageRequest,\n type SignTransactionRequest,\n type SwitchNetworkRequest\n} from 'wallet-comms-sdk';\nimport type Wallet from '../wallet/Wallet';\nimport {rostrumProvider} from '../network/RostrumProvider';\nimport {Networks, Transaction, Address, AddressType, BNExtended, Networkish} from 'libnexa-ts';\nimport type {BaseAccount} from '../wallet/accounts/interfaces/BaseAccountInterface';\nimport DAppAccount from '../wallet/accounts/models/DappAccount';\nimport {AccountType} from '../utils/WalletUtils';\nimport type {\n ApprovalCallbacks,\n MessageApprovalDetails,\n SendTransactionApprovalDetails,\n TransactionApprovalDetails\n} from './ApprovalInterfaces';\nimport {AUTO_APPROVE_CALLBACKS} from './ApprovalInterfaces';\n\n/**\n * Extract all token outputs and amounts from transaction hex\n * @param txHex - Transaction hex string\n * @param network - Network to use for token address creation\n * @returns Array of token outputs with tokenId and amount\n */\nconst getTokenOutputsFromTx = (txHex: string, network: Networkish): Array<{ tokenId: string, amount: string }> => {\n const tokenOutputs: Array<{ tokenId: string, amount: string }> = []\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 tokenIdHex = output.scriptPubKey.chunks[0].buf?.toString('hex')\n if (tokenIdHex && output.scriptPubKey.chunks[1]?.buf) {\n const tokenAddress = Address.fromObject({\n data: tokenIdHex,\n network: network.toString(),\n type: AddressType.GroupIdAddress\n })\n\n if (tokenAddress !== null) {\n const tokenAddressStr = tokenAddress.toString()\n\n // Extract token amount\n const tokenAmount = BNExtended.fromScriptNumBuffer(output.scriptPubKey.chunks[1].buf, false, 8).toBigInt()\n\n tokenOutputs.push({\n tokenId: tokenAddressStr,\n amount: tokenAmount.toString()\n })\n }\n }\n }\n }\n } catch (error) {\n console.warn('Failed to extract token data from transaction:', error)\n }\n\n return tokenOutputs\n}\n\n/**\n * Wallet-side WalletComms integration for receiving and handling dApp requests\n *\n * This class runs inside wallet applications and handles incoming requests from dApps.\n * It manages session connections, message signing, transaction signing, and network switching.\n * The wallet holds private keys and can actually sign transactions.\n *\n * @example\n * ```typescript\n * const wallet = Wallet.fromSeedPhrase('...');\n * await wallet.initialize();\n *\n * const walletComms = new WalletCommsIntegration(wallet);\n *\n * // Connect to a dApp using a pairing URI (usually from QR code)\n * const dAppInfo = await walletComms.connect('wl:1@relay.net/...');\n * console.log('Connected to:', dAppInfo.name);\n *\n * // The integration automatically handles dApp requests\n * ```\n */\nexport class WalletCommsIntegration {\n private wallet: Wallet;\n private provider: DAppProvider | null = null;\n private currentAccount: BaseAccount | null = null;\n private isConnected: boolean = false;\n private approvalCallbacks: ApprovalCallbacks;\n private connectedDApp: DAppInfo | null = null;\n\n constructor(wallet: Wallet, approvalCallbacks?: ApprovalCallbacks) {\n this.wallet = wallet;\n this.approvalCallbacks = approvalCallbacks || AUTO_APPROVE_CALLBACKS;\n }\n\n /**\n * Set approval callbacks for handling user consent\n */\n setApprovalCallbacks(callbacks: ApprovalCallbacks): void {\n this.approvalCallbacks = callbacks;\n }\n\n /**\n * Connect to a dApp using a pairing URI\n *\n * This method will only use DApp accounts for security isolation.\n * If no DApp account is provided, the first available one will be used or created.\n *\n * @param pairingURI - The pairing URI from the dApp (usually from QR code)\n * @param dappAccount - Optional specific DApp account to use (defaults to first available)\n * @returns Information about the connected dApp\n */\n async connect(pairingURI: string, dappAccount?: DAppAccount): Promise<DAppInfo> {\n if (this.isConnected) {\n this.disconnect();\n }\n\n this.provider = new DAppProvider(pairingURI);\n\n // Set up request handlers\n this.setupHandlers();\n\n // Connect to the dApp\n const dAppInfo = await this.provider.connect();\n\n // Request approval for connection if callback is provided\n if (this.approvalCallbacks.approveConnection) {\n const approved = await this.approvalCallbacks.approveConnection(dAppInfo);\n if (!approved) {\n this.provider.disconnect();\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Connection rejected by user'\n );\n }\n }\n\n this.connectedDApp = dAppInfo;\n\n // Use provided DApp account or get/create one\n if (dappAccount) {\n // Validate it's actually a DApp account\n if (dappAccount.getAccountType() !== AccountType.DAPP_ACCOUNT) {\n throw new Error('Only DApp accounts can be used with WalletComms');\n }\n this.currentAccount = dappAccount;\n } else {\n this.currentAccount = await this.getOrCreateDAppAccount();\n }\n\n // Join the session with the DApp account address\n const primaryAddress = this.currentAccount.getPrimaryAddressKey();\n await this.provider.joinSession(primaryAddress.address);\n\n this.isConnected = true;\n return dAppInfo;\n }\n\n /**\n * Get an existing DApp account or create a new one\n *\n * @returns A DApp account\n */\n private async getOrCreateDAppAccount(): Promise<DAppAccount> {\n // Get all DApp accounts using the new helper method\n const dappAccounts = this.wallet.accountStore.getAccountsByType(AccountType.DAPP_ACCOUNT);\n\n // Return first existing DApp account or create a new one\n if (dappAccounts.length > 0) {\n return dappAccounts[0] as DAppAccount;\n }\n\n // No DApp accounts exist, create one\n return await this.wallet.newAccount(AccountType.DAPP_ACCOUNT) as DAppAccount;\n }\n\n /**\n * Disconnect from the current dApp session\n */\n disconnect(): void {\n if (this.provider) {\n this.provider.disconnect();\n this.provider = null;\n }\n this.isConnected = false;\n this.currentAccount = null;\n }\n\n /**\n * Set up handlers for dApp requests\n */\n private setupHandlers(): void {\n if (!this.provider) return;\n\n // Handle message signing requests\n this.provider.onSignMessage(async (request: SignMessageRequest) => {\n try {\n const account = this.getAccountByAddress(request.account);\n if (!account) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Account ${request.account} not found`\n );\n }\n\n // Request approval for message signing\n if (this.approvalCallbacks.approveMessage && this.connectedDApp) {\n const approvalDetails: MessageApprovalDetails = {\n dApp: this.connectedDApp,\n account: request.account,\n message: request.message,\n messagePreview: request.message.length > 100\n ? request.message.substring(0, 100) + '...'\n : request.message\n };\n\n const approved = await this.approvalCallbacks.approveMessage(approvalDetails);\n if (!approved) {\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Message signing rejected by user'\n );\n }\n }\n\n return this.wallet.signMessage(request.message, request.account);\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to sign message'\n );\n }\n });\n\n // Handle get account requests\n this.provider.on('wallet_getAccount', async () => {\n if (!this.currentAccount) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n 'No account selected'\n );\n }\n const primaryAddress = this.currentAccount.getPrimaryAddressKey();\n return primaryAddress.address;\n });\n\n // Handle get accounts (multiple) requests - only return DApp accounts\n this.provider.on('wallet_getAccounts', async () => {\n const dappAccounts = this.wallet.accountStore.getAccountsByType(AccountType.DAPP_ACCOUNT);\n const addresses: string[] = [];\n\n // Return addresses from all DApp accounts\n for (const account of dappAccounts) {\n const primaryAddress = account.getPrimaryAddressKey();\n addresses.push(primaryAddress.address);\n }\n\n return addresses;\n });\n\n // Handle transaction signing requests\n this.provider.on('wallet_signTransaction', async (request: SignTransactionRequest) => {\n try {\n const account = this.getAccountByAddress(request.account);\n if (!account) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Account ${request.account} not found`\n );\n }\n\n // Request approval for transaction signing\n if (this.approvalCallbacks.approveTransaction && this.connectedDApp) {\n // Parse transaction to extract readable details\n let totalAmount = 'Unknown';\n let fees = 'Unknown';\n\n try {\n const tempBuilder = this.wallet.newTransaction(account, request.hex);\n const tx = tempBuilder.transactionBuilder.build();\n\n // Calculate total NEXA amount being sent (excluding change)\n let nexaTotal = 0n;\n for (const output of tx.outputs) {\n if (output.value != BigInt(Transaction.DUST_AMOUNT)) { // Only NEXA outputs\n nexaTotal += output.value;\n }\n }\n\n // Estimate fees\n const estimatedFee = tx.estimateRequiredFee();\n\n totalAmount = nexaTotal.toString()\n fees = estimatedFee.toString()\n } catch (error) {\n // If parsing fails, keep default \"Unknown\" values\n console.warn('Failed to parse transaction for approval details:', error);\n }\n\n // Extract token outputs from transaction hex\n const tokenOutputs = getTokenOutputsFromTx(request.hex, this.wallet.network);\n\n const approvalDetails: TransactionApprovalDetails = {\n dApp: this.connectedDApp,\n account: request.account,\n transactionHex: request.hex,\n broadcast: request.broadcast || false,\n totalAmount,\n fees,\n tokenOutputs: tokenOutputs.length > 0 ? tokenOutputs : undefined\n };\n\n const approved = await this.approvalCallbacks.approveTransaction(approvalDetails);\n if (!approved) {\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Transaction signing rejected by user'\n );\n }\n }\n\n // Parse and sign the transaction\n let txBuilder = this.wallet.newTransaction(account, request.hex)\n\n txBuilder = txBuilder.sign()\n\n const tx = await txBuilder.build();\n\n // Broadcast if requested\n if (request.broadcast) {\n return await this.wallet.sendTransaction(tx); // Return just the txId string\n }\n\n return tx; // Return just the transaction hex string\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to sign transaction'\n );\n }\n });\n\n // Handle send transaction requests\n this.provider.on('wallet_sendTransaction', async (request: SendTransactionRequest) => {\n try {\n const account = this.getAccountByAddress(request.from);\n if (!account) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Account ${request.from} not found`\n );\n }\n\n // Calculate total amount\n let totalAmount = BigInt(0);\n for (const recipient of request.to) {\n if (!recipient.token) {\n totalAmount += BigInt(recipient.amount);\n }\n }\n\n // Request approval for sending transaction\n if (this.approvalCallbacks.approveSendTransaction && this.connectedDApp) {\n const approvalDetails: SendTransactionApprovalDetails = {\n dApp: this.connectedDApp,\n fromAccount: request.from,\n recipients: request.to,\n totalAmount: totalAmount.toString(),\n opReturn: request.data\n };\n\n const approved = await this.approvalCallbacks.approveSendTransaction(approvalDetails);\n if (!approved) {\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Send transaction rejected by user'\n );\n }\n }\n\n let txBuilder = this.wallet.newTransaction(account)\n .onNetwork(this.wallet.network);\n\n // Add recipients\n for (const recipient of request.to) {\n if (recipient.token) {\n txBuilder = txBuilder.sendToToken(recipient.address, recipient.amount, recipient.token)\n } else {\n txBuilder = txBuilder.sendTo(recipient.address, recipient.amount);\n }\n }\n\n // Add OP_RETURN data if provided\n if (request.data) {\n txBuilder = txBuilder.addOpReturn(request.data);\n }\n\n // Build and send the transaction\n const tx = await txBuilder\n .populate()\n .sign()\n .build();\n\n const txId = await this.wallet.sendTransaction(tx);\n return { txId, hex: tx };\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to send transaction'\n );\n }\n });\n\n // Handle network switching requests\n this.provider.on('wallet_switchNetwork', async (request: SwitchNetworkRequest) => {\n try {\n // Validate network\n const network = Networks.get(request.network);\n if (!network) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Unknown network: ${request.network}`\n );\n }\n\n // Reconnect to the new network\n await rostrumProvider.connect(request.network);\n\n return { success: true, network: request.network };\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to switch network'\n );\n }\n });\n\n // Handle add token requests\n this.provider.on('wallet_addToken', async (request: AddTokenRequest) => {\n // This would need implementation based on how tokens are tracked\n // For now, we'll acknowledge but not implement\n console.log('Add token request:', request);\n return { success: true };\n });\n\n // Handle peer disconnect\n this.provider.onPeerDisconnect(() => {\n console.log('DApp disconnected');\n this.isConnected = false;\n });\n\n // Handle connection close\n this.provider.onClose(() => {\n console.log('Connection closed');\n this.isConnected = false;\n });\n }\n\n /**\n * Get an account by its address\n */\n private getAccountByAddress(address: string): BaseAccount | null {\n const accounts = this.wallet.accountStore.listAccounts();\n\n for (const [_, account] of accounts) {\n const addresses = account.getAddresses();\n if (addresses.some(addr => addr.address === address)) {\n return account;\n }\n }\n\n return null;\n }\n\n /**\n * Switch the active account\n */\n setActiveAccount(account: BaseAccount): void {\n this.currentAccount = account;\n }\n\n /**\n * Get the current active account\n */\n getActiveAccount(): BaseAccount | null {\n return this.currentAccount;\n }\n\n /**\n * Check if connected to a dApp\n */\n isConnectedToDApp(): boolean {\n return this.isConnected;\n }\n\n /**\n * Get the current session details\n */\n getSessionInfo(): any {\n if (!this.provider) {\n return null;\n }\n return this.provider.getSessionInfo();\n }\n}\n","import type {\n SignMessageRequest,\n SignTransactionRequest,\n SendTransactionRequest,\n AddTokenRequest,\n SwitchNetworkRequest,\n DAppInfo\n} from 'wallet-comms-sdk';\n\n/**\n * Details for transaction signing approval request\n */\nexport interface TransactionApprovalDetails {\n dApp: DAppInfo;\n account: string;\n transactionHex: string;\n broadcast: boolean;\n sighashSpec?: any;\n // Parsed transaction details (if available)\n recipients?: Array<{\n address: string;\n amount: string;\n token?: string;\n }>;\n totalAmount?: string;\n fees?: string;\n opReturn?: string;\n tokenOutputs?: Array<{\n tokenId: string;\n amount: string;\n }>; // Array of token outputs with amounts\n}\n\n/**\n * Details for message signing approval request\n */\nexport interface MessageApprovalDetails {\n dApp: DAppInfo;\n account: string;\n message: string;\n messagePreview: string; // First 100 chars for display\n}\n\n/**\n * Details for send transaction approval request\n */\nexport interface SendTransactionApprovalDetails {\n dApp: DAppInfo;\n fromAccount: string;\n recipients: Array<{\n address: string;\n amount: string;\n token?: string;\n }>;\n totalAmount: string;\n estimatedFees?: string;\n opReturn?: string;\n}\n\n/**\n * Details for network switching approval request\n */\nexport interface NetworkSwitchApprovalDetails {\n dApp: DAppInfo;\n currentNetwork: string;\n requestedNetwork: string;\n}\n\n/**\n * Details for add token approval request\n */\nexport interface AddTokenApprovalDetails {\n dApp: DAppInfo;\n account: string;\n tokenId: string;\n tokenInfo?: {\n name?: string;\n symbol?: string;\n decimals?: number;\n };\n}\n\n/**\n * Approval callbacks interface for handling user approval requests\n */\nexport interface ApprovalCallbacks {\n /**\n * Request approval for transaction signing\n * @param details Transaction details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveTransaction?: (details: TransactionApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for message signing\n * @param details Message details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveMessage?: (details: MessageApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for sending a transaction\n * @param details Send transaction details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveSendTransaction?: (details: SendTransactionApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for network switching\n * @param details Network switch details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveNetworkSwitch?: (details: NetworkSwitchApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for adding a token\n * @param details Add token details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveAddToken?: (details: AddTokenApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for connecting to a dApp\n * @param dAppInfo DApp information for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveConnection?: (dAppInfo: DAppInfo) => Promise<boolean>;\n}\n\n/**\n * Default approval callbacks that auto-approve everything (for backwards compatibility)\n */\nexport const AUTO_APPROVE_CALLBACKS: ApprovalCallbacks = {\n approveTransaction: async () => true,\n approveMessage: async () => true,\n approveSendTransaction: async () => true,\n approveNetworkSwitch: async () => true,\n approveAddToken: async () => true,\n approveConnection: async () => true,\n};","import {type DAppInfo, WalletProvider} from 'wallet-comms-sdk';\nimport WatchOnlyWallet from '../wallet/WatchOnlyWallet';\nimport {rostrumProvider} from '../network/RostrumProvider';\nimport type {Networkish} from 'libnexa-ts';\n\n/**\n * DApp-side WalletComms provider that creates unsigned transactions and requests signatures\n *\n * This class runs inside dApp applications and communicates with wallet apps via WalletComms.\n * It uses WatchOnlyWallet to create unsigned transactions, then requests signatures from wallets.\n * The dApp never has access to private keys - only signed transaction results.\n *\n * @example\n * ```typescript\n * // Initialize the dApp provider\n * const dappProvider = new DAppWalletProvider(\n * 'wss://relay.nexa.org',\n * {\n * name: 'My Trading dApp',\n * url: 'https://trade.example.com',\n * description: 'Decentralized trading platform',\n * icon: 'https://trade.example.com/logo.png'\n * }\n * );\n *\n * // Connect and wait for wallet\n * await dappProvider.connect();\n * const pairingURI = dappProvider.getPairingURI();\n * // Display QR code with pairingURI\n *\n * const walletAddress = await dappProvider.waitForWallet(30000);\n * console.log('Connected to wallet:', walletAddress);\n *\n * // Send a transaction\n * const txId = await dappProvider.sendTransaction(\n * 'nexa:nqtsq5g5jsdmqqywaqd82lhnnk3a8wqunjz6gtxdtavnnekc',\n * '10000000'\n * );\n * ```\n */\nexport class DAppCommsProvider {\n private provider: WalletProvider;\n private watchOnlyWallet: WatchOnlyWallet | null = null;\n private connectedWalletAddress: string | null = null;\n private currentNetwork: Networkish | string = 'mainnet';\n\n /**\n * Creates a new DAppCommsProvider instance\n * @param relayUrl The WalletComms relay server URL\n * @param dAppInfo Information about your dApp\n * @param network Optional network (defaults to mainnet)\n */\n constructor(\n relayUrl: string,\n dAppInfo: DAppInfo,\n network: Networkish | string = 'mainnet'\n ) {\n this.provider = new WalletProvider(relayUrl, dAppInfo);\n this.currentNetwork = network;\n }\n\n /**\n * Connect to the WalletComms relay server\n * @returns Promise resolving when connected\n */\n async connect(): Promise<void> {\n await this.provider.connect();\n\n // Connect to the appropriate network\n await rostrumProvider.connect(this.currentNetwork);\n }\n\n /**\n * Get the pairing URI for QR code display\n * @returns The pairing URI string\n */\n getPairingURI(): string {\n return this.provider.getPairingURI();\n }\n\n /**\n * Wait for a wallet to connect\n * @param timeout Timeout in milliseconds (default 30000)\n * @returns Promise resolving to the wallet address\n */\n async waitForWallet(timeout: number = 30000): Promise<string> {\n try {\n // Use the built-in waitForWallet method from WalletProvider\n const walletAddress = await this.provider.waitForWallet(timeout);\n\n this.connectedWalletAddress = walletAddress;\n\n // Create WatchOnlyWallet with the connected address\n this.watchOnlyWallet = new WatchOnlyWallet([{\n address: walletAddress\n }], this.currentNetwork as string);\n\n return walletAddress;\n } catch (error) {\n throw new Error(`Failed to connect wallet: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Send NEXA to an address\n * @param toAddress Destination address\n * @param amount Amount in satoshis (as string)\n * @param opReturnData Optional OP_RETURN data\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async sendTransaction(\n toAddress: string,\n amount: string,\n opReturnData?: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create unsigned transaction using WatchOnlyWallet\n let txBuilder = this.watchOnlyWallet.newTransaction()\n .sendTo(toAddress, amount);\n\n // Add OP_RETURN data if provided\n if (opReturnData) {\n txBuilder = txBuilder.addOpReturn(opReturnData);\n }\n\n // Populate and build unsigned transaction\n const unsignedTx = await txBuilder\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Send tokens to an address\n * @param toAddress Destination address\n * @param amount Amount of tokens (as string)\n * @param tokenId Token ID\n * @param opReturnData Optional OP_RETURN data\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async sendTokenTransaction(\n toAddress: string,\n amount: string,\n tokenId: string,\n opReturnData?: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create unsigned token transaction\n let txBuilder = this.watchOnlyWallet.newTransaction()\n .sendToToken(toAddress, amount, tokenId);\n\n // Add OP_RETURN data if provided\n if (opReturnData) {\n txBuilder = txBuilder.addOpReturn(opReturnData);\n }\n\n // Populate and build unsigned transaction\n const unsignedTx = await txBuilder\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint a new token\n * @param name Token name\n * @param ticker Token ticker symbol\n * @param decimals Number of decimal places\n * @param docUrl URL to token documentation\n * @param docHash Hash of token documentation\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createToken(\n name: string,\n ticker: string,\n decimals: number,\n docUrl: string,\n docHash: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create token creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .token(name, ticker, decimals, docUrl, docHash)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint a new NFT collection\n * @param name Collection name\n * @param ticker Collection ticker symbol\n * @param docUrl URL to collection documentation\n * @param docHash Hash of collection documentation\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createCollection(\n name: string,\n ticker: string,\n docUrl: string,\n docHash: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create collection creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .collection(name, ticker, docUrl, docHash)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint an NFT within a collection\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to NFT content ZIP file\n * @param zipHash Hash of NFT content ZIP file\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createNFT(\n parentCollection: string,\n zipUrl: string,\n zipHash: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create NFT creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .nft(parentCollection, zipUrl, zipHash)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint an SFT (Semi-Fungible Token) within a collection with specified quantity\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to SFT content ZIP file\n * @param zipHash Hash of SFT content ZIP file\n * @param quantity Quantity of SFTs to create\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createSFT(\n parentCollection: string,\n zipUrl: string,\n zipHash: string,\n quantity: bigint,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create SFT creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .sft(parentCollection, zipUrl, zipHash, quantity)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Sign an arbitrary unsigned transaction\n * @param unsignedTx Unsigned transaction hex string\n * @param sighashSpec Optional sighash specification for selective signing\n * @param broadcast Whether to broadcast immediately (default false)\n * @returns Promise resolving to transaction ID (if broadcast) or signed hex\n */\n async signTransaction(\n unsignedTx: string,\n sighashSpec?: Record<number, {inFlag: number; inRange?: number; outFlag: number; outRange?: number;}>,\n broadcast: boolean = false\n ): Promise<string> {\n if (!this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Build an unsigned transaction without signing\n * @param toAddress Destination address\n * @param amount Amount in satoshis (as string)\n * @param tokenId Optional token ID for token transfers\n * @param opReturnData Optional OP_RETURN data\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildTransaction(\n toAddress: string,\n amount: string,\n tokenId?: string,\n opReturnData?: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n let txBuilder = this.watchOnlyWallet.newTransaction();\n\n if (tokenId) {\n txBuilder = txBuilder.sendToToken(toAddress, amount, tokenId);\n } else {\n txBuilder = txBuilder.sendTo(toAddress, amount);\n }\n\n if (opReturnData) {\n txBuilder = txBuilder.addOpReturn(opReturnData);\n }\n\n return await txBuilder.populate().build();\n }\n\n /**\n * Build an unsigned token creation transaction\n * @param name Token name\n * @param ticker Token ticker symbol\n * @param decimals Number of decimal places\n * @param docUrl URL to token documentation\n * @param docHash Hash of token documentation\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildTokenCreation(\n name: string,\n ticker: string,\n decimals: number,\n docUrl: string,\n docHash: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .token(name, ticker, decimals, docUrl, docHash)\n .populate()\n .build();\n }\n\n /**\n * Build an unsigned collection creation transaction\n * @param name Collection name\n * @param ticker Collection ticker symbol\n * @param docUrl URL to collection documentation\n * @param docHash Hash of collection documentation\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildCollectionCreation(\n name: string,\n ticker: string,\n docUrl: string,\n docHash: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .collection(name, ticker, docUrl, docHash)\n .populate()\n .build();\n }\n\n /**\n * Build an unsigned NFT creation transaction\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to NFT content ZIP file\n * @param zipHash Hash of NFT content ZIP file\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildNFTCreation(\n parentCollection: string,\n zipUrl: string,\n zipHash: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .nft(parentCollection, zipUrl, zipHash)\n .populate()\n .build();\n }\n\n /**\n * Build an unsigned SFT creation transaction\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to SFT content ZIP file\n * @param zipHash Hash of SFT content ZIP file\n * @param quantity Quantity of SFTs to create\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildSFTCreation(\n parentCollection: string,\n zipUrl: string,\n zipHash: string,\n quantity: bigint\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .sft(parentCollection, zipUrl, zipHash, quantity)\n .populate()\n .build();\n }\n\n /**\n * Initialize WatchOnlyWallet with multiple addresses\n * @param addresses Array of addresses to watch\n */\n initializeWatchOnly(addresses: string[]): void {\n this.watchOnlyWallet = new WatchOnlyWallet(\n addresses.map(addr => ({ address: addr })),\n this.currentNetwork as string\n );\n }\n\n /**\n * Create a custom unsigned transaction\n * @param txBuilder Function that configures the transaction builder\n * @param sighashSpec Optional sighash specification for selective signing\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createCustomTransaction(\n txBuilder: (builder: any) => any,\n sighashSpec?: Record<number, {inFlag: number; inRange?: number; outFlag: number; outRange?: number;}>,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create custom transaction using provided builder function\n const builder = this.watchOnlyWallet.newTransaction();\n\n const configuredBuilder = txBuilder(builder);\n\n const unsignedTx = await configuredBuilder\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Sign a message with the connected wallet\n * @param message Message to sign\n * @returns Promise resolving to the signature\n */\n async signMessage(message: string): Promise<string> {\n if (!this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n return await this.provider.signMessage(\n this.connectedWalletAddress,\n message\n );\n }\n\n /**\n * Switch to a different network\n * @param network Network name or identifier\n * @returns Promise resolving when network is switched\n */\n async switchNetwork(network: string): Promise<void> {\n await this.provider.switchNetwork(network);\n this.currentNetwork = network;\n\n // Reconnect rostrum provider to new network\n await rostrumProvider.connect(network);\n\n // Update watch-only wallet network if connected\n if (this.watchOnlyWallet && this.connectedWalletAddress) {\n this.watchOnlyWallet = new WatchOnlyWallet([{\n address: this.connectedWalletAddress\n }], network);\n }\n }\n\n /**\n * Get the currently connected wallet address\n * @returns Wallet address or null if not connected\n */\n getConnectedWallet(): string | null {\n return this.connectedWalletAddress;\n }\n\n /**\n * Check if a wallet is currently connected\n * @returns True if wallet is connected\n */\n isConnected(): boolean {\n return this.connectedWalletAddress !== null;\n }\n\n /**\n * Get the current network\n * @returns Current network identifier\n */\n getCurrentNetwork(): Networkish | string {\n return this.currentNetwork;\n }\n\n /**\n * Get the underlying WatchOnlyWallet instance\n * @returns WatchOnlyWallet instance or null if not connected\n */\n getWatchOnlyWallet(): WatchOnlyWallet | null {\n return this.watchOnlyWallet;\n }\n\n /**\n * Disconnect from the wallet\n */\n disconnect(): void {\n this.provider.disconnect();\n this.watchOnlyWallet = null;\n this.connectedWalletAddress = null;\n }\n\n /**\n * Set up event listeners for wallet events\n * @param event Event name\n * @param callback Event callback\n */\n on(event: string, callback: (...args: any[]) => void): void {\n this.provider.on(event, callback);\n }\n\n /**\n * Remove event listeners\n * @param event Event name\n */\n off(event: string): void {\n this.provider.off(event);\n }\n\n /**\n * Set up wallet disconnect event listener\n * @param callback Function to call when wallet disconnects\n */\n onWalletDisconnect(callback: () => void): void {\n this.provider.onPeerDisconnect(() => {\n this.watchOnlyWallet = null;\n this.connectedWalletAddress = null;\n callback();\n });\n }\n\n /**\n * Set up connection close event listener\n * @param callback Function to call when connection closes\n */\n onConnectionClose(callback: () => void): void {\n this.provider.onClose(() => {\n this.watchOnlyWallet = null;\n this.connectedWalletAddress = null;\n callback();\n });\n }\n}\n\nexport default DAppCommsProvider;\n"],"names":[],"version":3,"file":"index.cjs.map","sourceRoot":"../"}
1
+ {"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,oCAAoC,GACpC,IAAI,cAAc,AAA8B,WAAW,CAAC,QAAQ,QAAQ,IAAI;AAEhF,mCAAmC,GACnC,IAAI,aAAa,eAAe,QAA6B,UAAU,CAAC,OAAO,QAAQ,IAAI;AAE3F,4DAA4D,GAC5D,IAAI,gBAAgB,cAAc,WAAW,OAAO,KAAK;AAEzD,+BAA+B,GAC/B,IAAI,SAAS,gBAAgB,CAAA,GAAA,cAAG,EAAE,MAAM,GAAG;AAE3C,sFAAsF,GACtF,IAAI,iBAAiB,SAAS,OAAO,QAAQ,GAAG;AAEhD;;;;;;;;;;;;;;;;CAgBC,GACD,IAAI,WAAW,kBAAkB,CAAA,GAAA,cAAQ;IAEzC,2CAAe;;;;;;;;ACnCf,iCAAiC,GACjC,IAAI,iCAAW,OAAO,QAAQ,YAAY,QAAQ,KAAK,MAAM,KAAK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AS,CAAC,CAAC,EAAE,CAAA,GAAA,iCAAM,GAAG;YACtB;AACJ;IAEA,2CAAe","sources":["node_modules/lodash-es/isBuffer.js","node_modules/lodash-es/_root.js","node_modules/lodash-es/_freeGlobal.js","node_modules/lodash-es/stubFalse.js","src/index.ts","package.json","src/wallet/Wallet.ts","src/network/RostrumProvider.ts","src/models/rostrum.entities.ts","src/utils/WalletUtils.ts","node_modules/lodash-es/isNil.js","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","node_modules/lodash-es/isArray.js","node_modules/lodash-es/isString.js","node_modules/lodash-es/_baseGetTag.js","node_modules/lodash-es/_Symbol.js","node_modules/lodash-es/_getRawTag.js","node_modules/lodash-es/_objectToString.js","node_modules/lodash-es/isObjectLike.js","src/wallet/transactions/WalletTransactionCreator.ts","src/utils/TXUtils.ts","src/models/wallet.entities.ts","src/wallet/transactions/interfaces/TransactionCreator.ts","node_modules/lodash-es/parseInt.js","node_modules/lodash-es/toString.js","node_modules/lodash-es/_baseToString.js","node_modules/lodash-es/_arrayMap.js","node_modules/lodash-es/isSymbol.js","src/wallet/accounts/AccountStore.ts","src/utils/ValidationUtils.ts","src/wallet/WatchOnlyWallet.ts","src/wallet/transactions/WatchOnlyTransactionCreator.ts","src/utils/WatchOnlyTXUtils.ts","node_modules/lodash-es/isObject.js","src/comms/WalletCommsIntegration.ts","src/comms/ApprovalInterfaces.ts","src/comms/DAppCommsProvider.ts"],"sourcesContent":["import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n","import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n","// @ts-ignore\nimport { version } from '../package.json';\nimport Wallet from \"./wallet/Wallet\";\n\n/**\n * Guards against multiple instances of the wallet SDK being loaded.\n * This prevents conflicts and ensures only one version is active at a time.\n * @param version - The version string to check\n * @throws {Error} When multiple instances are detected\n */\nfunction versionGuard(version: string): void {\n if (version !== undefined) {\n let message = 'More than one instance of Wallet SDK' +\n 'Please make sure to require Wallet SDK and check that submodules do' +\n ' not also include their own Wallet SDK dependency.';\n throw new Error(message);\n }\n}\n\nversionGuard((global as any)._walletSdk_ver);\n(global as any)._walletSdk_ver = `v${version}`;\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 versionGuard,\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 WalletComms integration\nexport { WalletCommsIntegration } from './comms/WalletCommsIntegration'\nexport { DAppCommsProvider } from './comms/DAppCommsProvider'\nexport type {\n ApprovalCallbacks,\n TransactionApprovalDetails,\n MessageApprovalDetails,\n SendTransactionApprovalDetails,\n NetworkSwitchApprovalDetails,\n AddTokenApprovalDetails\n} from './comms/ApprovalInterfaces'\nexport { AUTO_APPROVE_CALLBACKS } from './comms/ApprovalInterfaces'\n\n// Re-export wallet-comms-sdk types for convenience\nexport type {\n DAppInfo,\n SignMessageRequest,\n SignTransactionRequest,\n SendTransactionRequest,\n AddTokenRequest,\n SwitchNetworkRequest,\n TransactionRecipient,\n SessionDetails,\n JsonRpcErrorCode\n} from 'wallet-comms-sdk'\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 type {\n TxEntityState,\n TxTemplateData,\n TxOptions,\n TokenAction,\n PermissionLabel,\n TransactionEntity\n} from './models/transaction.entities'\n","{\n \"name\": \"nexa-wallet-sdk\",\n \"version\": \"0.5.4\",\n \"type\": \"module\",\n \"source\": \"src/index.ts\",\n \"types\": \"dist/index.d.ts\",\n \"main\": \"dist/index.cjs\",\n \"module\": \"dist/index.mjs\",\n \"browser\": \"dist/index.web.mjs\",\n \"exports\": {\n \"types\": \"./dist/index.d.ts\",\n \"node\": {\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.cjs\"\n },\n \"browser\": \"./dist/index.web.mjs\",\n \"default\": \"./dist/index.mjs\"\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\",\n \"docs:serve\": \"typedoc && npx serve docs -l 8080\",\n \"docs:mkdocs\": \"typedoc && mkdocs serve\",\n \"docs:build\": \"typedoc && mkdocs build\",\n \"docs:setup\": \"./scripts/setup-docs.sh\",\n \"wallet-cli\": \"node examples/wallet-cli.cjs\"\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/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\": \"commonjs\",\n \"distDir\": \"dist\",\n \"isLibrary\": true,\n \"includeNodeModules\": [\n \"lodash-es\"\n ]\n },\n \"module\": {\n \"context\": \"node\",\n \"outputFormat\": \"esmodule\",\n \"distDir\": \"dist\",\n \"isLibrary\": true\n },\n \"browser\": {\n \"context\": \"browser\",\n \"outputFormat\": \"esmodule\",\n \"distDir\": \"dist\",\n \"isLibrary\": true\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\": \"^1.0.5\",\n \"lodash-es\": \"^4.17.21\",\n \"prompt-sync\": \"^4.2.0\",\n \"wallet-comms-sdk\": \"^0.6.1\"\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 {AddressKey} from \"../models/wallet.entities\";\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)\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 * @param transaction - The signed transaction in hex format\n * @returns Promise that resolves to the transaction ID (txid)\n * @throws {Error} If the transaction is invalid or broadcast fails\n *\n * @example\n * ```typescript\n * const tx = wallet.newTransaction(account)\n * .to('nexa:address', 1000000)\n * .sign();\n *\n * const txId = await wallet.sendTransaction(tx.toHex());\n * console.log('Transaction sent:', txId);\n * ```\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 /**\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 ValidationUtils.validateArgument(!isNil(addressKey), \"You dont own this private key\")\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(): any {\n return {\n phrase: this.phrase,\n masterKey: this.masterKey,\n accounts: this._accountStore.listAccounts(),\n // accountIndexes: this.accountStore.listAccounts().keys()\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 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 */\n public async getTransactionHistory(address: string) {\n return await this.execute<ITXHistory[]>('blockchain.address.get_history', address);\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 if (e instanceof Error) {\n console.info(e.message);\n } else {\n console.error(e);\n }\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 (e) {\n console.log(e)\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 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) {\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, indexes.rIndex + 1, indexes.rIndex + 20, indexes.cIndex + 1, indexes.cIndex + 20))\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))\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) {\n let accounts: BaseAccount[] = [];\n // accounts 0, 100+\n const nexaAccounts = await discoverNexaAccounts(masterKey);\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\nasync 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 (error) {\n console.warn(`Error checking authorities for token ${tokenId} on address ${address}:`, error);\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\nasync function rescanAddressesHistory(addresses: string[]) {\n let index = 0, i = 0, minHeight = Number.MAX_SAFE_INTEGER;\n\n for (let address of addresses) {\n i++;\n let txHistory = await rostrumProvider.getTransactionHistory(address);\n if (!isNil(txHistory)) {\n index = i;\n let heights = txHistory.filter(tx => tx.height > 0).map(h => h.height);\n if (!isNil(heights)) {\n minHeight = Math.min(minHeight, ...heights);\n }\n }\n }\n\n return {index: (index > 0 ? index + 1 : 0), height: (minHeight == Number.MAX_SAFE_INTEGER ? 0 : minHeight)};\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","/**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\nfunction isNil(value) {\n return value == null;\n}\n\nexport default isNil;\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 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;\n abstract getNewAddress(): 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 sumBalance,\n sumTokensBalance\n} from \"../../../utils/WalletUtils\";\nimport type {TransactionEntity} from \"../../../models/transaction.entities\";\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\n constructor(bip44Account: number, accountIndexes: AccountIndexes, accountKeys: AccountKeys) {\n super(bip44Account)\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 if (accountIndexes.cIndex < 0) {\n throw new Error(`Can not create nexa account with an cindex of ${accountIndexes.cIndex}. must be >= 0.`);\n }\n this._accountIndexes = accountIndexes;\n this._accountKeys = accountKeys;\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 public getNewAddress() {\n return this._accountKeys.receiveKeys[this._accountKeys.receiveKeys.length - 1]?.address ?? '';\n }\n\n public getNewChangeAddress(): string {\n return this._accountKeys.changeKeys[this._accountKeys.changeKeys.length - 1]?.address ?? ''\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, 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 buffer representation of an address\n *\n * @param address - The address string (hex or Nexa address format)\n * @returns Buffer containing the address data\n *\n * @example\n * ```typescript\n * const buffer = getAddressBuffer('nexatest:nqtsq5g5jsdmqqywaqd82lhnnk3a8wqunjz6gtxdtavnnekc');\n * const hexBuffer = getAddressBuffer('a1b2c3d4e5f6');\n * ```\n */\nexport function getAddressBuffer(address: string) {\n if (CommonUtils.isHexa(address)) {\n return Buffer.from(address, 'hex') ;\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) {\n if (CommonUtils.isHexa(token)) {\n return token;\n }\n return getAddressBuffer(token).toString('hex');\n}\nexport function calcOutpointHash(txIdem: string, outputIndex: number) {\n const writer = new BufferWriter(undefined)\n const outpoint = writer.write(Buffer.from(txIdem, 'hex').reverse()).writeUInt32LE(outputIndex).toBuffer()\n return Hash.sha256(outpoint).reverse().toString('hex')\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","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n","import baseGetTag from './_baseGetTag.js';\nimport isArray from './isArray.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nexport default isString;\n","import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n","import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n","import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n","import {\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 prepareDeleteTransaction\n} from \"../../utils/TXUtils\";\nimport type {BaseAccount} from \"../accounts/interfaces/BaseAccountInterface\";\nimport type {AddressKey} from \"../../models/wallet.entities\";\nimport {TransactionCreator} from \"./interfaces/TransactionCreator\";\n\nexport default class WalletTransactionCreator extends TransactionCreator {\n\n private _keysToSign: PrivateKey[] = [];\n private _account!: BaseAccount;\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 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 populate(): this {\n this.validateAccount();\n this.builder.push(async () => {\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, this._account.accountKeys, tokenAction.token!, tokenAction.amount, tokenAction.parentToken, this.spentOutpoints))\n } else if(tokenAction.action == 'melt') {\n tK = tK.concat(await populateTokenMelt(this.transactionBuilder, this._account.accountKeys, tokenAction.token!, tokenAction.amount, tokenAction.parentToken))\n } else if (tokenAction.action == 'group') {\n tK = tK.concat(await buildCreateGroupTransaction(this.transactionBuilder, this._account.accountKeys, tokenAction.extraData?.opReturnData!, this.network, this.spentOutpoints))\n } else if (tokenAction.action == 'subgroup') {\n tK = tK.concat(await populateTokenAuth(this.transactionBuilder, this._account.accountKeys, tokenAction.parentToken!, 'subgroup', tokenAction.token, this._account.accountKeys.receiveKeys.at(-1)!.address, tokenAction.extraData?.quantity, this.spentOutpoints));\n } else if(tokenAction.action == 'renew') {\n tK = tK.concat(await populateAndDuplicateTokenAuths(this.transactionBuilder, this._account.accountKeys, tokenAction.token!, tokenAction.extraData!.perms!, tokenAction.extraData!.address!))\n } else if(tokenAction.action == 'delete') {\n tK = tK.concat(await prepareDeleteTransaction(this.transactionBuilder, this._account.accountKeys, tokenAction.extraData!.outpoint!))\n } else {\n tK = tK.concat(await populateTokenInputsAndChange(this.transactionBuilder, this._account.accountKeys, tokenAction.token!, tokenAction.amount))\n }\n\n this._keysToSign!.concat(tK)\n }\n }\n\n nK = nK.concat(await populateNexaInputsAndChange(this.transactionBuilder, this._account.accountKeys, 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 console.log(`Skipping input ${inputIndex} - no placeholder found`)\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 | Opcode, 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 - Buffer to check\n * @returns true if it's a 64-byte zero placeholder\n */\n private isPlaceholder(buf: Buffer | undefined): boolean {\n if (!buf || buf.length < 64) return false;\n const placeholderBytes = Buffer.alloc(64, 0);\n return buf.subarray(0, 64).equals(placeholderBytes);\n }\n\n /**\n * Extract sighash type from placeholder buffer (bytes after the 64-byte placeholder)\n * @param buf - Buffer 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: Buffer): 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","import {rostrumProvider} from '../network/RostrumProvider';\nimport type {AccountKeys} from '../models/wallet.entities';\nimport {AccountKeysUtils} from '../models/wallet.entities';\nimport {isNullOrEmpty, MAX_INT64, tokenIdToHex} from './CommonUtils';\nimport {\n Networkish,\n PrivateKey,\n TransactionBuilder,\n UTXO\n} from \"libnexa-ts\";\nimport {\n Address,\n AddressType,\n BNExtended,\n GroupToken,\n Transaction,\n UnitUtils\n} from \"libnexa-ts\";\nimport type {PermissionLabel, TxOptions} from \"../models/transaction.entities\";\nimport {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 let id = GroupToken.findGroupId(outpoint, Buffer.from(opReturnData, 'hex'), 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 const isSubgroupMint = !!parentToken;\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 * 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 // duplicate\n const duplicateAddress = toAddr != null ? toAddr :\n (keys.changeKeys.length > 0 ? keys.changeKeys[keys.changeKeys.length - 1].address : keys.receiveKeys[keys.receiveKeys.length - 1].address);\n txBuilder.to(duplicateAddress, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n\n if (reqiredPerms.size === 0) {\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 tokenIdHex = output.scriptPubKey.chunks[0].buf?.toString('hex');\n if (tokenIdHex && output.scriptPubKey.chunks[1]?.buf) {\n const tokenAddress = Address.fromObject({\n data: tokenIdHex,\n network: network.toString(),\n type: AddressType.GroupIdAddress\n });\n\n if (tokenAddress !== null) {\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 }\n } catch (error) {\n console.warn('Failed to extract token data from transaction:', error);\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 {PermissionLabel, TokenAction, TxOptions} 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(input.outpoint.toString('hex'))\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: input.outpoint.toString('hex'),\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!) : Opcode.OP_FALSE\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: input.outpoint.toString('hex'),\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 console.error('parseTxHex: Error parsing transaction:', 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(input.outpoint.toString('hex'));\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 legacy token (not implemented)\n * @returns This instance for chaining\n */\n public legacyToken(name: string, ticker: string, decimals: number, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildTokenDescriptionLegacy(\n ticker,\n name,\n docUrl,\n docHash,\n decimals\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 legacy group (not implemented)\n * @returns This instance for chaining\n */\n public legacyGroup(name: string, ticker: string, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildTokenDescriptionLegacy(\n ticker,\n name,\n docUrl,\n docHash,\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 token with metadata\n * @param name Token name\n * @param ticker Token ticker symbol\n * @param decimals Number of decimal places\n * @param docUrl URL to token documentation\n * @param docHash Hash of token documentation\n * @returns This instance for chaining\n */\n public token(name: string, ticker: string, decimals: number, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildTokenDescription(\n ticker,\n name,\n docUrl,\n docHash,\n decimals\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 an NFT collection with metadata\n * @param name Collection name\n * @param ticker Collection ticker symbol\n * @param docUrl URL to collection documentation\n * @param docHash Hash of collection documentation\n * @returns This instance for chaining\n */\n public collection(name: string, ticker: string, docUrl: string, docHash: string): this {\n this.builder.push(async () => {\n const opReturn = ScriptFactory.buildNFTCollectionDescription(\n ticker,\n name,\n docUrl,\n docHash\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\n return this\n }\n\n /**\n * Creates an NFT within a collection\n * @param parent Parent collection token ID\n * @param zipUrl URL to NFT content ZIP file\n * @param zipHash Hash of NFT content ZIP file\n * @returns This instance for chaining\n */\n public nft(parent: string, zipUrl: string, zipHash: string) {\n this.builder.push(async () => {\n // add op_return for the nft\n let opReturn = ScriptFactory.buildNFTDescription(zipUrl, zipHash);\n this.transactionBuilder.addData(opReturn, true);\n // generate subgroup ID\n const subGroupBuffer = GroupToken.generateSubgroupId(parent, zipHash);\n const subGroupAddress = new Address(subGroupBuffer, Networks.get(this.network) || Networks.mainnet, AddressType.GroupIdAddress).toString()\n this.tokens.add({\n token: subGroupAddress,\n parentToken: parent,\n amount: BigInt(Transaction.DUST_AMOUNT),\n action: 'subgroup',\n extraData: {\n quantity: 1n\n }\n })\n })\n return this\n }\n\n /**\n * Creates an SFT (Semi-Fungible Token) within a collection with specified quantity\n * @param parent Parent collection token ID\n * @param zipUrl URL to SFT content ZIP file\n * @param zipHash Hash of SFT content ZIP file\n * @param quantity Quantity of SFTs to create\n * @returns This instance for chaining\n */\n public sft(parent: string, zipUrl: string, zipHash: string, quantity: bigint) {\n this.builder.push(async () => {\n // add op_return for the sft\n let opReturn = ScriptFactory.buildNFTDescription(zipUrl, zipHash);\n this.transactionBuilder.addData(opReturn, true);\n // generate subgroup ID\n const subGroupBuffer = GroupToken.generateSubgroupId(parent, zipHash)\n const subGroupAddress = new Address(subGroupBuffer, Networks.get(this.network) || Networks.mainnet, AddressType.GroupIdAddress).toString()\n this.tokens.add({\n token: subGroupAddress,\n parentToken: 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 root from './_root.js';\nimport toString from './toString.js';\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeParseInt = root.parseInt;\n\n/**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\nfunction parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n}\n\nexport default parseInt;\n","import baseToString from './_baseToString.js';\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n","import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default baseToString;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n","import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n","import type {BaseAccount} from \"./interfaces/BaseAccountInterface\";\nimport {\n AccountType,\n discoverNexaAccount,\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))\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') {\n if (!Buffer.isBuffer(argument)) {\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 {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\";\nimport {isNullOrEmpty} from \"../utils/CommonUtils\";\n\n/**\n * WatchOnlyWallet provides functionality for monitoring and creating transactions\n * for addresses 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 /** Array of addresses to monitor without their private keys */\n private readonly _addressesToWatch: WatchOnlyAddress[];\n\n /**\n * Creates a new WatchOnlyWallet instance\n * @param addressesToWatch Array of addresses to monitor\n * @param network Optional network name (defaults to mainnet)\n * @throws Error if validation fails\n */\n constructor(addressesToWatch: 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._addressesToWatch = this.validateAddressesToWatch(addressesToWatch);\n }\n\n /**\n * Validates the addresses to watch array\n * @param addressesToWatch Array of addresses to validate\n * @returns Validated array of WatchOnlyAddress objects\n * @throws Error if validation fails\n */\n private validateAddressesToWatch(addressesToWatch: WatchOnlyAddress[]): WatchOnlyAddress[] {\n if (addressesToWatch === null || addressesToWatch === undefined) {\n throw new Error('addresesToWatch is required');\n }\n \n if (!isArray(addressesToWatch)) {\n throw new Error('addressesToWatch must be an array');\n }\n\n // Check if array is not empty\n if (addressesToWatch.length === 0) {\n throw new Error('addressesToWatch cannot be empty');\n }\n\n // Validate each address object\n const validatedAddresses: WatchOnlyAddress[] = [];\n\n for (let i = 0; i < addressesToWatch.length; i++) {\n const addr = addressesToWatch[i];\n\n // Check if address is an object\n if (!isObject(addr) || isArray(addr)) {\n throw new Error(`addressesToWatch[${i}] 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(`addressesToWatch[${i}].address must be a string`);\n }\n\n // Check if address is not empty\n if (addr.address.trim() === '') {\n throw new Error(`addressesToWatch[${i}].address cannot be empty`);\n }\n\n // Validate address format\n if (!isValidNexaAddress(addr.address, this._network)) {\n throw new Error(`addressesToWatch[${i}].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(`addressesToWatch[${i}].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(`addressesToWatch[${i}].derivationPath must be a string`);\n }\n\n // Check for duplicate addresses\n const isDuplicate = validatedAddresses.some(existingAddr =>\n existingAddr.address === addr.address\n );\n if (isDuplicate) {\n throw new Error(`Duplicate address found: ${addr.address}`);\n }\n\n validatedAddresses.push({\n address: addr.address.trim(),\n xPub: addr.xPub,\n derivationPath: addr.derivationPath\n });\n }\n\n return validatedAddresses;\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._addressesToWatch).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._addressesToWatch.map(addr => addr.address), callback)\n }\n\n /**\n * Unsubscribe from address notifications to prevent memory leaks\n * \n * This method stops listening for notifications on all watched addresses.\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._addressesToWatch.map(addr => addr.address), callback)\n }\n\n /**\n * Gets the list of addresses being watched\n * @returns Array of watched addresses (copy to prevent mutation)\n */\n public getWatchedAddresses(): WatchOnlyAddress[] {\n return [...this._addressesToWatch];\n }\n}\n","import {\n AddressType,\n TransactionBuilder,\n} from \"libnexa-ts\";\nimport type {WatchOnlyAddress} from \"../../models/wallet.entities\";\nimport {TransactionCreator} from \"./interfaces/TransactionCreator\";\nimport {\n watchOnlyBuildCreateGroupTransaction, watchOnlyPopulateAndDuplicateTokenAuths,\n watchOnlyPopulateNexaInputsAndChange,\n watchOnlyPopulateTokenAuth, watchOnlyPopulateTokenInputsAndChange, watchOnlyPopulateTokenMelt,\n watchOnlyPopulateTokenMint, 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 /**\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 == '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 GroupToken,\n Transaction,\n UnitUtils\n} from \"libnexa-ts\";\nimport type { PermissionLabel, TxOptions } from \"../models/transaction.entities\";\nimport {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 let id = GroupToken.findGroupId(outpoint, Buffer.from(opReturnData, 'hex'), 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\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\n txBuilder.to(toAddr != null ? toAddr : item.address, Transaction.DUST_AMOUNT, token, dupAuthority(utxo.token_amount));\n\n if (reqiredPerms.size === 0) {\n return usedAddresses;\n }\n }\n }\n\n throw new Error(\"The required authorities not found\");\n}\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n","import {\n type AddTokenRequest,\n type DAppInfo,\n DAppProvider,\n JsonRpcError,\n JsonRpcErrorCode,\n type SendTransactionRequest,\n type SignMessageRequest,\n type SignTransactionRequest,\n type SwitchNetworkRequest\n} from 'wallet-comms-sdk';\nimport type Wallet from '../wallet/Wallet';\nimport {rostrumProvider} from '../network/RostrumProvider';\nimport {Networks, Transaction, Address, AddressType, BNExtended, Networkish} from 'libnexa-ts';\nimport type {BaseAccount} from '../wallet/accounts/interfaces/BaseAccountInterface';\nimport DAppAccount from '../wallet/accounts/models/DappAccount';\nimport {AccountType} from '../utils/WalletUtils';\nimport type {\n ApprovalCallbacks,\n MessageApprovalDetails,\n SendTransactionApprovalDetails,\n TransactionApprovalDetails\n} from './ApprovalInterfaces';\nimport {AUTO_APPROVE_CALLBACKS} from './ApprovalInterfaces';\n\n/**\n * Extract all token outputs and amounts from transaction hex\n * @param txHex - Transaction hex string\n * @param network - Network to use for token address creation\n * @returns Array of token outputs with tokenId and amount\n */\nconst getTokenOutputsFromTx = (txHex: string, network: Networkish): Array<{ tokenId: string, amount: string }> => {\n const tokenOutputs: Array<{ tokenId: string, amount: string }> = []\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 tokenIdHex = output.scriptPubKey.chunks[0].buf?.toString('hex')\n if (tokenIdHex && output.scriptPubKey.chunks[1]?.buf) {\n const tokenAddress = Address.fromObject({\n data: tokenIdHex,\n network: network.toString(),\n type: AddressType.GroupIdAddress\n })\n\n if (tokenAddress !== null) {\n const tokenAddressStr = tokenAddress.toString()\n\n // Extract token amount\n const tokenAmount = BNExtended.fromScriptNumBuffer(output.scriptPubKey.chunks[1].buf, false, 8).toBigInt()\n\n tokenOutputs.push({\n tokenId: tokenAddressStr,\n amount: tokenAmount.toString()\n })\n }\n }\n }\n }\n } catch (error) {\n console.warn('Failed to extract token data from transaction:', error)\n }\n\n return tokenOutputs\n}\n\n/**\n * Wallet-side WalletComms integration for receiving and handling dApp requests\n *\n * This class runs inside wallet applications and handles incoming requests from dApps.\n * It manages session connections, message signing, transaction signing, and network switching.\n * The wallet holds private keys and can actually sign transactions.\n *\n * @example\n * ```typescript\n * const wallet = Wallet.fromSeedPhrase('...');\n * await wallet.initialize();\n *\n * const walletComms = new WalletCommsIntegration(wallet);\n *\n * // Connect to a dApp using a pairing URI (usually from QR code)\n * const dAppInfo = await walletComms.connect('wl:1@relay.net/...');\n * console.log('Connected to:', dAppInfo.name);\n *\n * // The integration automatically handles dApp requests\n * ```\n */\nexport class WalletCommsIntegration {\n private wallet: Wallet;\n private provider: DAppProvider | null = null;\n private currentAccount: BaseAccount | null = null;\n private isConnected: boolean = false;\n private approvalCallbacks: ApprovalCallbacks;\n private connectedDApp: DAppInfo | null = null;\n\n constructor(wallet: Wallet, approvalCallbacks?: ApprovalCallbacks) {\n this.wallet = wallet;\n this.approvalCallbacks = approvalCallbacks || AUTO_APPROVE_CALLBACKS;\n }\n\n /**\n * Set approval callbacks for handling user consent\n */\n setApprovalCallbacks(callbacks: ApprovalCallbacks): void {\n this.approvalCallbacks = callbacks;\n }\n\n /**\n * Connect to a dApp using a pairing URI\n *\n * This method will only use DApp accounts for security isolation.\n * If no DApp account is provided, the first available one will be used or created.\n *\n * @param pairingURI - The pairing URI from the dApp (usually from QR code)\n * @param dappAccount - Optional specific DApp account to use (defaults to first available)\n * @returns Information about the connected dApp\n */\n async connect(pairingURI: string, dappAccount?: DAppAccount): Promise<DAppInfo> {\n if (this.isConnected) {\n this.disconnect();\n }\n\n this.provider = new DAppProvider(pairingURI);\n\n // Set up request handlers\n this.setupHandlers();\n\n // Connect to the dApp\n const dAppInfo = await this.provider.connect();\n\n // Request approval for connection if callback is provided\n if (this.approvalCallbacks.approveConnection) {\n const approved = await this.approvalCallbacks.approveConnection(dAppInfo);\n if (!approved) {\n this.provider.disconnect();\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Connection rejected by user'\n );\n }\n }\n\n this.connectedDApp = dAppInfo;\n\n // Use provided DApp account or get/create one\n if (dappAccount) {\n // Validate it's actually a DApp account\n if (dappAccount.getAccountType() !== AccountType.DAPP_ACCOUNT) {\n throw new Error('Only DApp accounts can be used with WalletComms');\n }\n this.currentAccount = dappAccount;\n } else {\n this.currentAccount = await this.getOrCreateDAppAccount();\n }\n\n // Join the session with the DApp account address\n const primaryAddress = this.currentAccount.getPrimaryAddressKey();\n await this.provider.joinSession(primaryAddress.address);\n\n this.isConnected = true;\n return dAppInfo;\n }\n\n /**\n * Get an existing DApp account or create a new one\n *\n * @returns A DApp account\n */\n private async getOrCreateDAppAccount(): Promise<DAppAccount> {\n // Get all DApp accounts using the new helper method\n const dappAccounts = this.wallet.accountStore.getAccountsByType(AccountType.DAPP_ACCOUNT);\n\n // Return first existing DApp account or create a new one\n if (dappAccounts.length > 0) {\n return dappAccounts[0] as DAppAccount;\n }\n\n // No DApp accounts exist, create one\n return await this.wallet.newAccount(AccountType.DAPP_ACCOUNT) as DAppAccount;\n }\n\n /**\n * Disconnect from the current dApp session\n */\n disconnect(): void {\n if (this.provider) {\n this.provider.disconnect();\n this.provider = null;\n }\n this.isConnected = false;\n this.currentAccount = null;\n }\n\n /**\n * Set up handlers for dApp requests\n */\n private setupHandlers(): void {\n if (!this.provider) return;\n\n // Handle message signing requests\n this.provider.onSignMessage(async (request: SignMessageRequest) => {\n try {\n const account = this.getAccountByAddress(request.account);\n if (!account) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Account ${request.account} not found`\n );\n }\n\n // Request approval for message signing\n if (this.approvalCallbacks.approveMessage && this.connectedDApp) {\n const approvalDetails: MessageApprovalDetails = {\n dApp: this.connectedDApp,\n account: request.account,\n message: request.message,\n messagePreview: request.message.length > 100\n ? request.message.substring(0, 100) + '...'\n : request.message\n };\n\n const approved = await this.approvalCallbacks.approveMessage(approvalDetails);\n if (!approved) {\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Message signing rejected by user'\n );\n }\n }\n\n return this.wallet.signMessage(request.message, request.account);\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to sign message'\n );\n }\n });\n\n // Handle get account requests\n this.provider.on('wallet_getAccount', async () => {\n if (!this.currentAccount) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n 'No account selected'\n );\n }\n const primaryAddress = this.currentAccount.getPrimaryAddressKey();\n return primaryAddress.address;\n });\n\n // Handle get accounts (multiple) requests - only return DApp accounts\n this.provider.on('wallet_getAccounts', async () => {\n const dappAccounts = this.wallet.accountStore.getAccountsByType(AccountType.DAPP_ACCOUNT);\n const addresses: string[] = [];\n\n // Return addresses from all DApp accounts\n for (const account of dappAccounts) {\n const primaryAddress = account.getPrimaryAddressKey();\n addresses.push(primaryAddress.address);\n }\n\n return addresses;\n });\n\n // Handle transaction signing requests\n this.provider.on('wallet_signTransaction', async (request: SignTransactionRequest) => {\n try {\n const account = this.getAccountByAddress(request.account);\n if (!account) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Account ${request.account} not found`\n );\n }\n\n // Request approval for transaction signing\n if (this.approvalCallbacks.approveTransaction && this.connectedDApp) {\n // Parse transaction to extract readable details\n let totalAmount = 'Unknown';\n let fees = 'Unknown';\n\n try {\n const tempBuilder = this.wallet.newTransaction(account, request.hex);\n const tx = tempBuilder.transactionBuilder.build();\n\n // Calculate total NEXA amount being sent (excluding change)\n let nexaTotal = 0n;\n for (const output of tx.outputs) {\n if (output.value != BigInt(Transaction.DUST_AMOUNT)) { // Only NEXA outputs\n nexaTotal += output.value;\n }\n }\n\n // Estimate fees\n const estimatedFee = tx.estimateRequiredFee();\n\n totalAmount = nexaTotal.toString()\n fees = estimatedFee.toString()\n } catch (error) {\n // If parsing fails, keep default \"Unknown\" values\n console.warn('Failed to parse transaction for approval details:', error);\n }\n\n // Extract token outputs from transaction hex\n const tokenOutputs = getTokenOutputsFromTx(request.hex, this.wallet.network);\n\n const approvalDetails: TransactionApprovalDetails = {\n dApp: this.connectedDApp,\n account: request.account,\n transactionHex: request.hex,\n broadcast: request.broadcast || false,\n totalAmount,\n fees,\n tokenOutputs: tokenOutputs.length > 0 ? tokenOutputs : undefined\n };\n\n const approved = await this.approvalCallbacks.approveTransaction(approvalDetails);\n if (!approved) {\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Transaction signing rejected by user'\n );\n }\n }\n\n // Parse and sign the transaction\n let txBuilder = this.wallet.newTransaction(account, request.hex)\n\n txBuilder = txBuilder.sign()\n\n const tx = await txBuilder.build();\n\n // Broadcast if requested\n if (request.broadcast) {\n return await this.wallet.sendTransaction(tx); // Return just the txId string\n }\n\n return tx; // Return just the transaction hex string\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to sign transaction'\n );\n }\n });\n\n // Handle send transaction requests\n this.provider.on('wallet_sendTransaction', async (request: SendTransactionRequest) => {\n try {\n const account = this.getAccountByAddress(request.from);\n if (!account) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Account ${request.from} not found`\n );\n }\n\n // Calculate total amount\n let totalAmount = BigInt(0);\n for (const recipient of request.to) {\n if (!recipient.token) {\n totalAmount += BigInt(recipient.amount);\n }\n }\n\n // Request approval for sending transaction\n if (this.approvalCallbacks.approveSendTransaction && this.connectedDApp) {\n const approvalDetails: SendTransactionApprovalDetails = {\n dApp: this.connectedDApp,\n fromAccount: request.from,\n recipients: request.to,\n totalAmount: totalAmount.toString(),\n opReturn: request.data\n };\n\n const approved = await this.approvalCallbacks.approveSendTransaction(approvalDetails);\n if (!approved) {\n throw new JsonRpcError(\n JsonRpcErrorCode.RequestRejected,\n 'Send transaction rejected by user'\n );\n }\n }\n\n let txBuilder = this.wallet.newTransaction(account)\n .onNetwork(this.wallet.network);\n\n // Add recipients\n for (const recipient of request.to) {\n if (recipient.token) {\n txBuilder = txBuilder.sendToToken(recipient.address, recipient.amount, recipient.token)\n } else {\n txBuilder = txBuilder.sendTo(recipient.address, recipient.amount);\n }\n }\n\n // Add OP_RETURN data if provided\n if (request.data) {\n txBuilder = txBuilder.addOpReturn(request.data);\n }\n\n // Build and send the transaction\n const tx = await txBuilder\n .populate()\n .sign()\n .build();\n\n const txId = await this.wallet.sendTransaction(tx);\n return { txId, hex: tx };\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to send transaction'\n );\n }\n });\n\n // Handle network switching requests\n this.provider.on('wallet_switchNetwork', async (request: SwitchNetworkRequest) => {\n try {\n // Validate network\n const network = Networks.get(request.network);\n if (!network) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InvalidParams,\n `Unknown network: ${request.network}`\n );\n }\n\n // Reconnect to the new network\n await rostrumProvider.connect(request.network);\n\n return { success: true, network: request.network };\n } catch (error) {\n throw new JsonRpcError(\n JsonRpcErrorCode.InternalError,\n error instanceof Error ? error.message : 'Failed to switch network'\n );\n }\n });\n\n // Handle add token requests\n this.provider.on('wallet_addToken', async (request: AddTokenRequest) => {\n // This would need implementation based on how tokens are tracked\n // For now, we'll acknowledge but not implement\n console.log('Add token request:', request);\n return { success: true };\n });\n\n // Handle peer disconnect\n this.provider.onPeerDisconnect(() => {\n console.log('DApp disconnected');\n this.isConnected = false;\n });\n\n // Handle connection close\n this.provider.onClose(() => {\n console.log('Connection closed');\n this.isConnected = false;\n });\n }\n\n /**\n * Get an account by its address\n */\n private getAccountByAddress(address: string): BaseAccount | null {\n const accounts = this.wallet.accountStore.listAccounts();\n\n for (const [_, account] of accounts) {\n const addresses = account.getAddresses();\n if (addresses.some(addr => addr.address === address)) {\n return account;\n }\n }\n\n return null;\n }\n\n /**\n * Switch the active account\n */\n setActiveAccount(account: BaseAccount): void {\n this.currentAccount = account;\n }\n\n /**\n * Get the current active account\n */\n getActiveAccount(): BaseAccount | null {\n return this.currentAccount;\n }\n\n /**\n * Check if connected to a dApp\n */\n isConnectedToDApp(): boolean {\n return this.isConnected;\n }\n\n /**\n * Get the current session details\n */\n getSessionInfo(): any {\n if (!this.provider) {\n return null;\n }\n return this.provider.getSessionInfo();\n }\n}\n","import type {\n SignMessageRequest,\n SignTransactionRequest,\n SendTransactionRequest,\n AddTokenRequest,\n SwitchNetworkRequest,\n DAppInfo\n} from 'wallet-comms-sdk';\n\n/**\n * Details for transaction signing approval request\n */\nexport interface TransactionApprovalDetails {\n dApp: DAppInfo;\n account: string;\n transactionHex: string;\n broadcast: boolean;\n sighashSpec?: any;\n // Parsed transaction details (if available)\n recipients?: Array<{\n address: string;\n amount: string;\n token?: string;\n }>;\n totalAmount?: string;\n fees?: string;\n opReturn?: string;\n tokenOutputs?: Array<{\n tokenId: string;\n amount: string;\n }>; // Array of token outputs with amounts\n}\n\n/**\n * Details for message signing approval request\n */\nexport interface MessageApprovalDetails {\n dApp: DAppInfo;\n account: string;\n message: string;\n messagePreview: string; // First 100 chars for display\n}\n\n/**\n * Details for send transaction approval request\n */\nexport interface SendTransactionApprovalDetails {\n dApp: DAppInfo;\n fromAccount: string;\n recipients: Array<{\n address: string;\n amount: string;\n token?: string;\n }>;\n totalAmount: string;\n estimatedFees?: string;\n opReturn?: string;\n}\n\n/**\n * Details for network switching approval request\n */\nexport interface NetworkSwitchApprovalDetails {\n dApp: DAppInfo;\n currentNetwork: string;\n requestedNetwork: string;\n}\n\n/**\n * Details for add token approval request\n */\nexport interface AddTokenApprovalDetails {\n dApp: DAppInfo;\n account: string;\n tokenId: string;\n tokenInfo?: {\n name?: string;\n symbol?: string;\n decimals?: number;\n };\n}\n\n/**\n * Approval callbacks interface for handling user approval requests\n */\nexport interface ApprovalCallbacks {\n /**\n * Request approval for transaction signing\n * @param details Transaction details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveTransaction?: (details: TransactionApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for message signing\n * @param details Message details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveMessage?: (details: MessageApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for sending a transaction\n * @param details Send transaction details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveSendTransaction?: (details: SendTransactionApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for network switching\n * @param details Network switch details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveNetworkSwitch?: (details: NetworkSwitchApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for adding a token\n * @param details Add token details for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveAddToken?: (details: AddTokenApprovalDetails) => Promise<boolean>;\n\n /**\n * Request approval for connecting to a dApp\n * @param dAppInfo DApp information for user review\n * @returns Promise<boolean> true if approved, false if rejected\n */\n approveConnection?: (dAppInfo: DAppInfo) => Promise<boolean>;\n}\n\n/**\n * Default approval callbacks that auto-approve everything (for backwards compatibility)\n */\nexport const AUTO_APPROVE_CALLBACKS: ApprovalCallbacks = {\n approveTransaction: async () => true,\n approveMessage: async () => true,\n approveSendTransaction: async () => true,\n approveNetworkSwitch: async () => true,\n approveAddToken: async () => true,\n approveConnection: async () => true,\n};","import {type DAppInfo, WalletProvider} from 'wallet-comms-sdk';\nimport WatchOnlyWallet from '../wallet/WatchOnlyWallet';\nimport {rostrumProvider} from '../network/RostrumProvider';\nimport type {Networkish} from 'libnexa-ts';\n\n/**\n * DApp-side WalletComms provider that creates unsigned transactions and requests signatures\n *\n * This class runs inside dApp applications and communicates with wallet apps via WalletComms.\n * It uses WatchOnlyWallet to create unsigned transactions, then requests signatures from wallets.\n * The dApp never has access to private keys - only signed transaction results.\n *\n * @example\n * ```typescript\n * // Initialize the dApp provider\n * const dappProvider = new DAppWalletProvider(\n * 'wss://relay.nexa.org',\n * {\n * name: 'My Trading dApp',\n * url: 'https://trade.example.com',\n * description: 'Decentralized trading platform',\n * icon: 'https://trade.example.com/logo.png'\n * }\n * );\n *\n * // Connect and wait for wallet\n * await dappProvider.connect();\n * const pairingURI = dappProvider.getPairingURI();\n * // Display QR code with pairingURI\n *\n * const walletAddress = await dappProvider.waitForWallet(30000);\n * console.log('Connected to wallet:', walletAddress);\n *\n * // Send a transaction\n * const txId = await dappProvider.sendTransaction(\n * 'nexa:nqtsq5g5jsdmqqywaqd82lhnnk3a8wqunjz6gtxdtavnnekc',\n * '10000000'\n * );\n * ```\n */\nexport class DAppCommsProvider {\n private provider: WalletProvider;\n private watchOnlyWallet: WatchOnlyWallet | null = null;\n private connectedWalletAddress: string | null = null;\n private currentNetwork: Networkish | string = 'mainnet';\n\n /**\n * Creates a new DAppCommsProvider instance\n * @param relayUrl The WalletComms relay server URL\n * @param dAppInfo Information about your dApp\n * @param network Optional network (defaults to mainnet)\n */\n constructor(\n relayUrl: string,\n dAppInfo: DAppInfo,\n network: Networkish | string = 'mainnet'\n ) {\n this.provider = new WalletProvider(relayUrl, dAppInfo);\n this.currentNetwork = network;\n }\n\n /**\n * Connect to the WalletComms relay server\n * @returns Promise resolving when connected\n */\n async connect(): Promise<void> {\n await this.provider.connect();\n\n // Connect to the appropriate network\n await rostrumProvider.connect(this.currentNetwork);\n }\n\n /**\n * Get the pairing URI for QR code display\n * @returns The pairing URI string\n */\n getPairingURI(): string {\n return this.provider.getPairingURI();\n }\n\n /**\n * Wait for a wallet to connect\n * @param timeout Timeout in milliseconds (default 30000)\n * @returns Promise resolving to the wallet address\n */\n async waitForWallet(timeout: number = 30000): Promise<string> {\n try {\n // Use the built-in waitForWallet method from WalletProvider\n const walletAddress = await this.provider.waitForWallet(timeout);\n\n this.connectedWalletAddress = walletAddress;\n\n // Create WatchOnlyWallet with the connected address\n this.watchOnlyWallet = new WatchOnlyWallet([{\n address: walletAddress\n }], this.currentNetwork as string);\n\n return walletAddress;\n } catch (error) {\n throw new Error(`Failed to connect wallet: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n\n /**\n * Send NEXA to an address\n * @param toAddress Destination address\n * @param amount Amount in satoshis (as string)\n * @param opReturnData Optional OP_RETURN data\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async sendTransaction(\n toAddress: string,\n amount: string,\n opReturnData?: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create unsigned transaction using WatchOnlyWallet\n let txBuilder = this.watchOnlyWallet.newTransaction()\n .sendTo(toAddress, amount);\n\n // Add OP_RETURN data if provided\n if (opReturnData) {\n txBuilder = txBuilder.addOpReturn(opReturnData);\n }\n\n // Populate and build unsigned transaction\n const unsignedTx = await txBuilder\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Send tokens to an address\n * @param toAddress Destination address\n * @param amount Amount of tokens (as string)\n * @param tokenId Token ID\n * @param opReturnData Optional OP_RETURN data\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async sendTokenTransaction(\n toAddress: string,\n amount: string,\n tokenId: string,\n opReturnData?: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create unsigned token transaction\n let txBuilder = this.watchOnlyWallet.newTransaction()\n .sendToToken(toAddress, amount, tokenId);\n\n // Add OP_RETURN data if provided\n if (opReturnData) {\n txBuilder = txBuilder.addOpReturn(opReturnData);\n }\n\n // Populate and build unsigned transaction\n const unsignedTx = await txBuilder\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint a new token\n * @param name Token name\n * @param ticker Token ticker symbol\n * @param decimals Number of decimal places\n * @param docUrl URL to token documentation\n * @param docHash Hash of token documentation\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createToken(\n name: string,\n ticker: string,\n decimals: number,\n docUrl: string,\n docHash: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create token creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .token(name, ticker, decimals, docUrl, docHash)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint a new NFT collection\n * @param name Collection name\n * @param ticker Collection ticker symbol\n * @param docUrl URL to collection documentation\n * @param docHash Hash of collection documentation\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createCollection(\n name: string,\n ticker: string,\n docUrl: string,\n docHash: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create collection creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .collection(name, ticker, docUrl, docHash)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint an NFT within a collection\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to NFT content ZIP file\n * @param zipHash Hash of NFT content ZIP file\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createNFT(\n parentCollection: string,\n zipUrl: string,\n zipHash: string,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create NFT creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .nft(parentCollection, zipUrl, zipHash)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Create and mint an SFT (Semi-Fungible Token) within a collection with specified quantity\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to SFT content ZIP file\n * @param zipHash Hash of SFT content ZIP file\n * @param quantity Quantity of SFTs to create\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createSFT(\n parentCollection: string,\n zipUrl: string,\n zipHash: string,\n quantity: bigint,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create SFT creation transaction\n const unsignedTx = await this.watchOnlyWallet.newTransaction()\n .sft(parentCollection, zipUrl, zipHash, quantity)\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Sign an arbitrary unsigned transaction\n * @param unsignedTx Unsigned transaction hex string\n * @param sighashSpec Optional sighash specification for selective signing\n * @param broadcast Whether to broadcast immediately (default false)\n * @returns Promise resolving to transaction ID (if broadcast) or signed hex\n */\n async signTransaction(\n unsignedTx: string,\n sighashSpec?: Record<number, {inFlag: number; inRange?: number; outFlag: number; outRange?: number;}>,\n broadcast: boolean = false\n ): Promise<string> {\n if (!this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Build an unsigned transaction without signing\n * @param toAddress Destination address\n * @param amount Amount in satoshis (as string)\n * @param tokenId Optional token ID for token transfers\n * @param opReturnData Optional OP_RETURN data\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildTransaction(\n toAddress: string,\n amount: string,\n tokenId?: string,\n opReturnData?: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n let txBuilder = this.watchOnlyWallet.newTransaction();\n\n if (tokenId) {\n txBuilder = txBuilder.sendToToken(toAddress, amount, tokenId);\n } else {\n txBuilder = txBuilder.sendTo(toAddress, amount);\n }\n\n if (opReturnData) {\n txBuilder = txBuilder.addOpReturn(opReturnData);\n }\n\n return await txBuilder.populate().build();\n }\n\n /**\n * Build an unsigned token creation transaction\n * @param name Token name\n * @param ticker Token ticker symbol\n * @param decimals Number of decimal places\n * @param docUrl URL to token documentation\n * @param docHash Hash of token documentation\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildTokenCreation(\n name: string,\n ticker: string,\n decimals: number,\n docUrl: string,\n docHash: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .token(name, ticker, decimals, docUrl, docHash)\n .populate()\n .build();\n }\n\n /**\n * Build an unsigned collection creation transaction\n * @param name Collection name\n * @param ticker Collection ticker symbol\n * @param docUrl URL to collection documentation\n * @param docHash Hash of collection documentation\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildCollectionCreation(\n name: string,\n ticker: string,\n docUrl: string,\n docHash: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .collection(name, ticker, docUrl, docHash)\n .populate()\n .build();\n }\n\n /**\n * Build an unsigned NFT creation transaction\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to NFT content ZIP file\n * @param zipHash Hash of NFT content ZIP file\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildNFTCreation(\n parentCollection: string,\n zipUrl: string,\n zipHash: string\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .nft(parentCollection, zipUrl, zipHash)\n .populate()\n .build();\n }\n\n /**\n * Build an unsigned SFT creation transaction\n * @param parentCollection Parent collection token ID\n * @param zipUrl URL to SFT content ZIP file\n * @param zipHash Hash of SFT content ZIP file\n * @param quantity Quantity of SFTs to create\n * @returns Promise resolving to unsigned transaction hex\n */\n async buildSFTCreation(\n parentCollection: string,\n zipUrl: string,\n zipHash: string,\n quantity: bigint\n ): Promise<string> {\n if (!this.watchOnlyWallet) {\n throw new Error('No wallet connected');\n }\n\n return await this.watchOnlyWallet.newTransaction()\n .sft(parentCollection, zipUrl, zipHash, quantity)\n .populate()\n .build();\n }\n\n /**\n * Initialize WatchOnlyWallet with multiple addresses\n * @param addresses Array of addresses to watch\n */\n initializeWatchOnly(addresses: string[]): void {\n this.watchOnlyWallet = new WatchOnlyWallet(\n addresses.map(addr => ({ address: addr })),\n this.currentNetwork as string\n );\n }\n\n /**\n * Create a custom unsigned transaction\n * @param txBuilder Function that configures the transaction builder\n * @param sighashSpec Optional sighash specification for selective signing\n * @param broadcast Whether to broadcast immediately (default true)\n * @returns Promise resolving to transaction ID or signed hex\n */\n async createCustomTransaction(\n txBuilder: (builder: any) => any,\n sighashSpec?: Record<number, {inFlag: number; inRange?: number; outFlag: number; outRange?: number;}>,\n broadcast: boolean = true\n ): Promise<string> {\n if (!this.watchOnlyWallet || !this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n // Create custom transaction using provided builder function\n const builder = this.watchOnlyWallet.newTransaction();\n\n const configuredBuilder = txBuilder(builder);\n\n const unsignedTx = await configuredBuilder\n .populate()\n .build();\n\n return await this.provider.signTransaction(\n this.connectedWalletAddress,\n unsignedTx,\n broadcast\n );\n }\n\n /**\n * Sign a message with the connected wallet\n * @param message Message to sign\n * @returns Promise resolving to the signature\n */\n async signMessage(message: string): Promise<string> {\n if (!this.connectedWalletAddress) {\n throw new Error('No wallet connected');\n }\n\n return await this.provider.signMessage(\n this.connectedWalletAddress,\n message\n );\n }\n\n /**\n * Switch to a different network\n * @param network Network name or identifier\n * @returns Promise resolving when network is switched\n */\n async switchNetwork(network: string): Promise<void> {\n await this.provider.switchNetwork(network);\n this.currentNetwork = network;\n\n // Reconnect rostrum provider to new network\n await rostrumProvider.connect(network);\n\n // Update watch-only wallet network if connected\n if (this.watchOnlyWallet && this.connectedWalletAddress) {\n this.watchOnlyWallet = new WatchOnlyWallet([{\n address: this.connectedWalletAddress\n }], network);\n }\n }\n\n /**\n * Get the currently connected wallet address\n * @returns Wallet address or null if not connected\n */\n getConnectedWallet(): string | null {\n return this.connectedWalletAddress;\n }\n\n /**\n * Check if a wallet is currently connected\n * @returns True if wallet is connected\n */\n isConnected(): boolean {\n return this.connectedWalletAddress !== null;\n }\n\n /**\n * Get the current network\n * @returns Current network identifier\n */\n getCurrentNetwork(): Networkish | string {\n return this.currentNetwork;\n }\n\n /**\n * Get the underlying WatchOnlyWallet instance\n * @returns WatchOnlyWallet instance or null if not connected\n */\n getWatchOnlyWallet(): WatchOnlyWallet | null {\n return this.watchOnlyWallet;\n }\n\n /**\n * Disconnect from the wallet\n */\n disconnect(): void {\n this.provider.disconnect();\n this.watchOnlyWallet = null;\n this.connectedWalletAddress = null;\n }\n\n /**\n * Set up event listeners for wallet events\n * @param event Event name\n * @param callback Event callback\n */\n on(event: string, callback: (...args: any[]) => void): void {\n this.provider.on(event, callback);\n }\n\n /**\n * Remove event listeners\n * @param event Event name\n */\n off(event: string): void {\n this.provider.off(event);\n }\n\n /**\n * Set up wallet disconnect event listener\n * @param callback Function to call when wallet disconnects\n */\n onWalletDisconnect(callback: () => void): void {\n this.provider.onPeerDisconnect(() => {\n this.watchOnlyWallet = null;\n this.connectedWalletAddress = null;\n callback();\n });\n }\n\n /**\n * Set up connection close event listener\n * @param callback Function to call when connection closes\n */\n onConnectionClose(callback: () => void): void {\n this.provider.onClose(() => {\n this.watchOnlyWallet = null;\n this.connectedWalletAddress = null;\n callback();\n });\n }\n}\n\nexport default DAppCommsProvider;\n"],"names":[],"version":3,"file":"index.cjs.map","sourceRoot":"../"}