Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: batch transfer #30

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { deployCommand } from "../src/commands/deploy.js";
import { verifyCommand } from "../src/commands/verify.js";
import { ReadContract } from "../src/commands/contract.js";
import { bridgeCommand } from "../src/commands/bridge.js";
import { batchTransferCommand } from "../src/commands/batchTransfer.js";

interface CommandOptions {
testnet?: boolean;
Expand All @@ -22,6 +23,7 @@ interface CommandOptions {
json?: any;
name?: string;
decodedArgs?: any;
file?: string;
}

const orange = chalk.rgb(255, 165, 0);
Expand Down Expand Up @@ -130,6 +132,7 @@ program
options.address!,
options.name!,
!!options.testnet,

args
);
});
Expand All @@ -151,4 +154,17 @@ program
await bridgeCommand(!!options.testnet);
});

program
.command("batch-transfer")
.description("Execute batch transactions from a file")
.requiredOption("-f, --file <file>", "Path to the batch file")
.option("-t, --testnet", "Execute on the testnet")
.action(async (options: CommandOptions) => {
try {
await batchTransferCommand(options.file!, !!options.testnet);
} catch (error) {
console.error(chalk.red("Error during batch processing:"), error);
}
});

program.parse(process.argv);
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"wallet": "pnpm run build && node dist/bin/index.js wallet",
"balance": "pnpm run build && node dist/bin/index.js balance",
"transfer": "pnpm run build && node dist/bin/index.js transfer --testnet --address 0xa5f45f5bddefC810C48aCC1D5CdA5e5a4c6BC59E --value 0.001",
"tx-status": "pnpm run build && node dist/bin/index.js tx --testnet --txid 0x876a0a9b167889350c41930a4204e5d9acf5704a7f201447a337094189af961c4"
"tx-status": "pnpm run build && node dist/bin/index.js tx --testnet --txid 0x876a0a9b167889350c41930a4204e5d9acf5704a7f201447a337094189af961c4",
"batch-transfer": "pnpm run build && node dist/bin/index.js batch-transfer --testnet --file"
},
"keywords": [
"rootstock",
Expand Down
99 changes: 99 additions & 0 deletions src/commands/batchTransfer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import fs from "fs";
import chalk from "chalk";
import ora from "ora";
import { walletFilePath } from "../utils/constants.js";
import ViemProvider from "../utils/viemProvider.js";

export async function batchTransferCommand(filePath: string, testnet: boolean) {
try {
if (!fs.existsSync(filePath)) {
console.log(chalk.red("🚫 Batch file not found. Please provide a valid file."));
return;
}

const batchData = JSON.parse(fs.readFileSync(filePath, "utf8"));

if (!Array.isArray(batchData) || batchData.length === 0) {
console.log(chalk.red("⚠️ Invalid batch data. Please check the file content."));
return;
}

if (!fs.existsSync(walletFilePath)) {
console.log(chalk.red("🚫 No saved wallet found. Please create a wallet first."));
return;
}

const walletsData = JSON.parse(fs.readFileSync(walletFilePath, "utf8"));

if (!walletsData.currentWallet || !walletsData.wallets) {
console.log(chalk.red("⚠️ No valid wallet found. Please create or import a wallet first."));
throw new Error();
}

const { currentWallet, wallets } = walletsData;
const wallet = wallets[currentWallet];
const { address: walletAddress } = wallet;

if (!walletAddress) {
console.log(chalk.red("⚠️ No valid address found in the saved wallet."));
return;
}

const provider = new ViemProvider(testnet);
const publicClient = await provider.getPublicClient();
const balance = await publicClient.getBalance({ address: walletAddress });

const rbtcBalance = Number(balance) / 10 ** 18;
console.log(chalk.white(`📄 Wallet Address:`), chalk.green(walletAddress));
console.log(chalk.white(`💰 Current Balance:`), chalk.green(`${rbtcBalance} RBTC`));

for (const transfer of batchData) {
const { to, value } = transfer;
if (!to || !value) {
console.log(chalk.red("⚠️ Invalid transaction data in batch. Skipping..."));
continue;
}

if (rbtcBalance < value) {
console.log(chalk.red(`🚫 Insufficient balance to transfer ${value} RBTC.`));
break;
}

const walletClient = await provider.getWalletClient();
const account = walletClient.account;
if (!account) {
console.log(chalk.red("⚠️ Failed to retrieve the account. Skipping this transaction."));
continue;
}

const txHash = await walletClient.sendTransaction({
account: account,
chain: provider.chain,
to: to,
value: BigInt(Math.floor(value * 10 ** 18)),
});

console.log(chalk.white(`🔄 Transaction initiated. TxHash:`), chalk.green(txHash));

const spinner = ora("⏳ Waiting for confirmation...").start();

const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
spinner.stop();

if (receipt.status === "success") {
console.log(chalk.green("✅ Transaction confirmed successfully!"));
console.log(chalk.white(`📦 Block Number:`), chalk.green(receipt.blockNumber));
console.log(chalk.white(`⛽ Gas Used:`), chalk.green(receipt.gasUsed.toString()));

const explorerUrl = testnet
? `https://explorer.testnet.rootstock.io/tx/${txHash}`
: `https://explorer.rootstock.io/tx/${txHash}`;
console.log(chalk.white(`🔗 View on Explorer:`), chalk.dim(`${explorerUrl}`));
} else {
console.log(chalk.red("❌ Transaction failed."));
}
}
} catch (error: any) {
console.error(chalk.red("🚨 Error during batch transfer:"), chalk.yellow(error.message || "Unknown error"));
}
}