Проблема, связанная с событиями обстрела в узле JS - PullRequest
0 голосов
/ 01 июня 2018

var events = require('events');

const express = require('express');
const router = express.Router();
const tokenbalance = require('./tokenbalance')

//const accCollection = require('../models/account.js');
const keythereum = require("keythereum");
const request = require("request");
const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const config = require('../../config');
const log = require('log4js').getLogger("tokenadmin");
var erc20Abi = [
	{
		"constant": true,
		"inputs": [],
		"name": "name",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_spender",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "approve",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "totalSupply",
		"outputs": [
			{
				"name": "",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_from",
				"type": "address"
			},
			{
				"name": "_to",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "transferFrom",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "decimals",
		"outputs": [
			{
				"name": "",
				"type": "uint8"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "version",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [
			{
				"name": "_owner",
				"type": "address"
			}
		],
		"name": "balanceOf",
		"outputs": [
			{
				"name": "balance",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "symbol",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_to",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "transfer",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_spender",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			},
			{
				"name": "_extraData",
				"type": "bytes"
			}
		],
		"name": "approveAndCall",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [
			{
				"name": "_owner",
				"type": "address"
			},
			{
				"name": "_spender",
				"type": "address"
			}
		],
		"name": "allowance",
		"outputs": [
			{
				"name": "remaining",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "fallback"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"name": "_from",
				"type": "address"
			},
			{
				"indexed": true,
				"name": "_to",
				"type": "address"
			},
			{
				"indexed": false,
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "Transfer",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"name": "_owner",
				"type": "address"
			},
			{
				"indexed": true,
				"name": "_spender",
				"type": "address"
			},
			{
				"indexed": false,
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "Approval",
		"type": "event"
	}
]
const Abiarray = erc20Abi;
console.log(Abiarray);
const web3 = new Web3(new Web3.providers.HttpProvider(config.rpcURL));



//event Transfer(myAddress,toAddress,amount);



let Tokenadmin ={
    tokenadmin :function(toAddress,myAddress,amount,contractAddress,callback) {
		//set from address,to address and token amount
		
		let tokena = web3.eth.contract(Abiarray).at(contractAddress);
		// console.log(tokena);
		console.log("bbbbbbbbbbbb");

         console.log(toAddress)
        console.log(myAddress)
         console.log(amount)
		console.log(contractAddress)
		amount1 = web3.toHex(amount)//To convert any given value to HEX
        console.log("Amount to transfer" +amount)
        
        tokena.balanceOf.call(myAddress, function (err, balance) {

         console.log("BALNCE B4 TRANSFER" +balance);
              
			})
			tokena.balanceOf.call(toAddress,function(err,result) {
				console.log("BALANCE B4 TRANSFER OF TOADDRESS"+result);
			})
        
    
               
        var privatekey = new Buffer('cc479124b293d2abd98ea4a57f2670ef7671c90d1eaa382258618d23440b12c2', 'hex')
       

        // //To get nonce
        // get transaction count, later will used as nonce
        web3.eth.getTransactionCount(myAddress,function(err,v) {
            console.log(v); 
			var count = v;
		
        
    
       console.log(toAddress,"aaaaaaaaaa", amount);
        var rawTransaction = {"from":myAddress, 
                              "gasPrice":web3.toHex(2 * 1e9),
                              "gasLimit":web3.toHex(210000),
                              "to": contractAddress,
                              "value":"0x0",
                              //"data" :tokena,
                              "data" : tokena.transfer.getData(toAddress,amount1),
							  "nonce":web3.toHex(count),
							  "chainid" : "0x04"
                              }
                              //console.log(rawTransaction);
        var transaction = new Tx(rawTransaction);
		transaction.sign(privatekey);
		
		let serializedTx = transaction.serialize();

		
		
    
        web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
			console.log("Response",err,hash);
            if (!err){
				console.log(hash);
				//filter.emit('Transfer','Event emitted')
				
					}
					
					
            else
                console.log("HASHERROR"+err);
				return callback ({hash:hash})
				
        //})
		});
		

			let filter =web3.eth.filter('Transfer',{fromBlock:2383351,toBlock:'latest'})
			console.log("Filter" +filter);
		     // watch for changes
            filter.watch(function(error, result){
	        if (!error)
	        console.log(result);
			});



        

        tokena.balanceOf.call(myAddress, function (err, balance) {

            console.log("BALANCE AFTER "+balance);
          
		})
		
   }) 
}

}
		module.exports =Tokenadmin;

Я хочу использовать событие Transfer (контракт erc20) в моем файле js, чтобы получить подробные данные транзакции для получения подробных данных о транзакции передачи токена. Я передал abi erc20Контракт токена в коде js. Также работает передаточная функция.Для передачи события я попытался использовать 1) .getpastevents, 2) .watch, 3) .allevents 4) .web3.eth.filter в своем коде js узла.В любом случае я мог видеть журнал событий в myetherscan.Также событие переноса есть в договоре erc20 abi.Но не смог увидеть журнал событий передачи в моей консоли и почтальоне.

Может кто-нибудь помочь, пожалуйста, решить эту проблему?

1 Ответ

0 голосов
/ 11 июня 2018

Я разобрал проблему. Это потому, что Infura не поддерживает события и фильтры. Поэтому я использовал другой метод, использующий web3 для решения этой проблемы. И наконец-то получил ее решение. Спасибо!Ана

...