-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Transferring ERC20 tokens from account using web3 over Ropsten #1151
Comments
Use following - rawTransaction.from = "0x9..."; // as you have set in example
rawTransaction.value = 0; // as you don't want to send ether with transaction
rawTransaction.to = tokenAddress;
rawTransaction.data = contract.transfer.getData(userAddress, tokenValues); // user's address is the address you want to send tokens to. |
a new version of web3 1.x
|
Hello! Give me, please, an example of the working code for sending tokens for the version of web3@1.0.0-beta.27. I'm trying to write code for these examples. But there are a lot of mistakes related to the irrelevance of the data. I think that it will be useful to many. Thank you! |
Single-address allocation of MineFIL Token (MFIL) code which was written and tested using web3 version 1.0.0-beta.29. Check the MFIL Ethereum Smart Contract Scripts for more. // Dotenv javascript libraries needed
require('dotenv').config();
// Ethereum javascript libraries needed
var Web3 = require('web3');
var Tx = require('ethereumjs-tx');
// Rather than using a local copy of geth, interact with the ethereum blockchain via infura.io
// The key for infura.io is in .env
const web3 = new Web3(Web3.givenProvider || "https://ropsten.infura.io/" + process.env["INFURA_KEY"])
// Fixed-point notation for number of MFIL which is divisible to 3 decimal places
function financialMfil(numMfil) {
return Number.parseFloat(numMfil / 1e3).toFixed(3);
}
// Create an async function so I can use the "await" keyword to wait for things to finish
const main = async () => {
// This code was written and tested using web3 version 1.0.0-beta.29
console.log(`web3 version: ${web3.version}`)
// Who holds the token now?
var myAddress = "0x644dE7C3f6425D8920332FC6C97Fbf7e04445C74";
// Who are we trying to send this token to?
var destAddress = "0xE3A029F6cA0C32a9E6c9a2154790Ea0A92cb2621";
// MineFIL Token (MFIL) is divisible to 3 decimal places, 1 = 0.001 of MFIL
var transferAmount = 1;
// Determine the nonce
var count = await web3.eth.getTransactionCount(myAddress);
console.log(`num transactions so far: ${count}`);
// MineFILToekn contract ABI Array
var abiArray = [{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [{
"name": "",
"type": "string"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_spender",
"type": "address"
}, {
"name": "_value",
"type": "uint256"
}],
"name": "approve",
"outputs": [{
"name": "",
"type": "bool"
}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [{
"name": "",
"type": "uint256"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_from",
"type": "address"
}, {
"name": "_to",
"type": "address"
}, {
"name": "_value",
"type": "uint256"
}],
"name": "transferFrom",
"outputs": [{
"name": "",
"type": "bool"
}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "INITIAL_SUPPLY",
"outputs": [{
"name": "",
"type": "uint256"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [{
"name": "",
"type": "uint8"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_spender",
"type": "address"
}, {
"name": "_subtractedValue",
"type": "uint256"
}],
"name": "decreaseApproval",
"outputs": [{
"name": "",
"type": "bool"
}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}, {
"constant": true,
"inputs": [{
"name": "_owner",
"type": "address"
}],
"name": "balanceOf",
"outputs": [{
"name": "balance",
"type": "uint256"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [{
"name": "",
"type": "string"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_to",
"type": "address"
}, {
"name": "_value",
"type": "uint256"
}],
"name": "transfer",
"outputs": [{
"name": "",
"type": "bool"
}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_spender",
"type": "address"
}, {
"name": "_addedValue",
"type": "uint256"
}],
"name": "increaseApproval",
"outputs": [{
"name": "",
"type": "bool"
}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}, {
"constant": true,
"inputs": [{
"name": "_owner",
"type": "address"
}, {
"name": "_spender",
"type": "address"
}],
"name": "allowance",
"outputs": [{
"name": "",
"type": "uint256"
}],
"payable": false,
"stateMutability": "view",
"type": "function"
}, {
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
}, {
"anonymous": false,
"inputs": [{
"indexed": true,
"name": "owner",
"type": "address"
}, {
"indexed": true,
"name": "spender",
"type": "address"
}, {
"indexed": false,
"name": "value",
"type": "uint256"
}],
"name": "Approval",
"type": "event"
}, {
"anonymous": false,
"inputs": [{
"indexed": true,
"name": "from",
"type": "address"
}, {
"indexed": true,
"name": "to",
"type": "address"
}, {
"indexed": false,
"name": "value",
"type": "uint256"
}],
"name": "Transfer",
"type": "event"
}]
// The address of the contract which created MFIL
var contractAddress = "0x1564A92a0870aF0eBf1F015f5FD223abaA3505CA";
var contract = new web3.eth.Contract(abiArray, contractAddress, {
from: myAddress
});
// How many tokens do I have before sending?
var balance = await contract.methods.balanceOf(myAddress).call();
console.log(`Balance before send: ${financialMfil(balance)} MFIL\n------------------------`);
// I chose gas price and gas limit based on what ethereum wallet was recommending for a similar transaction. You may need to change the gas price!
// Use Gwei for the unit of gas price
var gasPriceGwei = 3;
var gasLimit = 3000000;
// Chain ID of Ropsten Test Net is 3, replace it to 1 for Main Net
var chainId = 3;
var rawTransaction = {
"from": myAddress,
"nonce": "0x" + count.toString(16),
"gasPrice": web3.utils.toHex(gasPriceGwei * 1e9),
"gasLimit": web3.utils.toHex(gasLimit),
"to": contractAddress,
"value": "0x0",
"data": contract.methods.transfer(destAddress, transferAmount).encodeABI(),
"chainId": chainId
};
console.log(`Raw of Transaction: \n${JSON.stringify(rawTransaction, null, '\t')}\n------------------------`);
// The private key for myAddress in .env
var privKey = new Buffer(process.env["PRIVATE_KEY"], 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();
// Comment out these four lines if you don't really want to send the TX right now
console.log(`Attempting to send signed tx: ${serializedTx.toString('hex')}\n------------------------`);
var receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
// The receipt info of transaction, Uncomment for debug
console.log(`Receipt info: \n${JSON.stringify(receipt, null, '\t')}\n------------------------`);
// The balance may not be updated yet, but let's check
balance = await contract.methods.balanceOf(myAddress).call();
console.log(`Balance after send: ${financialMfil(balance)} MFIL`);
}
main(); |
@FradSer I get "SyntaxError: await is only valid in async function" when I run your code. |
Not sure how people are using data: Contract.methods.transfer(to, 1000).encodeABI() My web3 version is '0.20.4' |
So apparently FradSer through in async in there and then everything has changed to promises in the current web3, which may or may not be people have. To anyone else trying to figure out everything posted online is different try starting with this web3 version: "^1.0.0-beta.29" |
@nickjuntilla That piece of code you mentioned is from web3 1.0.0 (beta). The code from @FradSer helped me finish mine, so big thanks! |
@nickjuntilla The code is written by 1.0.0-beta.29 , update your web3. |
The issue in the original question is that
should be
Use to user account address here but not the contract address. No need to use {from: "...} here. Use the contract address in the raw transaction. |
How do I deploy a contract by signing the transaction and unlocking the account using web3 ? Can anybody give a code snippet ? @FradSer please ? |
@sathyamlokare You don't need to unlock the account if you are signing the transaction using a privateKey. Here is a 100% functional code, if you have questions please ask. PS:
|
@neohq can you help me with this , everything works fine here gets deployed. But it says TransactionReciept Status failed
you can check the transactions here |
@sathyamlokare Increase gas limit and try again. |
@jdkanani I did that also, still getting the error |
@sathyamlokare If you are using Geth as a blockchain client, use 1.7.3 version, you are probably using the latest version 1.8.1 or 1.8.2 which has that problem you are describing. Using |
@neohq hello, i use your code, but has some errors when exec contract, this trans hash is https://rinkeby.etherscan.io/tx/0x77d854d47d65681e23f4780af45cb8cd7f935ee8a47a2249ac1fd7887cc21432 . and the code is can you help me ? thank you, i think is contract error, but i dont konw . |
@greggmojica I try and success. Thank many. |
var privKey = new Buffer(process.env["PRIVATE_KEY"], 'hex'); How can I use |
Refer to Send ERC20 token with web3 |
I was deploy smart contract to my private network and then tested got output as below node send.js
|
CircumstanceI have followed all indications from here and StackOverflow, the transaction gets broadcasted but no tokens are transferred. When I check the balance again, it's the same as before (10,000). const Tx = require('ethereumjs-tx');
const config = require('../config');
const contract = require('../contract');
const web3 = require('../web3');
const main = async () => {
try {
const count = await web3.eth.getTransactionCount(config.accounts[0]);
const nonce = web3.utils.toHex(count);
const txValue = web3.utils.toHex(parseInt(process.argv[2], 10) || 10);
const from = web3.utils.toChecksumAddress(config.accounts[0]);
const to = web3.utils.toChecksumAddress(config.accounts[1]);
const rawTx = {
nonce: nonce,
from: from,
to: to,
value: '0x0',
gasLimit: '0x30D40', // 54,000
gasPrice: '0x2CB417800', // 12 gwei
data: contract.methods.transfer(to, txValue).encodeABI(),
chainId: '0x03'
};
const privateKey = Buffer.from(config.private, 'hex');
const tx = new Tx(rawTx);
tx.sign(privateKey);
const serializedTx = tx.serialize();
const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
console.log(`Receipt info: ${JSON.stringify(receipt, null, '\t')}`);
console.log(`From\'s balance after transfer: ${await contract.methods.balanceOf(from).call()}`);
console.log(`To\'s balance after transfer: ${await contract.methods.balanceOf(to).call()}`);
} catch (err) {
console.log(err);
}
};
main(); Tools• node UpdateSolved. I was sending the tx to the other account by mistake, not to the contract. More details here. |
My error fixed ! just put private key |
@PaulRBerg you try use FradSer script above var abiArray = JSON.parse(fs.readFileSync(path.resolve(__dirname, './erc20_abi.json'), 'utf-8'));
var contract = new web3.eth.Contract(abiArray, contractAddress, {
from: myAddress
}); |
@hs1gab I have it at line 4 const path = require('path');
const config = require('./config');
const web3 = require('./web3');
const ABI = require(path.join(__dirname, '..', 'build', 'contracts', 'PaulCoin.json')).abi;
const contract = new web3.eth.Contract(ABI, config.contract, { from: config.accounts[0] });
module.exports = contract; As I previously stated, I can read the balance. I also can transfer ETH, only when trying to move tokens there are problems. |
@PaulRBerg Have you been move token by manual in Remix solidity by function transfer ? just for check account able to basic token move first or in your code try change const txValue = web3.utils.toHex(parseInt(process.argv[2], 10) || 10);
// to
const txValue = "12300000000000000000" ;
// or
var VALUE_TOKEN = "12300000000000000000" ; // cause of 18 decimal
const txValue = web3.utils.toWei( VALUE_TOKEN , "ether") ; |
@greggmojica
then throw
|
thank you very mach!i get it. |
@PaulRBerg |
try use |
How do you use infura to get the user's key for (var private key = new Buffer ('f6da78c45601d9ae02fcdb161e44a15a99e1fb1aa931dd95366add5dec367e', hex')) |
@srishidev10 You can't have a contract sign a tx between two parties. You have these options though:
More on that here. However, I think we diverged. @greggmojica should close this issue if the initial problems were solved. |
Please ask further questions on https://ethereum.stackexchange.com/ |
// This is my code after one week trying a lot of tutorials. Thanks internet const fs = require('fs'); /**
const main = async () => {
}; main(); |
What I dont understand is there any difference when you send token from one wallet address to other wallet address, and when you want to basically buy token with a wallet address from the smart contract of the token? |
I created a contract token using the sample solidity code tutorial. It has a function called transfer to send tokens between accounts:
function transfer(address _to, uint256 _value)
I need to now connect to this contract using web3, and then send a certain number of tokens generated to another account. I've been struggling with how to do this for quite some time and hoping this community could help. Here is what I have thus far, using web3 version 0.20.0:
This transaction works but it's sending ether as opposed to the actual ERC20 token. I'm really at a loss for why this is the case and would appreciate any help whatsoever.
The text was updated successfully, but these errors were encountered: