4

How to send custom ERC20 tokens from one wallet to another, if i want to send EBTC/ECASH custom ERC20 tokens.

I wrote a method that can send the ether from one account to another, how could i do the same for non ether transactions?

public static void sendCustomToken(String privateKey,String toAccount, double amount) throws Exception{ 

Web3j web3 = Web3j.build(new HttpService("http://localhost:8180/")); 
BigInteger key = new BigInteger(privateKey,16); 
ECKeyPair ecKeyPair = ECKeyPair.create(key.toByteArray()); 
Credentials credentials = Credentials.create(ecKeyPair); 
TransactionReceipt transactionReceipt = Transfer.sendFundsAsync( web3, credentials, toAccount, BigDecimal.valueOf(amount), Convert.Unit.ETHER).get(); 

System.out.println("Transaction Hash:"+transactionReceipt.getTransactionHash());
}

Custom Token: eBTC Contract Address: 0x2fd41f516fac94ed08e156f489f56ca3a80b04d0 Token Decimals: 8

Any help or pointers?

1

I assume you are using Web3j and a deployed smart contract implementing ERC20 interface, where transfer method looks like this:

function transfer(address _to, uint256 _value) public returns (bool success) {
    require(balances[msg.sender] >= _value && _value > 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
}

You can use web3j wrapper for your contract to call contract methods on a blockahain. Suppose your Contract filname is MyContract.sol, then you'll need solc compiler and web3j tool and do the following in your console:

$ solc {contract}.sol --bin --abi --optimize -o {output-dir}/

this will generate .abi and .bin files from which you generate a java wrapper class:

$ web3j solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name

This will produce a java wrapper class for your contract like MyContract.java on which you can call all the methods available on the smart contract:

import static org.web3j.tx.Contract.GAS_LIMIT;
import static org.web3j.tx.ManagedTransaction.GAS_PRICE;

//web3j initialization code goes here

//Load the deployed contract:
MyContract contract = MyContract.load(contractAddress, web3j, credentials,     GAS_PRICE, GAS_LIMIT);

//Call methods on the contract:
Future<> result = contract.transfer(_to, _value);

You can find more info on how to work with smart contracts wrappers here. Hope that helps.

edit. abi and bin for this particular contract can be obtained from etherscan.io You can transfer tokens even if you are not the owner of the contract. But you are only abe to transfer tokens available to your own account as seen in the contract:

 function transfer(address _to, uint256 _amount) returns (bool success) {
     if (balances[msg.sender] >= _amount 
        && _amount > 0
         && balances[_to] + _amount > balances[_to]) {
         balances[msg.sender] -= _amount;
         balances[_to] += _amount;
         Transfer(msg.sender, _to, _amount);
        return true;
     } else {
         return false;
     }
 }
  • no he's looking for transferring the custom ERC20 tokens (not the actual Ethers) from one account to another (or exchanges) with the help of Private Keys. The code he has given would transfer only ethers and he's looking now to transfer the custom ERC20 tokens (i.e., tokens developed on top of Ethereum blockchain). – Khaja Mohammed Oct 31 '17 at 12:49
  • I assume that ERC20 tokens is a standard interface implementation in a form of smart contract, which needs to be deployed on the blockchain. This interface supports methods to send custom tokens between accounts. All you need to do is to implement transfer method like shown in the example here and call it from whatever client you are using, Geth, Browser-Solidity or something. – ITisha Oct 31 '17 at 14:06
  • @ITisha Smart contract is already deployed on to the blockchain, if i have some custom tokens from this contract, how am i suppose to transfer them from one wallet address to another? p.s I am not the creator of the smart contract. – srikanth Oct 31 '17 at 14:26
  • @srikanth, oh I thing I get it now :) Check out this link. It describes how to get a java wrapper class for your contract for example you'll have a class like MyContract.class. The wrapper will have all the methods available on the contract: MyContract contract = MyContract.load(contractAddress, web3j, credentials, GAS_PRICE, GAS_LIMIT); Future<> result = contract.transfer(_to, _value); I'd suggest to check web3j docs, they are pretty useful. – ITisha Oct 31 '17 at 14:43
  • @srikanth I edited the original answer, hope that I don't miss the point completely :) – ITisha Oct 31 '17 at 15:01
1

Inspired by @ITisha, I have a more detailed example as below.

Assume we want to send some "dog coins" to another address as a contract owner.

Prepare work:

  1. MyContract.bin
  2. DogCoin.abi

Steps:

1.generate a java wrapper file from command line, notice that macOS and Linux may cause differences, Linux is recommended:

 web3j solidity generate /path/to/MyContract.bin /path/to/DogCoin.abi -o /path/to/src/main/DogCoin.java -p com.your.organisation.name

2.Then is our core function to transfer coins:

public class EthereumTest {


     public static void transferCoins (String toAccount, int coinAmount){


         // if testing, use https://ropsten.etherscan.io/address/[Your contract address]
         Web3j web3 = Web3j.build(new HttpService("https://mainnet.infura.io/[your contract]"));  
         try{

                Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
                String clientVersion = web3ClientVersion.getWeb3ClientVersion();
                System.out.println("clientVersion " + clientVersion);

                String privateKey = "[ contract owner privateKey ]";
                BigInteger key = new BigInteger(privateKey,16); 
                ECKeyPair ecKeyPair = ECKeyPair.create(key.toByteArray()); 
                Credentials credentials = Credentials.create(ecKeyPair); 


                TransactionReceiptProcessor transactionReceiptProcessor = new NoOpProcessor(web3);
                TransactionManager transactionManager = new RawTransactionManager(
                        web3, credentials, ChainId.MAINNET, transactionReceiptProcessor);
                //if testing, use ChainId.ROPSTEN

                // need to use the java wrapper filed generated before
                DogCoin mycontract = DogCoin.load("[Your contract address]", web3, transactionManager, GAS_PRICE, GAS_LIMIT);


                BigInteger _value = BigInteger.valueOf((long) (coinAmount *Math.pow(10, 8)) );


                 try {

                    TransactionReceipt  mReceipt = mycontract.transfer(toAccount, _value).sendAsync().get();

                    String sTransHash = mReceipt.getTransactionHash();


                    System.out.println("toAccount: " + toAccount + " coinAmount: " + coinAmount + " transactionhash: " + sTransHash)

                    // You can view the transaction record on https://etherscan.io/tx/[transaction hash]
                    // if testing , on https://ropsten.etherscan.io/tx/[transaction hash]
                } catch (Exception e) {
                    System.out.println("Ethereum Exception " + e.getMessage());

                }

            }catch(IOException e){
                System.out.println("Ethereum IOException " + e.getMessage());

            }
     }


    public static void main(String[] args) { // unit testing

        String toAccount = "0x1xxxyyyzzz...";

        int coinAmount = 1; // e.g 1 dog coin

        transferCoins(toAccount, coinAmount); 

    }
}

A few comments:

a. we use low-level transactionManager to achieve asyc solution, so we can get transaction hash right away when transaction is pending.

b. we can define our own GAS_PRICE and GAS_LIMIT, here we use the library default value

c. mycontract.transfer() is a method from the java wrapper code generated with the contract

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.