diff --git a/README.md b/README.md index 17fe600..80a6e91 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # web3j-sample -web3 for java 样例程序 +web3 for java 样例程序 (基于web3j 3.6.0) 环境 idea maven 运行前提 需要有一个开启RPC或者IPC服务的以太坊节点 @@ -15,5 +15,14 @@ web3 for java 样例程序 - [EthMnemonic](https://github.com/ethjava/web3j-sample/blob/master/src/main/java/com/ethjava/EthMnemonic.java) 生成、导入助记词(需要比特币的jar包 可以查看pom.xml) - [Filter](https://github.com/ethjava/web3j-sample/blob/master/src/main/java/com/ethjava/Filter.java) 新块、新交易相关监听 - [ContractEvent](https://github.com/ethjava/web3j-sample/blob/master/src/main/java/com/ethjava/ContractEvent.java) 执行合约相关log监听 +- [DecodeMessage](https://github.com/ethjava/web3j-sample/blob/master/src/main/java/com/ethjava/DecodeMessage.java) 加密后的交易数据解析 +- [IBAN](https://github.com/ethjava/web3j-sample/blob/master/src/main/java/com/ethjava/IBAN.java) 根据官方规则生成iban及付款二维码 +- [Calculate](https://github.com/ethjava/web3j-sample/blob/master/src/main/java/com/ethjava/Calculate.java) 在发布合约前计算合约地址,根据签名后的交易信息计算TxHash +- [Solidity](https://github.com/ethjava/web3j-sample/tree/master/src/main/java/com/ethjava/sol) 合约类相关 +- [LinkToken Support](https://github.com/ethjava/web3j-sample/tree/LinkToken) 链克支持 -基本功能demo已完成 +--- + +打赏 eth地址:0x248F272180db4D079443753336c5C847A080275c + +[博客Blog](https://blog.csdn.net/u011181222) \ No newline at end of file diff --git a/pom.xml b/pom.xml index f1656a3..66553f9 100644 --- a/pom.xml +++ b/pom.xml @@ -38,7 +38,7 @@ org.web3j core - 3.3.1 + 3.6.0 @@ -60,5 +60,11 @@ compile + + com.alibaba + fastjson + 1.2.31 + + diff --git a/src/main/java/com/ethjava/Calculate.java b/src/main/java/com/ethjava/Calculate.java new file mode 100644 index 0000000..e5a6676 --- /dev/null +++ b/src/main/java/com/ethjava/Calculate.java @@ -0,0 +1,46 @@ +package com.ethjava; + +import org.web3j.crypto.Hash; +import org.web3j.rlp.RlpEncoder; +import org.web3j.rlp.RlpList; +import org.web3j.rlp.RlpString; +import org.web3j.utils.Numeric; + +import java.util.Arrays; + +public class Calculate { + public static void main(String[] args) { + System.out.println(calculateContractAddress("0x6c0f49aF552F2326DD851b68832730CB7b6C0DaF".toLowerCase(), 294)); + + String signedData = "0xf8ac8201518506fc23ac00830493e094fda023cea60a9f421d74ac49f9a015880a77dd7280b844a9059cbb000000000000000000000000b5dbd2e4093a501f1d1e645f04cef5815a1581d7000000000000000000000000000000000000000000000004c53ecdc18a6000001ca03d710f3c5aabde2733938c44c0b1448f96e760c030205562f59889557397faa4a007110abbcfa343381a2f713d6339d3fa751200f82cc2f06a4d1967b4eaf61d50"; + System.out.println(caculateTransactionHash(signedData)); + } + + /** + * 发布前 计算合约地址 + */ + private static String calculateContractAddress(String address, long nonce) { + //样例 https://ropsten.etherscan.io/tx/0x728a95b02beec3de9fb09ede00ca8ca6939bad2ad26c702a8392074dc04844c7 + byte[] addressAsBytes = Numeric.hexStringToByteArray(address); + + byte[] calculatedAddressAsBytes = + Hash.sha3(RlpEncoder.encode( + new RlpList( + RlpString.create(addressAsBytes), + RlpString.create((nonce))))); + + calculatedAddressAsBytes = Arrays.copyOfRange(calculatedAddressAsBytes, + 12, calculatedAddressAsBytes.length); + String calculatedAddressAsHex = Numeric.toHexString(calculatedAddressAsBytes); + return calculatedAddressAsHex; + } + + /** + * 提交前 计算交易hash + */ + private static String caculateTransactionHash(String signedData) { + //样例 https://ropsten.etherscan.io/tx/0xfd8acd10d72127f29f0a01d8bcaf0165665b5598781fe01ca4bceaa6ab9f2cb0 + String txHash = Hash.sha3(signedData); + return txHash; + } +} diff --git a/src/main/java/com/ethjava/ContractEvent.java b/src/main/java/com/ethjava/ContractEvent.java index 6a83376..59bb116 100644 --- a/src/main/java/com/ethjava/ContractEvent.java +++ b/src/main/java/com/ethjava/ContractEvent.java @@ -33,13 +33,10 @@ public static void main(String[] args) { contractAddress); Event event = new Event("Transfer", Arrays.>asList( - new TypeReference
() { + new TypeReference
(true) { }, - new TypeReference
() { - } - ), - Arrays.>asList( - new TypeReference() { + new TypeReference
(true) { + }, new TypeReference(false) { } ) ); diff --git a/src/main/java/com/ethjava/DecodeMessage.java b/src/main/java/com/ethjava/DecodeMessage.java new file mode 100644 index 0000000..8648d3a --- /dev/null +++ b/src/main/java/com/ethjava/DecodeMessage.java @@ -0,0 +1,76 @@ +package com.ethjava; + +import org.web3j.crypto.*; +import org.web3j.rlp.RlpDecoder; +import org.web3j.rlp.RlpList; +import org.web3j.rlp.RlpString; +import org.web3j.rlp.RlpType; +import org.web3j.utils.Numeric; + +import java.math.BigInteger; +import java.security.SignatureException; +import java.util.List; + +public class DecodeMessage { + + /** + * 通过签名后会得到一个加密后的字符串 + * 本类将分析这个字符串 + */ + public static void main(String[] args) { + String signedData = "0xf8ac8201518506fc23ac00830493e094fda023cea60a9f421d74ac49f9a015880a77dd7280b844a9059cbb000000000000000000000000b5dbd2e4093a501f1d1e645f04cef5815a1581d7000000000000000000000000000000000000000000000004c53ecdc18a6000001ca03d710f3c5aabde2733938c44c0b1448f96e760c030205562f59889557397faa4a007110abbcfa343381a2f713d6339d3fa751200f82cc2f06a4d1967b4eaf61d50"; + decodeMessage(signedData); + decodeMessageV340(signedData); + } + + private static void decodeMessage(String signedData) { + //样例 https://ropsten.etherscan.io/tx/0xfd8acd10d72127f29f0a01d8bcaf0165665b5598781fe01ca4bceaa6ab9f2cb0 + try { + System.out.println(signedData); + System.out.println("解密 start " + System.currentTimeMillis()); + RlpList rlpList = RlpDecoder.decode(Numeric.hexStringToByteArray(signedData)); + List values = ((RlpList) rlpList.getValues().get(0)).getValues(); + BigInteger nonce = Numeric.toBigInt(((RlpString) values.get(0)).getBytes()); + BigInteger gasPrice = Numeric.toBigInt(((RlpString) values.get(1)).getBytes()); + BigInteger gasLimit = Numeric.toBigInt(((RlpString) values.get(2)).getBytes()); + String to = Numeric.toHexString(((RlpString) values.get(3)).getBytes()); + BigInteger value = Numeric.toBigInt(((RlpString) values.get(4)).getBytes()); + String data = Numeric.toHexString(((RlpString) values.get(5)).getBytes()); + RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, data); + RlpString v = (RlpString) values.get(6); + RlpString r = (RlpString) values.get(7); + RlpString s = (RlpString) values.get(8); + Sign.SignatureData signatureData = new Sign.SignatureData( + v.getBytes()[0], + Numeric.toBytesPadded(Numeric.toBigInt(r.getBytes()), 32), + Numeric.toBytesPadded(Numeric.toBigInt(s.getBytes()), 32)); + BigInteger pubKey = Sign.signedMessageToKey(TransactionEncoder.encode(rawTransaction), signatureData); + System.out.println("publicKey " + pubKey.toString(16)); + String address = Numeric.prependHexPrefix(Keys.getAddress(pubKey)); + System.out.println("address " + address); + System.out.println("解密 end " + System.currentTimeMillis()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 可以看到交易数据本身是没有加密的,是可以直接获取到。 + * v r s是用私钥加密的数据,利用v r s加上交易数据可以得到私钥对应的公钥及地址。 + * 所以RawTransaction里是没有fromAddress的参数的。 + * 解密出的地址就是发出交易的地址。这样一来完成了验证。 + */ + private static void decodeMessageV340(String signedData) { + System.out.println("解密 start " + System.currentTimeMillis()); + RawTransaction rawTransaction = TransactionDecoder.decode(signedData); + if (rawTransaction instanceof SignedRawTransaction) { + try { + String from = ((SignedRawTransaction) rawTransaction).getFrom(); + System.out.println("address " + from); + } catch (SignatureException e) { + e.printStackTrace(); + } + } + System.out.println("解密 end " + System.currentTimeMillis()); + } +} diff --git a/src/main/java/com/ethjava/IBAN.java b/src/main/java/com/ethjava/IBAN.java new file mode 100644 index 0000000..3f6ee47 --- /dev/null +++ b/src/main/java/com/ethjava/IBAN.java @@ -0,0 +1,115 @@ +package com.ethjava; + +import java.math.BigInteger; +import java.text.Format; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import static java.lang.Integer.parseInt; + +public class IBAN { + + /** + * 根据官方支持的IBAN规则生成二维码 目前支持的有imtoken kcash + * 参考url + * https://github.com/ethereum/web3.js/blob/develop/lib/web3/iban.js + * 可以防止地址错误(有两位校验和) + */ + public static void main(String[] args) { + getIBAN(); + } + + public static void getIBAN() { + String address = "0xaaae432f77a74a33c5e5b47612dabef44a905de6".toLowerCase(); + System.out.println(address); + address = address.substring(2); + BigInteger value = new BigInteger(address, 16); + StringBuilder bban = new StringBuilder(value.toString(36).toUpperCase()); + while (bban.length() < 15 * 2) { + bban.insert(0, '0'); + } + System.out.println("bban " + bban); + String iban = "XE00" + bban; + + iban = iban.substring(4) + iban.substring(0, 4); + StringBuilder code = new StringBuilder(); + for (int i = 0; i < iban.length(); i++) { + char chr = iban.charAt(i); + if (chr >= 'A' && chr <= 'Z') { + int temp = chr - 'A' + 10; + code.append(String.valueOf(temp)); + } else { + code.append(String.valueOf((chr - '0'))); + } + } +// System.out.println(code); + String remainder = code.toString(); + String block; + while (remainder.length() > 2) { + int endPoint = remainder.length() >= 9 ? 9 : remainder.length(); + block = remainder.substring(0, endPoint); + remainder = parseInt(block, 10) % 97 + remainder.substring(block.length()); +// System.out.println(remainder); + } + + int checkNum = parseInt(remainder, 10) % 97; + String checkDigit = ("0" + (98 - checkNum)); + checkDigit = checkDigit.substring(checkDigit.length() - 2); +// System.out.println(checkDigit); + String IBAN = "XE" + checkDigit + bban; + String qrCodeString = "iban:" + IBAN + "?token=ETH&amount=5"; + System.out.println("IBAN " + IBAN); + System.out.println("验证 " + validateIBAN(IBAN)); + System.out.println("qrcode " + qrCodeString); + decodeQRString(qrCodeString); + } + + private static boolean validateIBAN(String iban) { + int len = iban.length(); + if (len < 4 || !iban.matches("[0-9A-Z]+")) + return false; + + iban = iban.substring(4) + iban.substring(0, 4); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < len; i++) + sb.append(Character.digit(iban.charAt(i), 36)); + + BigInteger bigInt = new BigInteger(sb.toString()); + + return bigInt.mod(BigInteger.valueOf(97)).intValue() == 1; + } + + private static void decodeQRString(String result) { + int ibanEndpoint = result.indexOf("?"); + String iban = result.substring(5, ibanEndpoint < 0 ? result.length() : ibanEndpoint); + String address = IBAN2Address(iban); + String query = result.substring(ibanEndpoint + 1, result.length()); + String[] params = query.split("&"); + String token = null; + String amount = null; + for (String param : params) { + if (param.startsWith("token=")) { + token = param.substring(6); + continue; + } + if (param.startsWith("amount=")) { + amount = param.substring(7); + } + } + System.out.println("decodeQRString"); + System.out.println("address " + address); + System.out.println("token " + token); + System.out.println("amount " + address); + } + + private static String IBAN2Address(String iban) { + String base36 = iban.substring(4); + StringBuilder base16 = new StringBuilder(new BigInteger(base36, 36).toString(16)); + while (base16.length() < 40) { + base16.insert(0, "0"); + } + return "0x" + base16.toString().toLowerCase(); + } +} diff --git a/src/main/java/com/ethjava/TokenClient.java b/src/main/java/com/ethjava/TokenClient.java index b4b06ac..b8b9e19 100644 --- a/src/main/java/com/ethjava/TokenClient.java +++ b/src/main/java/com/ethjava/TokenClient.java @@ -7,6 +7,7 @@ import org.web3j.abi.datatypes.*; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.abi.datatypes.generated.Uint8; +import org.web3j.crypto.Hash; import org.web3j.protocol.Web3j; import org.web3j.protocol.admin.Admin; import org.web3j.protocol.admin.methods.response.PersonalUnlockAccount; @@ -16,12 +17,17 @@ import org.web3j.protocol.core.methods.response.EthGetTransactionCount; import org.web3j.protocol.core.methods.response.EthSendTransaction; import org.web3j.protocol.http.HttpService; +import org.web3j.rlp.RlpEncoder; +import org.web3j.rlp.RlpList; +import org.web3j.rlp.RlpString; import org.web3j.utils.Convert; +import org.web3j.utils.Numeric; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; @@ -49,8 +55,8 @@ public static void main(String[] args) { System.out.println(getTokenSymbol(web3j, contractAddress)); System.out.println(getTokenTotalSupply(web3j, contractAddress)); System.out.println(sendTokenTransaction( - fromAddress,"yzw", - "0x6c0f49aF552F2326DD851b68832730CB7b6C0DaF",contractAddress, + fromAddress, "yzw", + "0x6c0f49aF552F2326DD851b68832730CB7b6C0DaF", contractAddress, BigInteger.valueOf(100000))); } @@ -223,7 +229,7 @@ public static BigInteger getTokenTotalSupply(Web3j web3j, String contractAddress /** * 代币转账 */ - public static String sendTokenTransaction(String fromAddress, String password, String toAddress, String contractAddress,BigInteger amount) { + public static String sendTokenTransaction(String fromAddress, String password, String toAddress, String contractAddress, BigInteger amount) { String txHash = null; try { @@ -265,4 +271,5 @@ public static String sendTokenTransaction(String fromAddress, String password, S return txHash; } + } diff --git a/src/main/java/com/ethjava/TransactionClient.java b/src/main/java/com/ethjava/TransactionClient.java index 3c5c214..7c6e913 100644 --- a/src/main/java/com/ethjava/TransactionClient.java +++ b/src/main/java/com/ethjava/TransactionClient.java @@ -139,5 +139,5 @@ private static String sendTransaction() { return txHash; } - // TODO: 2018/3/13 使用 web3j.ethSendRawTransaction() 发送交易 需要用私钥自签名交易 + //使用 web3j.ethSendRawTransaction() 发送交易 需要用私钥自签名交易 详见ColdWallet.java } diff --git a/src/main/java/com/ethjava/sol/SolSample.java b/src/main/java/com/ethjava/sol/SolSample.java new file mode 100644 index 0000000..b7fb387 --- /dev/null +++ b/src/main/java/com/ethjava/sol/SolSample.java @@ -0,0 +1,54 @@ +package com.ethjava.sol; + +import com.ethjava.utils.Environment; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.RemoteCall; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.protocol.http.HttpService; +import org.web3j.utils.Convert; + +import java.math.BigInteger; + +public class SolSample { + public static void main(String[] args) { + deploy(); + use(); + } + + private static void deploy() { + Web3j web3j = Web3j.build(new HttpService(Environment.RPC_URL)); + Credentials credentials = null;//可以根据私钥生成 + RemoteCall deploy = TokenERC20.deploy(web3j, credentials, + Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(), + BigInteger.valueOf(3000000), + BigInteger.valueOf(5201314), + "my token", "mt"); + try { + TokenERC20 tokenERC20 = deploy.send(); + tokenERC20.isValid(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + private static void use() { + Web3j web3j = Web3j.build(new HttpService(Environment.RPC_URL)); + String contractAddress = null; + Credentials credentials = null;//可以根据私钥生成 + TokenERC20 contract = TokenERC20.load(contractAddress, web3j, credentials, + Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(), + BigInteger.valueOf(100000)); + String myAddress = null; + String toAddress = null; + BigInteger amount = BigInteger.ONE; + try { + BigInteger balance = contract.balanceOf(myAddress).send(); + TransactionReceipt receipt = contract.transfer(toAddress, amount).send(); + //etc.. + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/ethjava/sol/TokenERC20.java b/src/main/java/com/ethjava/sol/TokenERC20.java new file mode 100644 index 0000000..98b4064 --- /dev/null +++ b/src/main/java/com/ethjava/sol/TokenERC20.java @@ -0,0 +1,287 @@ +package com.ethjava.sol; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.web3j.abi.EventEncoder; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.TypeReference; +import org.web3j.abi.datatypes.Address; +import org.web3j.abi.datatypes.Event; +import org.web3j.abi.datatypes.Function; +import org.web3j.abi.datatypes.Type; +import org.web3j.abi.datatypes.Utf8String; +import org.web3j.abi.datatypes.generated.Uint256; +import org.web3j.abi.datatypes.generated.Uint8; +import org.web3j.crypto.Credentials; +import org.web3j.protocol.Web3j; +import org.web3j.protocol.core.DefaultBlockParameter; +import org.web3j.protocol.core.RemoteCall; +import org.web3j.protocol.core.methods.request.EthFilter; +import org.web3j.protocol.core.methods.response.Log; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.tx.Contract; +import org.web3j.tx.TransactionManager; +import rx.Observable; +import rx.functions.Func1; + +/** + *

Auto generated code. + *

Do not modify! + *

Please use the web3j command line tools, + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the + * codegen module to update. + * + *

Generated with web3j version 3.4.0. + */ +public class TokenERC20 extends Contract { + private static final String BINARY = "60806040526002805460ff1916601217905534801561001d57600080fd5b506040516109c63803806109c683398101604090815281516020808401518385015160025460ff16600a0a84026003819055336000908152600485529586205590850180519395909491019261007592850190610092565b508051610089906001906020840190610092565b5050505061012d565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100d357805160ff1916838001178555610100565b82800160010185558215610100579182015b828111156101005782518255916020019190600101906100e5565b5061010c929150610110565b5090565b61012a91905b8082111561010c5760008155600101610116565b90565b61088a8061013c6000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100be578063095ea7b31461014857806318160ddd1461018057806323b872dd146101a7578063313ce567146101d157806342966c68146101fc57806370a082311461021457806379cc67901461023557806395d89b4114610259578063a9059cbb1461026e578063cae9ca5114610294578063dd62ed3e146102fd575b600080fd5b3480156100ca57600080fd5b506100d3610324565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561010d5781810151838201526020016100f5565b50505050905090810190601f16801561013a5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561015457600080fd5b5061016c600160a060020a03600435166024356103b2565b604080519115158252519081900360200190f35b34801561018c57600080fd5b506101956103df565b60408051918252519081900360200190f35b3480156101b357600080fd5b5061016c600160a060020a03600435811690602435166044356103e5565b3480156101dd57600080fd5b506101e6610454565b6040805160ff9092168252519081900360200190f35b34801561020857600080fd5b5061016c60043561045d565b34801561022057600080fd5b50610195600160a060020a03600435166104d5565b34801561024157600080fd5b5061016c600160a060020a03600435166024356104e7565b34801561026557600080fd5b506100d36105b8565b34801561027a57600080fd5b50610292600160a060020a0360043516602435610612565b005b3480156102a057600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845261016c948235600160a060020a03169460248035953695946064949201919081908401838280828437509497506106219650505050505050565b34801561030957600080fd5b50610195600160a060020a036004358116906024351661073a565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103aa5780601f1061037f576101008083540402835291602001916103aa565b820191906000526020600020905b81548152906001019060200180831161038d57829003601f168201915b505050505081565b336000908152600560209081526040808320600160a060020a039590951683529390529190912055600190565b60035481565b600160a060020a038316600090815260056020908152604080832033845290915281205482111561041557600080fd5b600160a060020a038416600090815260056020908152604080832033845290915290208054839003905561044a848484610757565b5060019392505050565b60025460ff1681565b3360009081526004602052604081205482111561047957600080fd5b3360008181526004602090815260409182902080548690039055600380548690039055815185815291517fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca59281900390910190a2506001919050565b60046020526000908152604090205481565b600160a060020a03821660009081526004602052604081205482111561050c57600080fd5b600160a060020a038316600090815260056020908152604080832033845290915290205482111561053c57600080fd5b600160a060020a0383166000818152600460209081526040808320805487900390556005825280832033845282529182902080548690039055600380548690039055815185815291517fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca59281900390910190a250600192915050565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103aa5780601f1061037f576101008083540402835291602001916103aa565b61061d338383610757565b5050565b60008361062e81856103b2565b15610732576040517f8f4ffcb10000000000000000000000000000000000000000000000000000000081523360048201818152602483018790523060448401819052608060648501908152875160848601528751600160a060020a03871695638f4ffcb195948b94938b939192909160a490910190602085019080838360005b838110156106c65781810151838201526020016106ae565b50505050905090810190601f1680156106f35780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b15801561071557600080fd5b505af1158015610729573d6000803e3d6000fd5b50505050600191505b509392505050565b600560209081526000928352604080842090915290825290205481565b6000600160a060020a038316151561076e57600080fd5b600160a060020a03841660009081526004602052604090205482111561079357600080fd5b600160a060020a038316600090815260046020526040902054828101116107b957600080fd5b50600160a060020a038083166000818152600460209081526040808320805495891680855282852080548981039091559486905281548801909155815187815291519390950194927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a3600160a060020a0380841660009081526004602052604080822054928716825290205401811461085857fe5b505050505600a165627a7a72305820a699795c1a251457c903be9b4228f16928a18279fb1c6adc9eadefb8a46ae9060029"; + + public static final String FUNC_NAME = "name"; + + public static final String FUNC_APPROVE = "approve"; + + public static final String FUNC_TOTALSUPPLY = "totalSupply"; + + public static final String FUNC_TRANSFERFROM = "transferFrom"; + + public static final String FUNC_DECIMALS = "decimals"; + + public static final String FUNC_BURN = "burn"; + + public static final String FUNC_BALANCEOF = "balanceOf"; + + public static final String FUNC_BURNFROM = "burnFrom"; + + public static final String FUNC_SYMBOL = "symbol"; + + public static final String FUNC_TRANSFER = "transfer"; + + public static final String FUNC_APPROVEANDCALL = "approveAndCall"; + + public static final String FUNC_ALLOWANCE = "allowance"; + + public static final Event TRANSFER_EVENT = new Event("Transfer", + Arrays.>asList(new TypeReference

(true) {}, new TypeReference
(true) {},new TypeReference(false) {})); + ; + + public static final Event BURN_EVENT = new Event("Burn", + Arrays.>asList(new TypeReference
(true) {},new TypeReference(false) {})); + ; + + protected TokenERC20(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected TokenERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public RemoteCall name() { + final Function function = new Function(FUNC_NAME, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall approve(String _spender, BigInteger _value) { + final Function function = new Function( + FUNC_APPROVE, + Arrays.asList(new Address(_spender), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall totalSupply() { + final Function function = new Function(FUNC_TOTALSUPPLY, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall transferFrom(String _from, String _to, BigInteger _value) { + final Function function = new Function( + FUNC_TRANSFERFROM, + Arrays.asList(new Address(_from), + new Address(_to), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall decimals() { + final Function function = new Function(FUNC_DECIMALS, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall burn(BigInteger _value) { + final Function function = new Function( + FUNC_BURN, + Arrays.asList(new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall balanceOf(String param0) { + final Function function = new Function(FUNC_BALANCEOF, + Arrays.asList(new Address(param0)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall burnFrom(String _from, BigInteger _value) { + final Function function = new Function( + FUNC_BURNFROM, + Arrays.asList(new Address(_from), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall symbol() { + final Function function = new Function(FUNC_SYMBOL, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall transfer(String _to, BigInteger _value) { + final Function function = new Function( + FUNC_TRANSFER, + Arrays.asList(new Address(_to), + new Uint256(_value)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall approveAndCall(String _spender, BigInteger _value, byte[] _extraData) { + final Function function = new Function( + FUNC_APPROVEANDCALL, + Arrays.asList(new Address(_spender), + new Uint256(_value), + new org.web3j.abi.datatypes.DynamicBytes(_extraData)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall allowance(String param0, String param1) { + final Function function = new Function(FUNC_ALLOWANCE, + Arrays.asList(new Address(param0), + new Address(param1)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialSupply, String tokenName, String tokenSymbol) { + String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new Uint256(initialSupply), + new Utf8String(tokenName), + new Utf8String(tokenSymbol))); + return deployRemoteCall(TokenERC20.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger initialSupply, String tokenName, String tokenSymbol) { + String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new Uint256(initialSupply), + new Utf8String(tokenName), + new Utf8String(tokenSymbol))); + return deployRemoteCall(TokenERC20.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + public List getTransferEvents(TransactionReceipt transactionReceipt) { + List valueList = extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + TransferEventResponse typedResponse = new TransferEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable transferEventObservable(EthFilter filter) { + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public TransferEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(TRANSFER_EVENT, log); + TransferEventResponse typedResponse = new TransferEventResponse(); + typedResponse.log = log; + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public Observable transferEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT)); + return transferEventObservable(filter); + } + + public List getBurnEvents(TransactionReceipt transactionReceipt) { + List valueList = extractEventParametersWithLog(BURN_EVENT, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (EventValuesWithLog eventValues : valueList) { + BurnEventResponse typedResponse = new BurnEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Observable burnEventObservable(EthFilter filter) { + return web3j.ethLogObservable(filter).map(new Func1() { + @Override + public BurnEventResponse call(Log log) { + EventValuesWithLog eventValues = extractEventParametersWithLog(BURN_EVENT, log); + BurnEventResponse typedResponse = new BurnEventResponse(); + typedResponse.log = log; + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + }); + } + + public Observable burnEventObservable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(BURN_EVENT)); + return burnEventObservable(filter); + } + + public static TokenERC20 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return new TokenERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + public static TokenERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { + return new TokenERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static class TransferEventResponse { + public Log log; + + public String from; + + public String to; + + public BigInteger value; + } + + public static class BurnEventResponse { + public Log log; + + public String from; + + public BigInteger value; + } +} diff --git a/src/main/java/com/ethjava/sol/erc20_example.sol b/src/main/java/com/ethjava/sol/erc20_example.sol new file mode 100644 index 0000000..48a5976 --- /dev/null +++ b/src/main/java/com/ethjava/sol/erc20_example.sol @@ -0,0 +1,153 @@ +pragma solidity ^0.4.16; + +interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } + +contract TokenERC20 { + // Public variables of the token + string public name; + string public symbol; + uint8 public decimals = 18; + // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constructor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + function TokenERC20( + uint256 initialSupply, + string tokenName, + string tokenSymbol + ) public { + totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount + balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != 0x0); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to] + _value > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from] + balanceOf[_to]; + // Subtract from the sender + balanceOf[_from] -= _value; + // Add the same to the recipient + balanceOf[_to] += _value; + Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from] + balanceOf[_to] == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public { + _transfer(msg.sender, _to, _value); + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` on behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] -= _value; + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens on your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Set allowance for other address and notify + * + * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + * @param _extraData some extra information to send to the approved contract + */ + function approveAndCall(address _spender, uint256 _value, bytes _extraData) + public + returns (bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] -= _value; // Subtract from the sender + totalSupply -= _value; // Updates totalSupply + Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] -= _value; // Subtract from the targeted balance + allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance + totalSupply -= _value; // Update totalSupply + Burn(_from, _value); + return true; + } +}