9
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.

I.B
  • 615
  • 3
  • 9
Anshul Basia
  • 101
  • 1
  • 1
  • 3

4 Answers4

10

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

Ismael
  • 30,570
  • 21
  • 53
  • 96
Daniel Gretzke
  • 1,279
  • 1
  • 9
  • 23
0

With metamask:

window.ethereum.request({
  method: 'eth_sendTransaction',
  params: [{
    to,
    from,
    value: web3.utils.toHex(web3.utils.toWei("0.5")),
  }],
})
.then(() => {
  alert("Woot!")
})
.catch((e) => {
  alert("Oops!")
})
pguardiario
  • 227
  • 2
  • 6
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')
Sergi Juanati
  • 3,399
  • 3
  • 17
  • 38