Reputation: 147
Here is the code snippet below :-
while (block_no >= 0) {
List<EthBlock.TransactionResult> txs = web3
.ethGetBlockByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(block_no)), true).send()
.getBlock().getTransactions();
txs.forEach(tx -> {
int i = 0;
EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx.get();
if ((transaction.getFrom().toLowerCase()).equals(address.toLowerCase())) {
// System.out.println("***************GETTING INSDIE OF IF LOOP***********");
ts[i] = new TransactionHistory();
ts[i].setFrom(transaction.getFrom());
ts[i].setTo(transaction.getTo());//not getting exact address except contract deployed address
ts[i].setBlockNumber("" + transaction.getBlockNumber());
ts[i].setGasPrice("" + transaction.getGasPrice());
ts[i].setNonce("" + transaction.getNonce());
history.add(ts[i]);
i++;
System.out.println("*******" + "\nValue Getting zero value" +
transaction.getvalue() + "\nBlockNumber: "
+ transaction.getBlockNumber() + "\n From: " +
transaction.getFrom() + "\n To:"
+ transaction.getTo() + "\n Nonce: " +
transaction.getNonce() + "\n BlockHash:"
+ transaction.getBlockHash() + "\n GasPrice:" +
transaction.getGasPrice());
//getting '0' instead of real value
System.out.println(transaction.getValue());
}
How can i fetch transaction value and sender's address using java and web3js eth transaction object ?
Upvotes: 0
Views: 798
Reputation: 1357
You have to listen to your smart contract events. Events are stored as logs within the ethereum virtual machine. Web3j and your Contract wrapper provide some methods to read past logs and/or listen to new ones.
If you want to read all events which occurred in the past, you can use ethGetLogs
method provided by Web3j. The result contains a List of logs with some properties about the transaction. For you, the interesting field is the topics field, which is a List of Strings and should contain the sender and receiver address if the event is some transfer event.
YourContract contract // init contract
Web3j web3j // init web3j
EthFilter ethFilter = new EthFilter(DefaultBlockParameterName.EARLIEST,
DefaultBlockParameterName.LATEST, contract.getContractAddress());
ethFilter.addSingleTopic(EventEncoder.encode(contract.YOUR_EVENT));
EthLog eventLog = web3j.ethGetLogs(ethFilter).send();
The other way is to subscribe to event logs. Therefore your contract wrapper and web3j provide some possibilities.
yourContract.xxxEventFlowable(ethFilter).subscribe(/*doSomthing*/);
or
web3j.ethLogFlowable(ethFilter).subscribe(/*doSomthing*/);
Upvotes: 2