So I tried to retrieve the events generated by my smartcontract
var abi = [{
"constant": false,
"inputs": [{
"name": "_value",
"type": "int32"
}],
"name": "changeLowerTrigger",
"outputs": [],
"payable": false,
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "metric",
"outputs": [{
"name": "name",
"type": "string",
"value": "place_holder_metric_name_to_be_autogenerated"
}, {
"name": "value",
"type": "int32",
"value": "7"
}],
"payable": false,
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_value",
"type": "int32"
}],
"name": "changeUpperTrigger",
"outputs": [],
"payable": false,
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_value",
"type": "int32"
}],
"name": "update",
"outputs": [],
"payable": false,
"type": "function"
}, {
"anonymous": false,
"inputs": [{
"indexed": false,
"name": "_value",
"type": "int32"
}],
"name": "ValueChanged",
"type": "event"
}, {
"anonymous": false,
"inputs": [{
"indexed": false,
"name": "_alarm",
"type": "string"
}, {
"indexed": false,
"name": "_value",
"type": "int32"
}],
"name": "Alarm",
"type": "event"
}]
var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at(
'0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9');
var events = myContractInstance.allEvents();
// watch for changes
events.watch(function(error, event) {
if (!error)
console.log(event);
});
// Or pass a callback to start watching immediately
var events = myContractInstance.allEvents(function(error, log) {
console.log(err, log);
});
But it returns only:
> events
{
callbacks: [function(error, log)],
filterId: "0xd6af6f5a7273fe21452f00c4682456",
getLogsCallbacks: [],
implementation: {
getLogs: function(),
newFilter: function(),
poll: function(),
uninstallFilter: function()
},
options: {
address: "0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9",
from: undefined,
fromBlock: undefined,
to: undefined,
toBlock: undefined,
topics: []
},
pollFilters: [],
requestManager: {
polls: {
0xd6af6f5a7273fe21452f00c4682456: {
data: {...},
id: "0xd6af6f5a7273fe21452f00c4682456",
callback: function(error, messages),
uninstall: function()
}
},
provider: {
newAccount: function(),
send: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),
sendAsync: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),
sign: function(),
unlockAccount: function()
},
timeout: {},
poll: function(),
reset: function(keepIsSyncing),
send: function(data),
sendAsync: function(data, callback),
sendBatch: function(data, callback),
setProvider: function(p),
startPolling: function(data, pollId, callback, uninstall),
stopPolling: function(pollId)
},
formatter: function(),
get: function(callback),
stopWatching: function(callback),
watch: function(callback)
}
But what I want, is the events shown in the next image at the very bottom(e.g.Value Changed value:7):
Since the events are displayed in the ETH-Wallet there should be a way. I rly just want a way to get the latest events in the geth console (or sth similare).
Thanks for any help I'm kinda lost and having some of the worst googling of my life.
All you need to do is to call get() on the result object you've got and posted in your answer. Its described in official documentation and can be found here
Related
I'm trying to send the content of a JSON file into Elasticsearch.
Each file contains only one simple JSON object (just attributes, no array, no nested objects). Filebeat sees the files but they're not sent to Elasticsearch (it's working with csv files so the connection is correct)...
Here is the JSON file (all in one line in the file but I passed it into a JSON formatter to be displayed here):
{
"IPID": "3782",
"Agent": "localhost",
"User": "vtom",
"Script": "/opt/vtom/scripts/scriptOK.ksh",
"Arguments": "",
"BatchQueue": "queue_ksh-json",
"VisualTOMServer": "labc",
"Job": "testJSONlogs",
"Application": "test_CAD",
"Environment": "TEST",
"JobRetry": "0",
"LabelPoint": "0",
"ExecutionMode": "NORMAL",
"DateName": "TEST_CAD",
"DateValue": "05/11/2022",
"DateStart": "2022-11-05",
"TimeStart": "20:58:14",
"StandardOutputName": "/opt/vtom/logs/TEST_test_CAD_testJSONlogs_221105-205814.o",
"StandardOutputContent": "_______________________________________________________________________\nVisual TOM context of the job\n \nIPID : 3782\nAgent : localhost\nUser : vtom\nScript : ",
"ErrorOutput": "/opt/vtom/logs/TEST_test_CAD_testJSONlogs_221105-205814.e",
"ErrorOutputContent": "",
"JsonOutput": "/opt/vtom/logs/TEST_test_CAD_testJSONlogs_221105-205814.json",
"ReturnCode": "0",
"Status": "Finished"
}
The input definition in Filebeat is (it's a merge of data from different web sources):
- type: filestream
id: vtomlogs
enabled: true
paths:
- /opt/vtom/logs/*.json
index: vtomlogs-%{+YYYY.MM.dd}
parsers:
- ndjson:
keys_under_root: true
overwrite_keys: true
add_error_key: true
expand_keys: true
The definition of the index template:
{
"properties": {
"IPID": {
"coerce": true,
"index": true,
"ignore_malformed": false,
"store": false,
"type": "integer",
"doc_values": true
},
"VisualTOMServer": {
"type": "keyword"
},
"Status": {
"type": "keyword"
},
"Agent": {
"type": "keyword"
},
"Script": {
"type": "text"
},
"User": {
"type": "keyword"
},
"ErrorOutputContent": {
"type": "text"
},
"ReturnCode": {
"type": "integer"
},
"BatchQueue": {
"type": "keyword"
},
"StandardOutputName": {
"type": "text"
},
"DateStart": {
"format": "yyyy-MM-dd",
"index": true,
"ignore_malformed": false,
"store": false,
"type": "date",
"doc_values": true
},
"Arguments": {
"type": "text"
},
"ExecutionMode": {
"type": "keyword"
},
"DateName": {
"type": "keyword"
},
"TimeStart": {
"format": "HH:mm:ss",
"index": true,
"ignore_malformed": false,
"store": false,
"type": "date",
"doc_values": true
},
"JobRetry": {
"type": "integer"
},
"LabelPoint": {
"type": "keyword"
},
"DateValue": {
"format": "dd/MM/yyyy",
"index": true,
"ignore_malformed": false,
"store": false,
"type": "date",
"doc_values": true
},
"JsonOutput": {
"type": "text"
},
"StandardOutputContent": {
"type": "text"
},
"Environment": {
"type": "keyword"
},
"ErrorOutput": {
"type": "text"
},
"Job": {
"type": "keyword"
},
"Application": {
"type": "keyword"
}
}
}
The file is seen by Filebeat but it does nothing with it...
0100","log.logger":"input.filestream","log.origin":{"file.name":"filestream/prospector.go","file.line":177},"message":"A new file /opt/vtom/logs/TEST_test_CAD_testJSONlogs_221106-124138.json has been found","service.name":"filebeat","id":"vtomlogs","prospector":"file_prospector","operation":"create","source_name":"native::109713280-64768","os_id":"109713280-64768","new_path":"/opt/vtom/logs/TEST_test_CAD_testJSONlogs_221106-124138.json","ecs.version":"1.6.0"}
My version of Elasticsearch is: 8.4.3
My version of Filebeat is: 8.5.0 (with allow_older_versions: true in my configuration file)
Thanks for your help
I'm trying to initiate a contract in this way:
function initContract() {
var contractJSON = $.getJSON("contract.json", function (data) {
return data;
});
return new web3.eth.Contract(contractJSON);
}
I've also tried with
return new web3.eth.Contract(JSON.parse(contractJSON));
But I don't think that second option is necesary.
I have a large contract.json file, so I only post a part of it:
{
"contractName": "contract",
"abi": [
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint256",
"name": "id",
"type": "uint256"
},
{
"indexed": false,
"internalType": "string",
"name": "hash",
"type": "string"
},
{
"indexed": false,
"internalType": "string",
"name": "nombre",
"type": "string"
},
{
"indexed": false,
"internalType": "string",
"name": "organizacion",
"type": "string"
},
{
"indexed": false,
"internalType": "string",
"name": "descripcion",
"type": "string"
},
{
"indexed": false,
"internalType": "address payable",
"name": "autor",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "donacionRecibida",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "donacionRequerida",
"type": "uint256"
}
],
"name": "proyectoDonado",
"type": "event"
},
...
I don't know if $getJSON needs the path of the json file as an argument, or just the name as I have it. I've seen it writen both ways in different pages. Either way I get this error:
Uncaught Error: You must provide the json interface of the contract when instantiating a contract object.
at Object.ContractMissingABIError (web3.min.js:30304)
Hope someone can help me!
I had the same error The fix was to provide the abi property of the interface object to web3.eth.Contract instead of the whole object. E.g:
//Get the JSON abi interface definition in whichever way you prefer into an object.
let myInterface = require('../my_contracts/my_contract_interface.json')
//Pass in the abi property of the object
let contract = new this.web3.eth.Contract(myInterface.abi)
Getting below error while signing the transaction on ethereum network:
E:\Web3\node_modules\ethereumjs-util\dist\index.js:369
var sig = secp256k1.sign(msgHash, privateKey);
^
RangeError: private key length is invalid
at Object.exports.ecsign (E:\Web3\node_modules\ethereumjs-util\dist\index.js:369:23)
at Transaction.sign (E:\Web3\node_modules\ethereumjs-tx\es5\index.js:252:23)
at Object.web3.eth.getTransactionCount [as callback] (E:\Web3\app3.js:264:8)
at sendTxCallback (E:\Web3\node_modules\web3-core-method\src\index.js:484:29)
at E:\Web3\node_modules\web3-core-requestmanager\src\index.js:147:9
And here is the web3 code responsible for this error. I am converting the private key values to 'hex' representation but it still not working out.
const Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/tBIZU6erdu0roIzShVDM')
const account1='0xceAbcE5eE63212e7d4fAf9eB522d2B7b5886bF1F'
const account2='0x5F16088a3dec5c07E02317B403472c9ff5335912'
console.log(process.env.PRIVATE_KEY_1)
const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1, 'hex')
const privateKey2 = Buffer.from(process.env.PRIVATE_KEY_2, 'hex')
console.log(privateKey1)
console.log(privateKey2)
contractABI = [
{
"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": "standard",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "",
"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": true,
"inputs": [
{
"name": "",
"type": "address"
},
{
"name": "",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"name": "_initialSupply",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"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 contractAddress = '0x30a8999Cb4c766fD6BA21723679466169710f053'
const contract = new web3.eth.Contract(contractABI, contractAddress)
const data = contract.methods.transfer(account2, 1000).encodeABI()
web3.eth.getTransactionCount(account1, (err, txCount) => {
//Build Tx
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(800000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
to: contractAddress,
data: data
}
//sign the Tx
const tx = new Tx(txObject)
tx.sign(privateKey1)
const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')
//Broadcast Tx
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('err: ',err,'txHash:', txHash)
})
})
I even tried without using the 'hex' conversion of private keys, also I tried removing '0x' from the private key values but nothing is working out.
Can anyone suggest, what can be issue here as I am new to Web3 and trying my level best to understand it.
I know it way to late but for anyone searching this, try :const privateKey = Buffer.from(process.env.PRIVATE_KEY, "hex");
It worked for me ;)
Try sending the private key removing the '0x'
Maybe like this:
process.env.PRIVATE_KEY_1.substr(2);
Hope it helps!
I had used MIST to deploy an ethereum token contract to my private chain. I can use MIST to interact with this token contract without any problem. I can transfer token between accounts. But when I use my web3.js script to interact with my private chain, it had no error BUT it just couldn't transfer token between accounts. But I can use this web3.js script to get correct balance of the accounts. I am new to ethereum development. Any helps are welcome!
I use the command to start private chain:
geth --identity "ImsaIco" --ipcdisable --nodiscover --rpc --rpcport "9001" --rpccorsdomain "*" --datadir "D:\abiz\blc\dev\icoc\chain" --port "8001" --rpcapi "db,eth,net,web3,personal" --networkid 1001 --mine
To let Mist connect to my private chain I use this command:
"D:\abiz\blc\software\mist\Mist.exe" --rpc "\\.\pipe\geth.ipc"
This is my web3.js script:
var Web3 = require('web3');
var net = require('net');
var web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:9001"));
var accounts;
// Copied from MIST interface
var heCoinContractAbi = [ { "constant": true, "inputs": [], "name": "name", "outputs": [ { "name": "", "type": "string", "value": "HeCoin" } ], "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", "value": "2e+25" } ], "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", "value": "18" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_value", "type": "uint256" } ], "name": "burn", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "", "type": "uint256", "value": "56000000000000000000" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_from", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "burnFrom", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "symbol", "outputs": [ { "name": "", "type": "string", "value": "HEC" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [], "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": "", "type": "address" }, { "name": "", "type": "address" } ], "name": "allowance", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [ { "name": "initialSupply", "type": "uint256", "index": 0, "typeShort": "uint", "bits": "256", "displayName": "initial Supply", "template": "elements_input_uint", "value": "20000000" }, { "name": "tokenName", "type": "string", "index": 1, "typeShort": "string", "bits": "", "displayName": "token Name", "template": "elements_input_string", "value": "HeCoin" }, { "name": "tokenSymbol", "type": "string", "index": 2, "typeShort": "string", "bits": "", "displayName": "token Symbol", "template": "elements_input_string", "value": "HEC" } ], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "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": "from", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } ], "name": "Burn", "type": "event" } ];
web3.eth.getAccounts(function(error, response){
if(!error) {
accounts = response;
callContractTransfer();
//getContractAccountBalance();
} else {
console.error(error); // there was an error, so let's see it.
}
});
function callContractTransfer() {
var hecoinContract = new web3.eth.Contract(heCoinContractAbi);
hecoinContract.options.address = '0xa960fFc27EF72f2db7AB6c86BaB9549FFcf20717'; // Copied from MIST interface
hecoinContract.methods.transfer(accounts[1], web3.utils.toWei('30', 'ether')).call({from: accounts[0]}, function(error, result) {
console.log('error:' + error + '!');
console.log('result:' + JSON.stringify(result) + '!');
});
}
function getContractAccountBalance() {
var hecoinContract = new web3.eth.Contract(heCoinContractAbi);
hecoinContract.options.address = '0xa960fFc27EF72f2db7AB6c86BaB9549FFcf20717';
hecoinContract.methods.balanceOf(accounts[1]).call({from: accounts[0]}, function(error, result) {
console.log('getContractAccountBalance error:' + error + '!');
console.log(accounts[1] + ':getContractAccountBalance result:' + result + '!');
});
}
According to https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-call the method call :
Will call a “constant” method and execute its smart contract method in the EVM without sending any transaction.
You should use the "send" method : https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-send with your function "transfer"
I have an api request that returns JSON data which is then used to populate an html table. I am able to populate the table with item.name ... I would like to add the metadata value for player.field but I have not been able to access it. Here is the JSON response:
{
"list": [
{
"id": 55,
"name": "0046GS (RMS03241708)",
"description": "S 12-7 M-S 10-9",
"uuid": "6f4b5bfd-6d17-4095-9e48-7b9313f7f8c6",
"previewPlayer": false,
"enabled": true,
"mac": "00-00-00-00-00-00",
"type": "CHROMEBOX",
"distributionServer": {
"id": 2,
"name": "Main",
"driver": "IP_P2P"
},
"playergroups": [
{
"id": 2,
"name": "GameStop",
"numberOfPlayers": 454
}
],
"playerDisplays": [
{
"id": 55,
"name": "Display 1",
"channel": {
"id": 53,
"name": "GameStop TV"
},
"screenCounter": 1
}
],
"requestLogs": false,
"downloadThreads": 1,
"unusedFilesCache": 24,
"planDeliveryMethod": "CONTENT_MANAGER_DIRECT",
"pollingInterval": 1,
"pollingUnit": "MINUTES",
"logLevel": "normal",
"metadataValue": [
{
"id": 12512,
"value": "true",
"playerMetadata": {
"id": 34,
"name": "Player.field",
"datatype": "BOOLEAN",
"valueType": "ANY",
"order": 4
}
},
{
"id": 1085,
"value": "77056",
"playerMetadata": {
"id": 31,
"name": "Player.ZipCode",
"datatype": "STRING",
"valueType": "ANY",
"order": 30
}
},
{
"id": 1071,
"value": "22:15",
"playerMetadata": {
"id": 10,
"name": "Player.ScreenOff_Wednesday",
"datatype": "STRING",
"valueType": "ANY",
"order": 12
}
}
],
"usedPairingKey": "HBVULW",
"active": "ACTIVE",
"lastModified": "2017-04-03 20:12:43",
"timezoneOffset": "0"
}
],
"offset": 0,
"count": 68
}
Here is the ajax request:
$.ajax({
type: 'GET',
url: "https://sampleserver.com:8080/ContentManager/api/rest/players?limit=1&offset=0&sort=name&filters=%7BplayerStatus%20:%20%7Bvalues:%5B'ACTIVE'%5D,%20comparator%20:%20'eq'%7D%7D",
dataType: "json",
success: function(data) {
$.each(data.list, function(i, item) {
var tr = $('<tr><td>'+item.name+'</td><td>'+some.JSONResponse+'</td></tr>').appendTo('#scalaapi');
});
}
});
I am stuck on how to specifically display the value for player.field ... "value": "true",
It feels like it should be simple, but my attempts have all been met with undefined.
Attempted if statement...
success: function(data) {
$.each(data.list, function(i, item) {
var tr = $('<tr><td>'+item.name+'</td><td class="val">...</td></tr>').appendTo('#scalaapi');
var bool = function(i,item) {if (item.metadataValue.id = '12512');
tr.find('.val').text(bool);};
});
}
});