* @param {Rpc|string|URL} rpc - RPC node information required to refresh accounts, calculate PoW, and process blocks
* @param {(Wallet)} wallet - Wallet from which to sweep funds
* @param {string} recipient - Destination address for all swept funds
-* @param {number} from - Starting account index to sweep
-* @param {number} to - Ending account index to sweep
+* @param {number} [from=0] - Starting account index to sweep
+* @param {number} [to=from] - Ending account index to sweep
* @returns An array of results including both successes and failures
*/
export async function sweep (
if (!(rpc instanceof Rpc)) {
throw new TypeError('RPC must be a valid node')
}
+
const blockQueue: Promise<void>[] = []
const results: SweepResult[] = []
-
const recipientAccount = Account.load(recipient)
const accounts = await wallet.refresh(rpc, from, to)
+
for (const account of accounts) {
- if (account.representative?.address && account.frontier_block && account.index != null) {
- const block = await new Block(account)
- .send(recipientAccount, account.balance ?? 0n)
- .sign(wallet, account.index)
- const blockRequest: Promise<void> = new Promise(async (resolve) => {
- try {
- await block.pow()
- const hash = await block.process(rpc)
- results.push({ status: 'success', address: block.account.address, message: hash })
- } catch (err: any) {
- results.push({ status: 'error', address: block.account.address, message: err.message })
- } finally {
- resolve()
+ const blockRequest: Promise<void> = new Promise(async (resolve) => {
+ let block
+ try {
+ if (account.index == null) {
+ throw new TypeError('Account index is required', { cause: account })
}
- })
- blockQueue.push(blockRequest)
- }
+ block = await new Block(account)
+ .send(recipientAccount, account.balance ?? 0n)
+ .sign(wallet, account.index)
+ await block.pow()
+ const hash = await block.process(rpc)
+ results.push({ status: 'success', address: block.account.address, message: hash })
+ } catch (err: any) {
+ results.push({ status: 'error', address: account.address, message: err.message })
+ } finally {
+ resolve()
+ }
+ })
+ blockQueue.push(blockRequest)
}
await Promise.allSettled(blockQueue)
return results