Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2.

contract Charity{

    function ping() public constant returns (uint) {
        return 200;
    }


}

Currently, I am compiling and calling it in typescript with:

import * as fs       from 'fs'       ;
import * as solc     from 'solc'     ;
import * as Web3     from 'web3'     ; 


var web3   = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

var contract_path : string = "path/to/Charity.sol"
const input       = fs.readFileSync(contract_path)
const output      = solc.compile(input.toString(), 1);
var contract_name = ":" + pr.last(contract_path.split("/")).split(".")[0]
const bytecode    = output.contracts[contract_name].bytecode
const abi_        = JSON.parse(output.contracts[contract_name].interface);

web3.eth.getAccounts().then(accounts => {

    var coinbase = accounts[0];
    var receiver = accounts[1];

    // create contract
    var myContract = new web3.eth.Contract([], {
          from     : coinbase
        , gasPrice : '20000000000'
    });

    // set address to coinbase, and jsonInterface to abi
    myContract.options.address = coinbase;
    myContract.options.jsonInterface = abi_;

    // deploy contract -> problem, how do I get the abi in here?
    var deployedContract = myContract.deploy({

        data: '0x' + bytecode,

    }).send({

        from: coinbase,
        gas : 1500000 ,
        gasPrice: '30000000000000'            

    }, (err, hash) => {

        if (err) { console.log("error on deployment: ", err) }
        console.log("Hash: ", hash)
    })

    // send contract fn to network to be executed
    // problem: this is not doing what it's suppose to 
    myContract.methods.ping().send({ from : coinbase }, (err, val) => {
        console.log("ping(): ", err, val)
    })

    myContract.methods.ping().send({from: coinbase})
    .on('transactionHash', function(hash){
        console.log("hash: ", hash)
    })
    .on('receipt', function(receipt){
        console.log("recepit: ", receipt)
    })
    .on('confirmation', function(confirmationNumber, receipt){
        console.log("conffirmation: ", receipt)
    })
    .on('error', console.error);        



});

The main issue here is that

myContract.methods.ping().send...
is not providing the expected value 200 on the callbacks. Is there a solution for this problem?

Answer №1

Remember to always use the call() method instead of send() when calling a constant function.

For more information, refer to the documentation:

Answer №2

Without altering the state, simply utilize call(). On the other hand, if you do make changes to the state, a transaction (send) is required followed by waiting for it to be mined. One approach is to emit an event and subsequently monitor it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The most efficient method for searching and deleting elements from an array in Mongoose

I'm currently struggling with my implementation of mongoose in express. It seems like I'm using too many queries just to add something to a document, and I can't help but feel that there's a simpler way to achieve this. This function i ...

Using PHP to trigger alerts with MySQL data via AJAX from a separate file

I need to notify the first page from the second one, like in the example below: <?php $sql = "SELECT table_id, on, off FROM tables"; // retrieving and populating my table with information $stmt = mysqli_prepare($dbc, $sql); mysqli_stmt_exec ...

Using Ajax and jQuery to fetch information from a previous search query

I'm currently utilizing Ajax and jQuery for my chat feature. Some may find it overly complex, but as long as it works, that's all that matters. It's functioning properly on the first friend result, however, not on the others. The issue lies ...

Choosing from a variety of tr elements

I'm working with a table in HTML that has about 100 rows. I would like to apply different colors to specific groups of rows, such as making rows 1-10 red and rows 20-40 blue. Using nth-child seems like an option, but it can get quite verbose if I nee ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

Attempting to transmit a text message to a PHP script using Ajax

Hey there! I'm facing a challenge while trying to send a string to a PHP file using AJAX. It seems like the http.send function is not working as expected, and I suspect there might be an issue in my code. (I'm fairly new to programming) mainlin ...

Limiting the amount of blogs shown on a single page can be achieved with Yii 1 and PHP

I have successfully implemented a feature to display blogs on one page. However, I now want to modify it so that only 5 blogs are shown per page and the user can click on a "next page" button to view the next set of 5 blogs. Here is the code snippet from ...

Retrieve the IDs of list elements in order to dynamically update a div using AJAX

I'm facing a bit of a challenge at the moment. I have a webpage that uses jQuery to load three different views: one displaying all categories associated with the user, another showing the image and name of items within the selected category, and a thi ...

Using jQuery to include Chinese characters in a request header

When making a jQuery post request, I need to set client information in the header. This is how my call looks: jQuery.ajax({ url : myURL, type : "POST", beforeSend : function(request){ request.setRequestHeader('someInfo', clie ...

Transition smoothly from the first texture to a solid color, and then seamlessly switch to the second texture using a GLSL Shader

I am working on a GLSL fragment shader that aims to achieve the following sequential effects: Transition from texture 1 to a specific color Transition from the color to texture 2 Here's my initial attempt: // Uniforms uniform sampler2D tex1; uniform ...

Setting up the data for the AjaxAppender Request Log4Javascript

I am completely new to Log4Javascript and the concept of logging, so please bear with me. My current task involves sending logs to a CouchDB server using a POST request. However, I keep encountering an error from the server: {"error":"bad_request","reaso ...

Is XML parsing used by AJAX?

Is an XML parser used by AJAX? If so, where is it used? I believe that the client-side JavaScript engine utilizes the DOM parser to extract necessary information from the XML document received from the server. Could it be possible that AJAX doesn't us ...

Troubleshooting problems with the CSS code for a progress bar in Gmail

I recently came across a unique progress bar design on Gmail and wanted to implement something similar. I found some code snippets on this webpage: . However, I encountered an issue where the progress bar was only displaying in Internet Explorer but not in ...

Utilize getElementsByClassName to dynamically alter the appearance of specific elements upon triggering an event

I'm attempting to utilize onmouseover="document.getElementsByClassName().style.background='color'" in order to switch the color of all divs with a specified classname to a different color when hovering over another element on the page. ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Teach me how to utilize Import / require() in Static Folder

I've been attempting this task for a while, but I'm unsure how to incorporate import or require into the express static folder. When I try to use it, I receive an error stating "require not defined" which makes sense since these are not supported ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

Troubleshooting Ajax contact form's failure to refresh (PHP and Bootstrap 4)

I have successfully implemented this code on one website, but it is not working as expected on another website. It sends the email but refreshes the page and redirects to a contact.php page with a message. Despite double-checking everything, including cha ...

The field 'shouldComponentUpdate' cannot be reassigned to itself

I encountered a TypeScript error while using shouldComponentUpdate: The error message states: "Property 'shouldComponentUpdate' in type 'Hello' is not assignable to the same property in base type Component<IProps, any, any>." ...