You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过Web3.js或Web3.py获取BSC链上AA地址的全量交易(含Mint、Burn操作)

Got it, let's fix this. The BSCScan API's lack of support for non-transfer transactions like mint/burn is a real pain, but Web3.js and Web3.py give you the tools to pull all on-chain activity tied to your address. Here's how to do it step by step:

Using Web3.js

Method 1: Fetch All Transactions (Including Contract Interactions)

This approach pulls every transaction where your address is either the sender (from) or recipient (to), then decodes the input data to identify mint/burn operations.

First, initialize your Web3 connection to a BSC node (we'll use Binance's public node here):

const Web3 = require('web3');
const web3 = new Web3('https://bsc-dataseed.binance.org/');

Next, write a function to fetch transactions across blocks (we batch 1000 blocks at a time to avoid hitting node limits):

async function getAllTransactions(targetAddress, startBlock = 0, endBlock = 'latest') {
  let allTxs = [];
  const finalEndBlock = endBlock === 'latest' ? await web3.eth.getBlockNumber() : endBlock;
  let currentBlock = finalEndBlock;

  while (currentBlock >= startBlock) {
    const batchEnd = currentBlock;
    const batchStart = Math.max(startBlock, currentBlock - 1000);

    // Loop through each block in the batch and pull relevant transactions
    for (let blockNum = batchStart; blockNum <= batchEnd; blockNum++) {
      try {
        const block = await web3.eth.getBlock(blockNum, true); // true = include full transaction details
        if (!block || !block.transactions) continue;

        // Filter transactions where target address is from or to
        const relevantTxs = block.transactions.filter(tx => 
          tx.from.toLowerCase() === targetAddress.toLowerCase() || 
          (tx.to && tx.to.toLowerCase() === targetAddress.toLowerCase())
        );
        allTxs.push(...relevantTxs);
      } catch (err) {
        console.log(`Skipping block ${blockNum}: ${err.message}`);
      }
    }

    currentBlock = batchStart - 1;
  }

  return allTxs;
}

Now, call this function and decode transaction inputs to spot mint/burn operations. You'll need the ABI of the contracts your address interacts with (grab this from BSCScan's contract page):

// Replace with your target address and contract ABI
const targetAddr = '0xYourAAAddressHere';
const erc20ABI = [/* Paste your contract's ABI here */];

getAllTransactions(targetAddr).then(txs => {
  txs.forEach(tx => {
    // Skip empty input (simple ETH/BNB transfers)
    if (tx.input === '0x') return;

    try {
      const contract = new web3.eth.Contract(erc20ABI, tx.to);
      const decoded = contract.decodeFunctionData(tx.input);
      
      console.log(`Tx ${tx.hash}: ${decoded.methodName} operation`);
      if (decoded.methodName === 'mint' || decoded.methodName === 'burn') {
        console.log(`✅ Found ${decoded.methodName} transaction: ${tx.hash}`);
      }
    } catch (err) {
      // Handle non-standard contracts or unknown methods
      console.log(`Could not decode tx ${tx.hash}: ${err.message}`);
    }
  });
});

Method 2: Listen for Transfer Events (Mint/Burn Proxy)

Most mint operations emit a Transfer event from the zero address (0x0000000000000000000000000000000000000000) to your address, while burns emit a Transfer from your address to the zero address. You can directly fetch these events:

async function fetchMintBurnEvents(targetAddr) {
  const transferEventABI = [
    {"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"}
  ];

  // Replace with the contract address you care about (e.g., the token contract)
  const contractAddr = '0xB8c77482e45F1F44dE1745F52C74426C631bDD52';
  const contract = new web3.eth.Contract(transferEventABI, contractAddr);

  // Fetch mint events (from zero address to target)
  const mintEvents = await contract.getPastEvents('Transfer', {
    fromBlock: 0,
    toBlock: 'latest',
    filter: { from: '0x0000000000000000000000000000000000000000', to: targetAddr }
  });
  console.log('Mint Events:', mintEvents);

  // Fetch burn events (from target to zero address)
  const burnEvents = await contract.getPastEvents('Transfer', {
    fromBlock: 0,
    toBlock: 'latest',
    filter: { from: targetAddr, to: '0x0000000000000000000000000000000000000000' }
  });
  console.log('Burn Events:', burnEvents);
}

// Call the function
fetchMintBurnEvents(targetAddr);
Using Web3.py

Method 1: Fetch & Decode All Transactions

Similar to the Web3.js approach, we'll pull relevant transactions and decode inputs to identify mint/burn operations.

First, set up your Web3 connection:

from web3 import Web3

# Connect to BSC public node
w3 = Web3(Web3.HTTPProvider('https://bsc-dataseed.binance.org/'))

Write a function to fetch transactions across blocks:

def get_all_transactions(target_address, start_block=0, end_block='latest'):
    all_txs = []
    final_end_block = w3.eth.block_number if end_block == 'latest' else end_block
    current_block = final_end_block

    while current_block >= start_block:
        batch_end = current_block
        batch_start = max(start_block, current_block - 1000)

        for block_num in range(batch_start, batch_end + 1):
            try:
                block = w3.eth.get_block(block_num, full_transactions=True)
                if not block or not block.transactions:
                    continue

                # Filter transactions involving target address
                relevant_txs = [
                    tx for tx in block.transactions
                    if tx['from'].lower() == target_address.lower()
                    or (tx['to'] is not None and tx['to'].lower() == target_address.lower())
                ]
                all_txs.extend(relevant_txs)
            except Exception as e:
                print(f"Skipping block {block_num}: {str(e)}")

        current_block = batch_start - 1

    return all_txs

Decode transactions to find mint/burn operations (again, use the contract's ABI from BSCScan):

target_addr = '0xYourAAAddressHere'
erc20_abi = [
    # Paste your contract's ABI here (include mint/burn functions and Transfer event)
    {
        "inputs": [{"internalType": "address", "name": "to", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}],
        "name": "mint",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [{"internalType": "uint256", "name": "amount", "type": "uint256"}],
        "name": "burn",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    }
]

all_txs = get_all_transactions(target_addr)

for tx in all_txs:
    if tx['input'] == '0x':
        continue

    try:
        contract = w3.eth.contract(address=tx['to'], abi=erc20_abi)
        func, params = contract.decode_function_input(tx['input'])
        
        print(f"Tx {tx['hash'].hex()}: {func.fn_name} operation")
        if func.fn_name in ['mint', 'burn']:
            print(f"✅ Found {func.fn_name} transaction: {tx['hash'].hex()}")
    except Exception as e:
        print(f"Could not decode tx {tx['hash'].hex()}: {str(e)}")

Method 2: Fetch Mint/Burn via Transfer Events

Use the same zero-address trick to pull mint/burn events directly:

def fetch_mint_burn_events(target_addr):
    transfer_event_abi = [
        {"anonymous":False,"inputs":[{"indexed":True,"internalType":"address","name":"from","type":"address"},{"indexed":True,"internalType":"address","name":"to","type":"address"},{"indexed":False,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"}
    ]

    # Replace with your target contract address
    contract_addr = '0xB8c77482e45F1F44dE1745F52C74426C631bDD52'
    contract = w3.eth.contract(address=contract_addr, abi=transfer_event_abi)

    # Fetch mint events
    mint_events = contract.events.Transfer.get_logs(
        fromBlock=0,
        toBlock='latest',
        argument_filters={'from': '0x0000000000000000000000000000000000000000', 'to': target_addr}
    )
    print("Mint Events:", mint_events)

    # Fetch burn events
    burn_events = contract.events.Transfer.get_logs(
        fromBlock=0,
        toBlock='latest',
        argument_filters={'from': target_addr, 'to': '0x0000000000000000000000000000000000000000'}
    )
    print("Burn Events:", burn_events)

# Call the function
fetch_mint_burn_events(target_addr)

Key Notes

  • Node Limits: Public BSC nodes may throttle your requests. Add delays between batch calls, or use a paid node service for faster, more reliable access.
  • ABI Requirements: You need the contract's ABI to decode transactions/events. Grab this from BSCScan's contract page under "Contract ABI".
  • Non-Standard Contracts: Some tokens use custom mint/burn functions or events. If the above methods don't catch them, check the contract's source code to find the correct function signatures or event definitions.
  • Efficiency: Querying from block 0 will take a long time. Instead, track the last block you queried and only pull new blocks going forward.

内容的提问来源于stack exchange,提问作者Talha Yazılım

火山引擎 最新活动