how to call smart contract method from web3.js using java script - smartcontracts

A smart contract method has already been deployed and I want to call a method using javascript. How can I do that?
contractABI = ABI json;
contractAddress = ('my addess');`

Related

How to check values of a variables and functions in solidity like javascript via console.log

How to check values of a variables and functions in solidity like javascript via console.log? Because i need visibility of results for deep understanding.
I am newbie...
i tried hardhat but need more understand.
I'm a newbie too, but I know this (I think)!
There is no console in solidity, you need to write a function for this, or just put it public in the variable itself!
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Value {
uint public num; //add "public" to see the value
function add(uint _num) external{
num += _num;
}
//this function is for returning value
function viewNum() public view returns(uint){
return(num);
}
}
Also use the Remix editor, it's in the browser. There are plenty of videos on the internet!
If you are using hardhat, then you can use console.sol.
You need to import it into your contract.
import "hardhat/console.sol";
Now, you are able to log your variable while you are working.
console.log(__your_variable__);
If you are still looking to log your variables once you deploy your contract, then you need to use event functionality.
Import hardhat console:
import "hardhat/console.sol";
Use console log in your contract
console.log(variable); //Variable value
console.log(1234); //direct value

create2 not working in tron, gives empty bytecode

So, I've a contract which deploys using create2 i.e., custom salt. Its working perfectly in Ethereum but with Tron it's not. When its called, the result of the contract ( which is created by create2 ) is empty. The contract ABI and Bytecode both shows null. I dont know why its happening. Am I missing something?
Here is the part of the code of my contract
function deploy(address _owner, uint256 _salt) public returns (address addr) {
bytes memory bytecode = getBytecode(_owner);
assembly {
addr := create2(
0,
add(bytecode, 0x20),
mload(bytecode),
_salt
)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
emit Deployed(addr, _salt);
}
function getBytecode(address _owner) public pure returns (bytes memory) {
bytes memory bytecode = type(Forwarder).creationCode;
return abi.encodePacked(bytecode, abi.encode(_owner));
}
Forwarder is my Contract
This is one of my contract which is deployed by create2
If anyone need anymore info, Let me know.
I wanna solve this.
So, we cannot get ABI and bytecode of a contract deployed using create2 said by tron support team.
and they provided a solution i.e.,
let instance = await tronWeb.contract().at("TREwN2qRkME9TyQUz8dG6HfjEyKGMPHAS5");
instance.loadAbi([{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]);
let res = await instance.totalSupply().call({_isConstant:true})
so we can get the instance from contract address and load the ABI
and then we can call the contract function and perform operation.

address(this).send(msg.value) returning false but ethers got transfered

Below is my function:
// Function
function deposit() payable external {
// if(!wallet_address.send(msg.value)){
// revert("doposit fail");
// }
bool isErr = address(this).send(msg.value);
console.log(isErr);
emit Deposit(msg.sender, msg.value, address(this).balance);
}
I use Remix IDE with solidity version 0.8.7 and my question is why send() returns false but the ethers got transferred. Is send() returns false when it success by default?
address(this).send(msg.value) effectively just creates an unnecessary internal transaction redirecting the value accepted by "this contract" to "this contract"
This internal transaction fails because because your contract does not implement the receive() nor fallback() special functions that are needed to accept ETH sent to your contract from send(), transfer(), call() in some cases, and generally any transaction (internal or main) that does not invoke any specific existing function. It does not fail the main transaction, just returns false from the send() method.
TLDR: The send() function is in this case redundant and you can safely remove it. Your contract is able to accept ETH from the deposit() function even without it.
It is low level function call, it can fail in after transfer step. If you don't check success variable, the compiler is warning you that the call could revert and you might carry on unaware that you ignored failure.
So you should check success variable to ensure transaction is success.
require(success, "ETH_TRANSFER_FAILED");

Solidity contract method not working on web3

I have a method on my contract:
function reservePlace(address _address, uint _place) public{
require(places[_place] == 0, "Place is already reserved");
userIds[_address] = lastUserId;
places[_place] = lastUserId;
lastUserId += 1;
}
and it works perfectly on truffle, I can execute it and works well
but when I use web3 and I pass:
contract.methods
.reservePlace("0x95f086ee384d54a056d87dC8A64E354cC55E2690", 1)
.call();
it doesn't do anything, also it doesn't show any error. Other methods work fine when I use them with web3 so web3 setup is correct. How can I solve it?
This is because you are calling data from the blockchain instead of sending it. In order for it to work, you should call:
contract.methods.reservePlace("0x95f086ee384d54a056d87dC8A64E354cC55E2690", 1).send({from:'your authorized address'});

“Out of Gas” while transferring ethereum from account to contract

I am using ganache to create 10 ethereum accounts. I want to transfer ethereum from one account to a smart contract. I am doing this by writing two following smart contracts in solidity;
pragma solidity >=0.4.0 <0.6.0;
contract Ether_Transfer_To{
function () external payable { //fallback function
}
function get_balance() public returns(uint){
return address(this).balance;
}
}
contract Ether_Transfer_From{
Ether_Transfer_To private the_instance;
constructor() public{
//the_instance=Ether_Transfer_To(address(this));
the_instance=new Ether_Transfer_To();
}
function get_balance() public returns(uint){
return address(this).balance;
}
function get_balance_of_instance() public returns(uint){
//return address(the_instance).balance;
return the_instance.get_balance();
}
function () external payable {
// msg.sender.send(msg.value)
address(the_instance).send(msg.value);
}
}
When I deploy the contract Ether_Transfer_From smart contract then I get its three-member functions as follows in remix;
But when I sent one 1 Wei from account to smart contract by writing 1 in the text box and clicking on a (fallback) button, then I get the following error;
transact to Ether_Transfer_From. (fallback) errored: VM Exception while
processing transaction: out of gas
I followed the answer of the same question by installing Ganache-cli 7.0.0 beta.0 by using following command;
npm install -g ganache-cli#7.0.0-beta.0
But I still get the same error. I think I am using older Ganache cli instead of Ganache-cli 7.0.0 beta.0 as it goes to C drive and I installed ganache 2.1.1 in D drive previously.
I just want to send ethereum from one account to other but I am really stuck in this out of gas Error. If there is any way to remove this error or transfer ethereum from one account to another then please let me know.
So this is what I did for one of my projects.
This snippet, deploys the compiles the solidity file and then deploys it and gets the address of the deployed contract address
const input = fs.readFileSync('Migrations.sol');
const output = solc.compile(input.toString(), 1);
const bytecode = output.contracts[':Migrations']['bytecode'];
const abi = JSON.parse(output.contracts[':Migrations'].interface);
var contract = new web3.eth.Contract(abi);
contract.deploy({
data: '0x'+bytecode,
})
.send({
from: chairPerson,
gas: 5500000,
gasPrice: '2000000000000'
})
.on('receipt', (receipt) => {
add=receipt.contractAddress;
})
Now using contract's abi, I can call methods of the deployed contract and use the following code to transfer '1.5' ether from one address to another.
contract.methods.registerRequest(fromAddress,toAddress,requestNumber).send({from:fromAddress,value : web3.utils.toWei('1.5', 'ether')}).on('transactionHash', (hashResult) => {-- some code--})
And also make the method in the solidity as payable to allow it to transfer ether, like :
function registerRequest(address requestedBy,address requestedTo,uint requestNumber) payable public{}
Refer : https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#id12
Basically I used web3 api itself to transfer ether from one account
to another by calling my solidity method.
Also, check the following things :
1. While deploying, are you deploying with enough gas ? I faced this error when I was deploying the contract with less gas quantity
2. Your method in solidity should be payable