{"version":3,"file":"account-manager.mjs","names":[],"sources":["../../src/types/account-manager.ts"],"sourcesContent":["import algosdk, { Address } from 'algosdk'\nimport { Config } from '../config'\nimport { calculateFundAmount, memoize } from '../util'\nimport { AccountInformation, DISPENSER_ACCOUNT, MultisigAccount, SigningAccount, TransactionSignerAccount } from './account'\nimport { AlgoAmount } from './amount'\nimport { ClientManager } from './client-manager'\nimport { CommonTransactionParams, TransactionComposer } from './composer'\nimport { TestNetDispenserApiClient } from './dispenser-client'\nimport { KmdAccountManager } from './kmd-account-manager'\nimport { SendParams, SendSingleTransactionResult } from './transaction'\nimport LogicSigAccount = algosdk.LogicSigAccount\nimport Account = algosdk.Account\nimport TransactionSigner = algosdk.TransactionSigner\n\nconst address = (address: string | Address) => (typeof address === 'string' ? Address.fromString(address) : address)\n\n/** Result from performing an ensureFunded call. */\nexport interface EnsureFundedResult {\n  /** The transaction ID of the transaction that funded the account. */\n  transactionId: string\n  /** The amount that was sent to the account. */\n  amountFunded: AlgoAmount\n}\n\n/**\n * Returns a `TransactionSigner` for the given account that can sign a transaction.\n * This function has memoization, so will return the same transaction signer for a given account.\n * @param account An account that can sign a transaction\n * @returns A transaction signer\n * @example\n * ```typescript\n * const signer = getAccountTransactionSigner(account)\n * ```\n */\nexport const getAccountTransactionSigner = memoize(function (\n  account: TransactionSignerAccount | Account | SigningAccount | LogicSigAccount | MultisigAccount,\n): TransactionSigner {\n  return 'signer' in account\n    ? account.signer\n    : 'lsig' in account\n      ? algosdk.makeLogicSigAccountTransactionSigner(account)\n      : algosdk.makeBasicAccountTransactionSigner(account)\n})\n\n/** Creates and keeps track of signing accounts that can sign transactions for a sending address. */\nexport class AccountManager {\n  private _clientManager: ClientManager\n  private _kmdAccountManager: KmdAccountManager\n  private _accounts: { [address: string]: TransactionSignerAccount } = {}\n  private _defaultSigner?: algosdk.TransactionSigner\n\n  /**\n   * Create a new account manager.\n   * @param clientManager The ClientManager client to use for algod and kmd clients\n   * @example Create a new account manager\n   * ```typescript\n   * const accountManager = new AccountManager(clientManager)\n   * ```\n   */\n  constructor(clientManager: ClientManager) {\n    this._clientManager = clientManager\n    this._kmdAccountManager = new KmdAccountManager(clientManager)\n  }\n\n  private _getComposer(getSuggestedParams?: () => Promise<algosdk.SuggestedParams>) {\n    return new TransactionComposer({\n      algod: this._clientManager.algod,\n      getSigner: this.getSigner.bind(this),\n      getSuggestedParams: getSuggestedParams ?? (() => this._clientManager.algod.getTransactionParams().do()),\n    })\n  }\n\n  /**\n   * KMD account manager that allows you to easily get and create accounts using KMD.\n   * @returns The `KmdAccountManager` instance.\n   * @example\n   * ```typescript\n   * const kmdManager = accountManager.kmd;\n   * ```\n   */\n  public get kmd() {\n    return this._kmdAccountManager\n  }\n\n  /**\n   * Sets the default signer to use if no other signer is specified.\n   *\n   * If this isn't set an a transaction needs signing for a given sender\n   * then an error will be thrown from `getSigner` / `getAccount`.\n   * @param signer The signer to use, either a `TransactionSigner` or a `TransactionSignerAccount`\n   * @example\n   * ```typescript\n   * const signer = accountManager.random() // Can be anything that returns a `algosdk.TransactionSigner` or `TransactionSignerAccount`\n   * accountManager.setDefaultSigner(signer)\n   *\n   * // When signing a transaction, if there is no signer registered for the sender then the default signer will be used\n   * const signer = accountManager.getSigner(\"SENDERADDRESS\")\n   * ```\n   * @returns The `AccountManager` so method calls can be chained\n   */\n  public setDefaultSigner(signer: algosdk.TransactionSigner | TransactionSignerAccount): AccountManager {\n    this._defaultSigner = 'signer' in signer ? signer.signer : signer\n    return this\n  }\n\n  /**\n   * Records the given account (that can sign) against the address of the provided account for later\n   * retrieval and returns a `TransactionSignerAccount` along with the original account in an `account` property.\n   */\n\n  private signerAccount<T extends TransactionSignerAccount | Account | SigningAccount | LogicSigAccount | MultisigAccount>(\n    account: T,\n  ): Address &\n    TransactionSignerAccount & {\n      /* The underlying account that specified this address. */ account: T\n    } {\n    const signer = getAccountTransactionSigner(account)\n    const acc: TransactionSignerAccount = {\n      addr: 'addr' in account ? account.addr : account.address(),\n      signer: signer,\n    }\n    this._accounts[acc.addr.toString()] = acc\n\n    const addressWithAccount = Address.fromString(acc.addr.toString()) as Address & TransactionSignerAccount & { account: T }\n    addressWithAccount.account = account\n    addressWithAccount.addr = acc.addr\n    addressWithAccount.signer = signer\n    return addressWithAccount\n  }\n\n  /**\n   * Tracks the given account for later signing.\n   *\n   * Note: If you are generating accounts via the various methods on `AccountManager`\n   * (like `random`, `fromMnemonic`, `logicsig`, etc.) then they automatically get tracked.\n   * @param account The account to register, which can be a `TransactionSignerAccount` or\n   *  a `algosdk.Account`, `algosdk.LogicSigAccount`, `SigningAccount` or `MultisigAccount`\n   * @example\n   * ```typescript\n   * const accountManager = new AccountManager(clientManager)\n   *  .setSignerFromAccount(algosdk.generateAccount())\n   *  .setSignerFromAccount(new algosdk.LogicSigAccount(program, args))\n   *  .setSignerFromAccount(new SigningAccount(mnemonic, sender))\n   *  .setSignerFromAccount(new MultisigAccount({version: 1, threshold: 1, addrs: [\"ADDRESS1...\", \"ADDRESS2...\"]}, [account1, account2]))\n   *  .setSignerFromAccount({addr: \"SENDERADDRESS\", signer: transactionSigner})\n   * ```\n   * @returns The `AccountManager` instance for method chaining\n   */\n  public setSignerFromAccount(account: TransactionSignerAccount | Account | LogicSigAccount | SigningAccount | MultisigAccount) {\n    this.signerAccount(account)\n    return this\n  }\n\n  /**\n   * Tracks the given `algosdk.TransactionSigner` against the given sender address for later signing.\n   * @param sender The sender address to use this signer for\n   * @param signer The `algosdk.TransactionSigner` to sign transactions with for the given sender\n   * @example\n   * ```typescript\n   * const accountManager = new AccountManager(clientManager)\n   *  .setSigner(\"SENDERADDRESS\", transactionSigner)\n   * ```\n   * @returns The `AccountManager` instance for method chaining\n   */\n  public setSigner(sender: string | Address, signer: algosdk.TransactionSigner) {\n    this._accounts[address(sender).toString()] = { addr: address(sender), signer }\n    return this\n  }\n\n  /**\n   * Takes all registered signers from the given `AccountManager` and adds them to this `AccountManager`.\n   *\n   * This is useful for situations where you have multiple contexts you are building accounts in such as unit tests.\n   * @param anotherAccountManager Another account manager with signers registered\n   * @param overwriteExisting Whether or not to overwrite any signers that have the same sender address with the ones in the other account manager or not (default: true)\n   * @returns The `AccountManager` instance for method chaining\n   * @example\n   * ```typescript\n   * accountManager2.setSigners(accountManager1);\n   * ```\n   */\n  public setSigners(anotherAccountManager: AccountManager, overwriteExisting = true) {\n    this._accounts = overwriteExisting\n      ? { ...this._accounts, ...anotherAccountManager._accounts }\n      : { ...anotherAccountManager._accounts, ...this._accounts }\n    return this\n  }\n\n  /**\n   * Returns the `TransactionSigner` for the given sender address, ready to sign a transaction for that sender.\n   *\n   * If no signer has been registered for that address then the default signer is used if registered and\n   * if not then an error is thrown.\n   *\n   * @param sender The sender address\n   * @example\n   * ```typescript\n   * const signer = accountManager.getSigner(\"SENDERADDRESS\")\n   * ```\n   * @returns The `TransactionSigner` or throws an error if not found and no default signer is set\n   */\n  public getSigner(sender: string | Address): algosdk.TransactionSigner {\n    const signer = this._accounts[address(sender).toString()]?.signer ?? this._defaultSigner\n    if (!signer) throw new Error(`No signer found for address ${sender}`)\n    return signer\n  }\n\n  /**\n   * Returns the `TransactionSignerAccount` for the given sender address.\n   *\n   * If no signer has been registered for that address then an error is thrown.\n   * @param sender The sender address\n   * @example\n   * ```typescript\n   * const sender = accountManager.random()\n   * // ...\n   * // Returns the `TransactionSignerAccount` for `sender` that has previously been registered\n   * const account = accountManager.getAccount(sender)\n   * ```\n   * @returns The `TransactionSignerAccount` or throws an error if not found\n   */\n  public getAccount(sender: string | Address): TransactionSignerAccount {\n    const account = this._accounts[address(sender).toString()]\n    if (!account) throw new Error(`No signer found for address ${sender}`)\n    return account\n  }\n\n  /**\n   * Returns the given sender account's current status, balance and spendable amounts.\n   *\n   * [Response data schema details](https://dev.algorand.co/reference/rest-api/algod/operations/accountinformation/)\n   * @example\n   * ```typescript\n   * const address = \"XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA\";\n   * const accountInfo = await accountManager.getInformation(address);\n   * ```\n   *\n   * @param sender The account / address to look up\n   * @returns The account information\n   */\n  public async getInformation(sender: string | Address): Promise<AccountInformation> {\n    const {\n      round,\n      lastHeartbeat = undefined,\n      lastProposed = undefined,\n      address,\n      ...account\n    } = await this._clientManager.algod.accountInformation(sender).do()\n\n    return {\n      ...account,\n      // None of the Number types can practically overflow 2^53\n      address: Address.fromString(address),\n      balance: AlgoAmount.MicroAlgo(Number(account.amount)),\n      amountWithoutPendingRewards: AlgoAmount.MicroAlgo(Number(account.amountWithoutPendingRewards)),\n      minBalance: AlgoAmount.MicroAlgo(Number(account.minBalance)),\n      pendingRewards: AlgoAmount.MicroAlgo(Number(account.pendingRewards)),\n      rewards: AlgoAmount.MicroAlgo(Number(account.rewards)),\n      validAsOfRound: BigInt(round),\n      totalAppsOptedIn: Number(account.totalAppsOptedIn),\n      totalAssetsOptedIn: Number(account.totalAssetsOptedIn),\n      totalCreatedApps: Number(account.totalCreatedApps),\n      totalCreatedAssets: Number(account.totalCreatedAssets),\n      appsTotalExtraPages: account.appsTotalExtraPages !== undefined ? Number(account.appsTotalExtraPages) : undefined,\n      rewardBase: account.rewardBase !== undefined ? Number(account.rewardBase) : undefined,\n      totalBoxBytes: account.totalBoxBytes !== undefined ? Number(account.totalBoxBytes) : undefined,\n      totalBoxes: account.totalBoxes !== undefined ? Number(account.totalBoxes) : undefined,\n      lastHeartbeatRound: lastHeartbeat !== undefined ? BigInt(lastHeartbeat) : undefined,\n      lastProposedRound: lastProposed !== undefined ? BigInt(lastProposed) : undefined,\n    }\n  }\n\n  /**\n   * Tracks and returns an Algorand account with secret key loaded (i.e. that can sign transactions) by taking the mnemonic secret.\n   *\n   * @example\n   * ```typescript\n   * const account = accountManager.fromMnemonic(\"mnemonic secret ...\")\n   * const rekeyedAccount = accountManager.fromMnemonic(\"mnemonic secret ...\", \"SENDERADDRESS...\")\n   * ```\n   * @param mnemonicSecret The mnemonic secret representing the private key of an account; **Note: Be careful how the mnemonic is handled**,\n   *  never commit it into source control and ideally load it from the environment (ideally via a secret storage service) rather than the file system.\n   * @param sender The optional sender address to use this signer for (aka a rekeyed account)\n   * @returns The account\n   */\n  public fromMnemonic(mnemonicSecret: string, sender?: string | Address) {\n    const account = algosdk.mnemonicToSecretKey(mnemonicSecret)\n    return this.signerAccount(new SigningAccount(account, sender))\n  }\n\n  /**\n   * Tracks and returns an Algorand account that is a rekeyed version of the given account to a new sender.\n   *\n   * @example\n   * ```typescript\n   * const account = accountManager.fromMnemonic(\"mnemonic secret ...\")\n   * const rekeyedAccount = accountManager.rekeyed(account, \"SENDERADDRESS...\")\n   * ```\n   * @param account The account to use as the signer for this new rekeyed account\n   * @param sender The sender address to use as the new sender\n   * @returns The account\n   */\n  public rekeyed(sender: string | Address, account: TransactionSignerAccount) {\n    return this.signerAccount({ addr: address(sender), signer: account.signer })\n  }\n\n  /**\n   * Tracks and returns an Algorand account with private key loaded by convention from environment variables based on the given name identifier.\n   *\n   * Note: This function expects to run in a Node.js environment.\n   *\n   * ## Convention:\n   * * **Non-LocalNet:** will load process.env['\\{NAME\\}_MNEMONIC'] as a mnemonic secret; **Note: Be careful how the mnemonic is handled**,\n   *  never commit it into source control and ideally load it via a secret storage service rather than the file system.\n   *   If process.env['\\{NAME\\}_SENDER'] is defined then it will use that for the sender address (i.e. to support rekeyed accounts)\n   * * **LocalNet:** will load the account from a KMD wallet called \\{NAME\\} and if that wallet doesn't exist it will create it and fund the account for you\n   *\n   * This allows you to write code that will work seamlessly in production and local development (LocalNet) without manual config locally (including when you reset the LocalNet).\n   *\n   * @example Default\n   *\n   * If you have a mnemonic secret loaded into `process.env.MY_ACCOUNT_MNEMONIC` then you can call the following to get that private key loaded into an account object:\n   * ```typescript\n   * const account = await accountManager.fromEnvironment('MY_ACCOUNT')\n   * ```\n   *\n   * If that code runs against LocalNet then a wallet called `MY_ACCOUNT` will automatically be created with an account that is automatically funded with 1000 (default) ALGO from the default LocalNet dispenser.\n   * If not running against LocalNet then it will use process.env.MY_ACCOUNT_MNEMONIC as the private key and (if present) process.env.MY_ACCOUNT_SENDER as the sender address.\n   *\n   * @param name The name identifier of the account\n   * @param fundWith The optional amount to fund the account with when it gets created (when targeting LocalNet), if not specified then 1000 ALGO will be funded from the dispenser account\n   * @returns The account\n   */\n  public async fromEnvironment(name: string, fundWith?: AlgoAmount) {\n    if (!process || !process.env) {\n      throw new Error('Attempt to get account with private key from a non Node.js context; this is not supported!')\n    }\n\n    const accountMnemonic = process.env[`${name.toUpperCase()}_MNEMONIC`]\n    const sender = process.env[`${name.toUpperCase()}_SENDER`]\n\n    if (accountMnemonic) {\n      const signer = algosdk.mnemonicToSecretKey(accountMnemonic)\n      return this.signerAccount(new SigningAccount(signer, sender))\n    }\n\n    if (await this._clientManager.isLocalNet()) {\n      const account = await this._kmdAccountManager.getOrCreateWalletAccount(name, fundWith)\n      return this.signerAccount(account.account)\n    }\n\n    throw new Error(`Missing environment variable ${name.toUpperCase()}_MNEMONIC when looking for account ${name}`)\n  }\n\n  /**\n   * Tracks and returns an Algorand account with private key loaded from the given KMD wallet (identified by name).\n   *\n   * @param name The name of the wallet to retrieve an account from\n   * @param predicate An optional filter to use to find the account (otherwise it will return a random account from the wallet)\n   * @param sender The optional sender address to use this signer for (aka a rekeyed account)\n   * @example Get default funded account in a LocalNet\n   *\n   * ```typescript\n   * const defaultDispenserAccount = await accountManager.fromKmd('unencrypted-default-wallet',\n   *   a => a.status !== 'Offline' && a.amount > 1_000_000_000\n   * )\n   * ```\n   * @returns The account\n   */\n  public async fromKmd(\n    name: string,\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    predicate?: (account: Record<string, any>) => boolean,\n    sender?: string | Address,\n  ) {\n    const account = await this._kmdAccountManager.getWalletAccount(name, predicate, sender)\n    if (!account) throw new Error(`Unable to find KMD account ${name}${predicate ? ' with predicate' : ''}`)\n    return this.signerAccount(account.account)\n  }\n\n  /**\n   * Tracks and returns an account that supports partial or full multisig signing.\n   *\n   * @example\n   * ```typescript\n   * const account = accountManager.multisig({version: 1, threshold: 1, addrs: [\"ADDRESS1...\", \"ADDRESS2...\"]},\n   *  [(await accountManager.fromEnvironment('ACCOUNT1')).account])\n   * ```\n   * @param multisigParams The parameters that define the multisig account\n   * @param signingAccounts The signers that are currently present\n   * @returns A multisig account wrapper\n   */\n  public multisig(multisigParams: algosdk.MultisigMetadata, signingAccounts: (algosdk.Account | SigningAccount)[]) {\n    return this.signerAccount(new MultisigAccount(multisigParams, signingAccounts))\n  }\n\n  /**\n   * Tracks and returns an account that represents a logic signature.\n   *\n   * @example\n   * ```typescript\n   * const account = accountManager.logicsig(program, [new Uint8Array(3, ...)])\n   * ```\n   * @param program The bytes that make up the compiled logic signature\n   * @param args The (binary) arguments to pass into the logic signature\n   * @returns A logic signature account wrapper\n   */\n  public logicsig(program: Uint8Array, args?: Array<Uint8Array>) {\n    return this.signerAccount(new LogicSigAccount(program, args))\n  }\n\n  /**\n   * Tracks and returns a new, random Algorand account with secret key loaded.\n   *\n   * @example\n   * ```typescript\n   * const account = accountManager.random()\n   * ```\n   * @returns The account\n   */\n  public random() {\n    return this.signerAccount(algosdk.generateAccount())\n  }\n\n  /**\n   * Returns an account (with private key loaded) that can act as a dispenser from\n   * environment variables, or against default LocalNet if no environment variables present.\n   *\n   * Note: requires a Node.js environment to execute.\n   *\n   * If present, it will load the account mnemonic stored in process.env.DISPENSER_MNEMONIC and optionally\n   * process.env.DISPENSER_SENDER if it's a rekeyed account.\n   *\n   * @example\n   * ```typescript\n   * const account = await accountManager.dispenserFromEnvironment()\n   * ```\n   *\n   * @returns The account\n   */\n  public async dispenserFromEnvironment() {\n    if (!process || !process.env) {\n      throw new Error('Attempt to get dispenser from environment from a non Node.js context; this is not supported!')\n    }\n\n    return process.env[`${DISPENSER_ACCOUNT.toUpperCase()}_MNEMONIC`]\n      ? await this.fromEnvironment(DISPENSER_ACCOUNT)\n      : await this.localNetDispenser()\n  }\n\n  /**\n   * Returns an Algorand account with private key loaded for the default LocalNet dispenser account (that can be used to fund other accounts).\n   *\n   * @example\n   * ```typescript\n   * const account = await accountManager.localNetDispenser()\n   * ```\n   * @returns The account\n   */\n  public async localNetDispenser() {\n    const dispenser = await this._kmdAccountManager.getLocalNetDispenserAccount()\n    return this.signerAccount(dispenser.account)\n  }\n\n  /**\n   * Rekey an account to a new address.\n   *\n   * **Note:** Please be careful with this function and be sure to read the [official rekey guidance](https://dev.algorand.co/concepts/accounts/rekeying).\n   *\n   * @param account The account to rekey\n   * @param rekeyTo The account address or signing account of the account that will be used to authorise transactions for the rekeyed account going forward.\n   *  If a signing account is provided that will now be tracked as the signer for `account` in this `AccountManager`\n   * @param options Any parameters to control the transaction or execution of the transaction\n   *\n   * @example Basic example (with string addresses)\n   * ```typescript\n   * await accountManager.rekeyAccount({account: \"ACCOUNTADDRESS\", rekeyTo: \"NEWADDRESS\"})\n   * ```\n   * @example Basic example (with signer accounts)\n   * ```typescript\n   * await accountManager.rekeyAccount({account: account1, rekeyTo: newSignerAccount})\n   * ```\n   * @example Advanced example\n   * ```typescript\n   * await accountManager.rekeyAccount({\n   *   account: \"ACCOUNTADDRESS\",\n   *   rekeyTo: \"NEWADDRESS\",\n   *   lease: 'lease',\n   *   note: 'note',\n   *   firstValidRound: 1000n,\n   *   validityWindow: 10,\n   *   extraFee: (1000).microAlgo(),\n   *   staticFee: (1000).microAlgo(),\n   *   // Max fee doesn't make sense with extraFee AND staticFee\n   *   //  already specified, but here for completeness\n   *   maxFee: (3000).microAlgo(),\n   *   maxRoundsToWaitForConfirmation: 5,\n   *   suppressLog: true,\n   * })\n   * ```\n   * @returns The result of the transaction and the transaction that was sent\n   */\n  async rekeyAccount(\n    account: string | Address,\n    rekeyTo: string | Address | TransactionSignerAccount,\n    options?: Omit<CommonTransactionParams, 'sender'> & SendParams,\n  ): Promise<SendSingleTransactionResult> {\n    const result = await this._getComposer()\n      .addPayment({\n        ...options,\n        sender: address(account),\n        receiver: address(account),\n        amount: AlgoAmount.MicroAlgo(0),\n        rekeyTo: address(typeof rekeyTo === 'object' && 'addr' in rekeyTo ? rekeyTo.addr : rekeyTo),\n      })\n      .send(options)\n\n    // If the rekey is a signing account set it as the signer for this account\n    if (typeof rekeyTo === 'object' && 'addr' in rekeyTo) {\n      this.rekeyed(account, rekeyTo)\n    }\n\n    Config.getLogger(options?.suppressLog).info(`Rekeyed ${account} to ${rekeyTo} via transaction ${result.txIds.at(-1)}`)\n\n    return { ...result, transaction: result.transactions.at(-1)!, confirmation: result.confirmations.at(-1)! }\n  }\n\n  private async _getEnsureFundedAmount(sender: Address, minSpendingBalance: AlgoAmount, minFundingIncrement?: AlgoAmount) {\n    const accountInfo = await this.getInformation(sender)\n    const currentSpendingBalance = accountInfo.balance.microAlgo - accountInfo.minBalance.microAlgo\n\n    const amountFunded = calculateFundAmount(minSpendingBalance.microAlgo, currentSpendingBalance, minFundingIncrement?.microAlgo ?? 0n)\n\n    return amountFunded === null ? undefined : AlgoAmount.MicroAlgo(amountFunded)\n  }\n\n  /**\n   * Funds a given account using a dispenser account as a funding source such that\n   * the given account has a certain amount of Algo free to spend (accounting for\n   * Algo locked in minimum balance requirement).\n   *\n   * https://dev.algorand.co/concepts/smart-contracts/costs-constraints#mbr\n   *\n   * @param accountToFund The account to fund\n   * @param dispenserAccount The account to use as a dispenser funding source\n   * @param minSpendingBalance The minimum balance of Algo that the account should have available to spend (i.e. on top of minimum balance requirement)\n   * @param options Optional parameters to control the funding increment, transaction or execution of the transaction\n   * @example Example using AlgorandClient\n   * ```typescript\n   * // Basic example\n   * await accountManager.ensureFunded(\"ACCOUNTADDRESS\", \"DISPENSERADDRESS\", algokit.algo(1))\n   * // With configuration\n   * await accountManager.ensureFunded(\"ACCOUNTADDRESS\", \"DISPENSERADDRESS\", algokit.algo(1),\n   *  { minFundingIncrement: algokit.algo(2), fee: (1000).microAlgo(), suppressLog: true }\n   * )\n   * ```\n   * @returns\n   * - The result of executing the dispensing transaction and the `amountFunded` if funds were needed.\n   * - `undefined` if no funds were needed.\n   */\n  async ensureFunded(\n    accountToFund: string | Address,\n    dispenserAccount: string | Address,\n    minSpendingBalance: AlgoAmount,\n    options?: {\n      minFundingIncrement?: AlgoAmount\n    } & SendParams &\n      Omit<CommonTransactionParams, 'sender'>,\n  ): Promise<(SendSingleTransactionResult & EnsureFundedResult) | undefined> {\n    const addressToFund = address(accountToFund)\n\n    const amountFunded = await this._getEnsureFundedAmount(addressToFund, minSpendingBalance, options?.minFundingIncrement)\n    if (!amountFunded) return undefined\n\n    const result = await this._getComposer()\n      .addPayment({\n        ...options,\n        sender: address(dispenserAccount),\n        receiver: addressToFund,\n        amount: amountFunded,\n      })\n      .send(options)\n\n    return {\n      ...result,\n      transaction: result.transactions[0],\n      confirmation: result.confirmations[0],\n      transactionId: result.txIds[0],\n      amountFunded: amountFunded,\n    }\n  }\n\n  /**\n   * Funds a given account using a dispenser account retrieved from the environment,\n   * per the `dispenserFromEnvironment` method, as a funding source such that\n   * the given account has a certain amount of Algo free to spend (accounting for\n   * Algo locked in minimum balance requirement).\n   *\n   * **Note:** requires a Node.js environment to execute.\n   *\n   * The dispenser account is retrieved from the account mnemonic stored in\n   * process.env.DISPENSER_MNEMONIC and optionally process.env.DISPENSER_SENDER\n   * if it's a rekeyed account, or against default LocalNet if no environment variables present.\n   *\n   * https://dev.algorand.co/concepts/smart-contracts/costs-constraints#mbr\n   *\n   * @param accountToFund The account to fund\n   * @param minSpendingBalance The minimum balance of Algo that the account should have available to spend (i.e. on top of minimum balance requirement)\n   * @param options Optional parameters to control the funding increment, transaction or execution of the transaction\n   * @example Example using AlgorandClient\n   * ```typescript\n   * // Basic example\n   * await accountManager.ensureFundedFromEnvironment(\"ACCOUNTADDRESS\", algokit.algo(1))\n   * // With configuration\n   * await accountManager.ensureFundedFromEnvironment(\"ACCOUNTADDRESS\", algokit.algo(1),\n   *  { minFundingIncrement: algokit.algo(2), fee: (1000).microAlgo(), suppressLog: true }\n   * )\n   * ```\n   * @returns\n   * - The result of executing the dispensing transaction and the `amountFunded` if funds were needed.\n   * - `undefined` if no funds were needed.\n   */\n  async ensureFundedFromEnvironment(\n    accountToFund: string | Address,\n    minSpendingBalance: AlgoAmount,\n    options?: {\n      minFundingIncrement?: AlgoAmount\n    } & SendParams &\n      Omit<CommonTransactionParams, 'sender'>,\n  ): Promise<(SendSingleTransactionResult & EnsureFundedResult) | undefined> {\n    const addressToFund = address(accountToFund)\n    const dispenserAccount = await this.dispenserFromEnvironment()\n\n    const amountFunded = await this._getEnsureFundedAmount(addressToFund, minSpendingBalance, options?.minFundingIncrement)\n    if (!amountFunded) return undefined\n\n    const result = await this._getComposer()\n      .addPayment({\n        ...options,\n        sender: dispenserAccount,\n        receiver: addressToFund,\n        amount: amountFunded,\n      })\n      .send(options)\n\n    return {\n      ...result,\n      transaction: result.transactions[0],\n      confirmation: result.confirmations[0],\n      transactionId: result.txIds[0],\n      amountFunded: amountFunded,\n    }\n  }\n\n  /**\n   * Funds a given account using the TestNet Dispenser API as a funding source such that\n   * the account has a certain amount of Algo free to spend (accounting for Algo locked\n   * in minimum balance requirement).\n   *\n   * https://dev.algorand.co/concepts/smart-contracts/costs-constraints#mbr\n   *\n   * @param accountToFund The account to fund\n   * @param dispenserClient The TestNet dispenser funding client\n   * @param minSpendingBalance The minimum balance of Algo that the account should have available to spend (i.e. on top of minimum balance requirement)\n   * @param options Optional parameters to control the funding increment, transaction or execution of the transaction\n   * @example Example using AlgorandClient\n   * ```typescript\n   * // Basic example\n   * await accountManager.ensureFundedFromTestNetDispenserApi(\"ACCOUNTADDRESS\", algorand.client.getTestNetDispenserFromEnvironment(), algokit.algo(1))\n   * // With configuration\n   * await accountManager.ensureFundedFromTestNetDispenserApi(\"ACCOUNTADDRESS\", algorand.client.getTestNetDispenserFromEnvironment(), algokit.algo(1),\n   *  { minFundingIncrement: algokit.algo(2) }\n   * )\n   * ```\n   * @returns\n   * - The result of executing the dispensing transaction and the `amountFunded` if funds were needed.\n   * - `undefined` if no funds were needed.\n   */\n  async ensureFundedFromTestNetDispenserApi(\n    accountToFund: string | Address,\n    dispenserClient: TestNetDispenserApiClient,\n    minSpendingBalance: AlgoAmount,\n    options?: {\n      minFundingIncrement?: AlgoAmount\n    },\n  ): Promise<EnsureFundedResult | undefined> {\n    if (!(await this._clientManager.isTestNet())) {\n      throw new Error('Attempt to fund using TestNet dispenser API on non TestNet network.')\n    }\n\n    const addressToFund = address(accountToFund)\n\n    const amountFunded = await this._getEnsureFundedAmount(addressToFund, minSpendingBalance, options?.minFundingIncrement)\n    if (!amountFunded) return undefined\n\n    const result = await dispenserClient.fund(addressToFund, amountFunded.microAlgo)\n    return {\n      amountFunded: AlgoAmount.MicroAlgo(result.amount),\n      transactionId: result.txId,\n    }\n  }\n}\n"],"mappings":";;;;;;;;AAUO,IAAA,kBAAkB,QAAQ;AAIjC,MAAM,WAAW,YAA+B,OAAO,YAAY,WAAW,QAAQ,WAAW,OAAO,IAAI;;;;;;;;;;;AAoB5G,MAAa,8BAA8B,QAAQ,SACjD,SACmB;CACnB,OAAO,YAAY,UACf,QAAQ,SACR,UAAU,UACR,QAAQ,qCAAqC,OAAO,IACpD,QAAQ,kCAAkC,OAAO;AACzD,CAAC;;AAGD,IAAa,iBAAb,MAA4B;CAC1B;CACA;CACA,YAAqE,CAAC;CACtE;;;;;;;;;CAUA,YAAY,eAA8B;EACxC,KAAK,iBAAiB;EACtB,KAAK,qBAAqB,IAAI,kBAAkB,aAAa;CAC/D;CAEA,aAAqB,oBAA6D;EAChF,OAAO,IAAI,oBAAoB;GAC7B,OAAO,KAAK,eAAe;GAC3B,WAAW,KAAK,UAAU,KAAK,IAAI;GACnC,oBAAoB,6BAA6B,KAAK,eAAe,MAAM,qBAAqB,CAAC,CAAC,GAAG;EACvG,CAAC;CACH;;;;;;;;;CAUA,IAAW,MAAM;EACf,OAAO,KAAK;CACd;;;;;;;;;;;;;;;;;CAkBA,iBAAwB,QAA8E;EACpG,KAAK,iBAAiB,YAAY,SAAS,OAAO,SAAS;EAC3D,OAAO;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