6
var myContract = web3.eth.contract(abi);
var address = contract address;
var contract_data = myContract.at(address);
var sender = '0xd3aaa525c087978133abb517593ea334f16abd1f';
var receiver = '0xff2b56315dc5372b45dfa3773c4cfd64f70c8e9c';
//transfer is the function in the contract to transfer money from wallet A to B
var getData = contract_data.transfer.getData(receiver,amount);
web3.eth.sendTransaction({to:receiver, from:sender, data: getData});

Source: How to call my contract's function using sendTransaction

When I am tracking the balance, it turns out that only gas price is being deducted from wallet A and nothing else ? But when I use metamask UI to do the transactions, balances are updated successfully. I believe, there is some flaw with the way I am using this api, it'd be really great if anyone could share their experience.

3
8

You need to pass value in Wei form to sendTransaction method:

web3.sendTransaction({to:receiver, from:sender, value:web3.toWei("0.5", "ether")})

sender account should be unlocked for this to succeed.

source


to send tokens you need to call

contract_data.transfer(receiver,amount{from:web3.eth.accounts[0]});

or something among those lines. You don't need to use web3.eth.sendTransaction

5
  • value is used to send ethers. But I guess OP is asking for transferring tokens (maybe erc-20). Dec 10 '17 at 6:40
  • I'm guessing he wants to send ethers because he is wondering why only gas is deducted Dec 10 '17 at 12:17
  • Hey, Thanks a lot. Yes, I intend to transfer tokens. And I need to use the transfer function of my contract to do that. Dec 10 '17 at 17:31
  • I updated my solution to send tokens Dec 10 '17 at 19:55
  • 1
    You're missing web3.eth.sendTransaction Oct 14 '20 at 5:07
0
//set web3 variable
const web3 = new Web3(window.ethereum);

//get all the accounts
const accounts = await web3.eth.getAccounts();

//if you're using react
this.setState({web3, accounts});

//send the tx using react
this.state.web3.eth.sendTransaction({to: contractAddress, from: this.state.accounts[0], value: ETHamount});

or if you're not using react

web3.eth.sendTransaction({to: address, from: address, value: inWei});

A conversion of wei to eth can be found here. Information on web3 variable setting (it uses infura usually as the endpoint [aka the provider]) can be found here.

0

If you are using web3.js 1.3.x, this is what worked in my case:

web3.utils.toHex(web3.utils.toWei(amount, 'ether'))

For whichever reason, the below command was sending a wrong value into Metamask.

web3.utils.toWei(amount, 'ether')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.