I got this error from metamask.
It was working fine couple of hours ago. I have tried reinstalling/ disable and re-enabling again but nothing worked.
Also,
My smart contract is fully functional (Tested in Remix Browser based IDE) and no other errors or logs are present anywhere. I also restarted Ganache and re-compiled and re-migrated my contracts with no luck.
Here is my solidity code:
pragma solidity ^0.4.18;
contract Voting {
address mainAddress;
bytes32[] candidateNames;
mapping(bytes32 => uint) candidateVotes;
mapping(bytes32 => bytes32) candidatesDetails;
function Voting() public {
mainAddress = msg.sender;
}
modifier isMainAddress {
if (msg.sender == mainAddress) {
_;
}
}
function getAllCandidates() public view returns (bytes32[]) {
return candidateNames;
}
function setCandidate(bytes32 newCandidate) isMainAddress public {
candidateNames.push(newCandidate);
}
function setVote(bytes32 candidate) public {
candidateVotes[candidate] = candidateVotes[candidate] + 1;
}
function getVote(bytes32 candidate) public view returns (uint) {
return candidateVotes[candidate];
}
function setDescrption(bytes32 candidateName, bytes32 candidatesDesc) isMainAddress public {
candidatesDetails[candidateName] = candidatesDesc;
}
function getDescription(bytes32 candidateName) public view returns (bytes32){
return candidatesDetails[candidateName];
}
}
And I am calling these functions like :
let votingContractInstance;
const contract = require('truffle-contract')
const votingContract = contract(VotingContract)
votingContract.setProvider(this.state.web3.currentProvider)
this.state.web3.eth.getAccounts((error, accounts) => {
votingContract.deployed().then((instance) => {
votingContractInstance = instance
return votingContractInstance.setVote(this.state.candidateName);
}).then((result) => {
this.setState(() => ({
allCandidates: result
}));
})
})
All of the calls are made by this way only.
I am using one of the truffle boxes (REACT box) and no logs/errors are present in console either.
Did you figure this out? Can you just call this.setState({ allcandidates: result })
Also, the result from setVote isn't anything because you don't have it return anything in the solc contract.
Related
I'm consuming a POST service in .net that returns the next structure, the service return data correctly
enter image description here
public sendExcelInBase64ToBackEnd(data: any) {
this.customOptions = {
headers: this.customHttp.buildHeader(),
};
this.customHttp.Post<SerialResultDTO>('/serialsExcel', data, this.customOptions).subscribe(val => { // <- val data returns ok
this.serialResult = val;
let x = this.serialResult.Success;
console.log(x);
console.log(val.Success); // <- prints undefined
})
return null;
}
When I try print in console 'val.Success' it prints undefined!!, Why this happens??
I want assign all atributes to a custom class in angular, but in chrome debug it shows object data, but in time of asign to my model class it gets undefined!!
Someone can help me please!! I appreciate that!!
Your image shows a lowercase success, but you try to log a titlecase Success. Change to
public sendExcelInBase64ToBackEnd(data: any) {
this.customOptions = {
headers: this.customHttp.buildHeader(),
};
this.customHttp.Post<SerialResultDTO>('/serialsExcel', data, this.customOptions).subscribe(val => {
this.serialResult = val;
let x = this.serialResult.success;
console.log(x);
console.log(val.success);
})
return null;
}
I see they use this kind of code to call restful URLs.
Let's say we have /users/{userId}/tasks to create task for a user.
To call this they create another class instead of calling request directly as shown below:
MyAPP.prototype.users = function (userId) {
return {
tasks: function (taskId) {
return this.usersTasks(userId, taskId);
}
}
}
MyAPP.prototype.usersTasks = function (userId, taskId) {
return {
create: function (task, cb) {
make request POST call
}
}
}
Then we can call this as myapp.users('123').tasks().create(task, cb);
What is this kind of coding called and is there any way to automatically generate the code from the URL structure itself?
That is a way of making classes, but I suggest you look into ES6 classes
Defining a class :
class MyAPP {
//:called when created
constructor(name) {
this.name = name;
console.log("[created] MyAPP :",name);
//(a in memory database stored in MyAPP : for example purpose)
this.DB = {'user000':{'tasks':{'task000':'do pizza'},{'task001':'code some magik'}}}
}
//: Get specific taskID for userID
getTask(userID, taskID) {
console.log("[get task]",taskID,"[from user]",userID)
return (this.DB[userID][taskID])
}
//: Get all tasks for userID
allTasks(userID) {
console.log("[get all tasks from user]",userID)
return (this.DB[userID].tasks)
}
//: Create a taskID with taskContent for userID
newTask(userID, taskID, taskContent) {
this.DB[userID].tasks[taskID] = taskContent
}
}
Creating a MyAPP instance :
var myapp = new MyAPP('Pizza API'); //creates a MyAPP with a name
And then (maybe I got your question wrong) using express you would make a server and listen for requests (GET, POST, PUT, ...)
app.get("/APIv1/:userID/:actionID", function(req, res) {
switch(req.params.actionID){
case 'all':
res.send(myapp.allTasks(req.params.userID));
break
default :
res.send("The "+myapp.name+" doesn't support that (yet)")
break
}
});
I have small test smart contract, which is deployed to my test network. And I want to use a server to call the function in the contract. Here is the code:
payontime.sol
pragma solidity ^0.4.0;
contract payontime{
address public remitter;
address private remittee;
uint value;
bool public start;
/*Only owner can use these function*/
modifier onlyOwner(){
if(msg.sender != remitter) throw;
_;
}
/*Initialize the owner*/
function payontime(address receiver) payable{
remitter = msg.sender;
value = msg.value;
remittee = receiver;
start = true;
if(!remittee.send(value)){
throw;
}
}
function wakeUp() public returns (string){
return "success" ;
}
function getContractAddr() public returns(address){
return this;
}
/*Get the remittee*/
function getRemitee() public returns(address){
return remittee;
}
}
I use truffle serve and a webpage to new the contract.
app.js
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import payontime_artifacts from '../../build/contracts/payontime.json'
var payontime = contract(payontime_artifacts);
window.App = {
sendCoin : function(){
var sender = web3.eth.accounts[0];
var receiver = document.getElementById('receiver').value;
var amount = parseInt(document.getElementById('amount').value);
web3.eth.getBalance(receiver,function(error,result){
if(!error){
consol.log("Before transfer: " + result );
}else{
console.log("Error: " + error);
}
});
var newContract = payontime.new(receiver,{from:sender, value:amount}).then(
function(myPay){
console.log(myPay.getContractAddr.call());
}).then(
function(){
web3.eth.getBalance(receiver,function(error,result){
if(!error){
console.log("After transfer: " + result );
}else{
console.log("Error: " + error);
}
});
});
}
}
window.addEventListener('load', function() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
// Use Mist/MetaMask's provider
window.web3 = new Web3(web3.currentProvider);
} else {
console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
payontime.setProvider(web3.currentProvider);
});
app.js logs the address 0x1d379f2ab48ad20319e9f81cb45af415aa6f2966 , and I want to use this address to call the wakeUp() in the payontime.sol through another application index.js.
const Web3 = require('web3');
/* Connect to ethereum node */
const etherUrl = "http://localhost:8545";
const abi = [{"constant":false,"inputs":[],"name":"wakeUp","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"getContractAddr","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"remitter","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"start","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"getRemitee","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"inputs":[{"name":"receiver","type":"address"}],"payable":true,"type":"constructor"}];
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(etherUrl));
/*Call the function which already deployed on ethereum network
Notice: ABI have to modifeid when the smart contract code change*/
var contractInstance = web3.eth.contract(abi).at('0x1d379f2ab48ad20319e9f81cb45af415aa6f2966');
var reply = "false";
reply = contractInstance.wakeUp.call(function(error,result){
if(error){
console.log("Error");
throw error;
}else{
return result;
}
});
console.log(reply);
But there is an error message:
BigNumber Error: new BigNumber() not a base 16 number
I found it might be caused by not fully synced. I think it have some problem when I call the function in a deployed contract. So how can I call a deployed contract from web.js?
contractInstance.wakeUp.call is calling the function as constant, but the function is not defined as constant:
function wakeUp() public returns (string){
return "success" ;
}
has to be:
function wakeUp() public constant returns (string){
return "success" ;
}
If your Solidity function doesn't change the blockchain state and is just reading data, you should define it as constant.
As well as putting your console log within the call back, you can fix the big number error with:
console.log(result.toNumber());
Speech is not being recognized with default dictation grammar in my UWP application. However, it is perfectly recognized when I use programmatic list constraint. Below is the speech recognition part of my code for reference. If I do not comment the 5th line, this works fine. Am I doing something wrong below:
speechRecognizer = new SpeechRecognizer();
bool PermissionGained = await CheckMicrophonePermission();
if (PermissionGained)
{
//speechRecognizer.Constraints.Add(new SpeechRecognitionListConstraint(Grammar.GrammarCommands.GrammarConstraintList));
await speechRecognizer.CompileConstraintsAsync();
//recognize speech input at any point of time
speechRecognizer.ContinuousRecognitionSession.ResultGenerated +=
async (s, e1) =>
{
if ((e1.Result != null))
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
await ParsespeechCommand(e1.Result);
});
speechRecognizer.ContinuousRecognitionSession.Resume();
}
};
await speechRecognizer.ContinuousRecognitionSession.StartAsync(SpeechContinuousRecognitionMode.PauseOnRecognition);
}
As discussed I made a demo and made some changes from the codes.
Here are my codes:
private async void myBtn_Click(object sender, RoutedEventArgs e)
{
//here I remove the checkPermission process
var speechRecognizer = new SpeechRecognizer();
if (true)
{
//speechRecognizer.Constraints.Add(new SpeechRecognitionListConstraint(new List<string> { "winffee", "Elvis", "noob" }));
await speechRecognizer.CompileConstraintsAsync();
//recognize speech input at any point of time
speechRecognizer.ContinuousRecognitionSession.ResultGenerated +=
async (s, e1) =>
{
if ((e1.Result != null))
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>//here I remove the async
{
var result = e1.Result;//here I remove the method to focus on the e1.Result.
});
speechRecognizer.ContinuousRecognitionSession.Resume();
}
};
await speechRecognizer.ContinuousRecognitionSession.StartAsync(SpeechContinuousRecognitionMode.PauseOnRecognition);
}
}
The whole function is triggered by a button click event. And I made comment on every change position(totally 3 places).
I have a library that connects to a remote API:
class Client(access_token) {
void put(key, value, callback);
void get(key, callback);
}
I want to set up a Node.js REPL to make it easy to try things out:
var repl = require('repl');
var r = repl.start('> ');
r.context.client = new Client(...);
The problem is that an asynchronous API is not convenient for a REPL. I'd prefer a synchronous one that yields the result via the return value and signals an error with an exception. Something like:
class ReplClient(access_token) {
void put(key, value); // throws NetworkError
string get(key); // throws NetworkError
}
Is there a way to implement ReplClient using Client? I'd prefer to avoid any dependencies other than the standard Node.js packages.
You can synchronously wait for stuff with the magic of wait-for-stuff.
Based on your example specification:
const wait = require('wait-for-stuff')
class ReplClient {
constructor(access_token) {
this.client = new Client(access_token)
}
put(key, value) {
return checkErr(wait.for.promise(this.client.put(key, value)))
}
get(key) {
return checkErr(wait.for.promise(this.client.get(key)))
}
}
const checkErr = (maybeErr) => {
if (maybeErr instanceof Error) {
throw maybeErr
} else {
return maybeErr
}
}