java TRC20

直接上代码!!!

创建地址(离线):

	private static SecureRandom random = new SecureRandom();
	/**具体方法
	*/
	public static Map<String, String> createAddress() {
			ECKey eCkey = new ECKey(random);
			String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes());
			byte[] addressBytes = eCkey.getAddress();
			String hexAddress = ByteArray.toHexString(addressBytes);
			Map<String, String> addressInfo = new HashMap<>(3);
			addressInfo.put("address", toViewAddress(hexAddress));
			addressInfo.put("hexAddress", hexAddress);
			addressInfo.put("privateKey", privateKey);
			return addressInfo;
		}

	/**
	 * 转换成T开头的地址
	 * @param hexAddress
	 * @return
	 */
	public static String toViewAddress(String hexAddress) {
		return encode58Check(ByteArray.fromHexString(hexAddress));
	}


ps:这里的参数都是明文,如需加密,自己搞定。

查余额(节点):


	/**
     * 查询数量
     */
    public BigDecimal balanceOf(String address) {
        String url = tronUrl +"/wallet/triggerconstantcontract";
        JSONObject param = new JSONObject();
        param.put("owner_address", TronUtils.toHexAddress(address));
        param.put("contract_address", TronUtils.toHexAddress(contract));
        param.put("function_selector", "balanceOf(address)");
        List<Type> inputParameters = new ArrayList<>();
        inputParameters.add(new Address(TronUtils.toHexAddress(address).substring(2)));
        param.put("parameter", FunctionEncoder.encodeConstructor(inputParameters));
        String result = HttpClientUtils.postJson(url, param.toJSONString());
        if (StringUtils.isNotEmpty(result)) {
            JSONObject obj = JSONObject.parseObject(result);
            JSONArray results = obj.getJSONArray("constant_result");
            if (results != null && results.size() > 0) {
                BigInteger amount = new BigInteger(results.getString(0), 16);
                return new BigDecimal(amount).divide(decimal, 6, RoundingMode.FLOOR);
            }
        }
        return BigDecimal.ZERO;
    }
/**
     * contract address
     */
    private String contract = "xxx";

这里的address必须是hex(16进制)类型地址,

根据PrivateKey获取地址

/**
	 * 根据私钥获取地址
	 *
	 * @param privateKey
	 * @return
	 */
	public static String getAddressByPrivateKey(String privateKey) {
		byte[] privateBytes = Hex.decode(privateKey);
		ECKey ecKey = ECKey.fromPrivate(privateBytes);
		byte[] from = ecKey.getAddress();
		return toViewAddress(Hex.toHexString(from));
	}

这个没什么特殊的。直接用就好了!

通过区块高度获取Transfer信息(归集用):

/**
     * 获取特定区块的所有Info 信息
     *
     * @return
     */
    private String getTransactionInfoByBlockNum(BigInteger num) {
        String url = tronUrl + "/wallet/gettransactioninfobyblocknum";
        Map<String, Object> map = new HashMap<>();
        map.put("num", num);
        String param = JSON.toJSONString(map);
        return HttpClientUtils.postJson(url, param);
    }

查询最新区块:

/**
     * 查询最新区块
     *
     * @return
     */
    public BigInteger getNowBlock() {
        String url = tronUrl + "/wallet/getnowblock";
        String httpRequest = HttpRequest.get(url).execute().body();
        JSONObject jsonObject1 = JSONObject.parseObject(httpRequest);
        return jsonObject1.getJSONObject("block_header").getJSONObject("raw_data").getBigInteger("number");
    }

根据hash,返回Transaction状态

/**
     * 返回状态
     */
    public boolean transactionStatus(String hash) {
        JSONObject parseObject = JSON.parseObject(getTransactionById(hash));
        if (StringUtils.isEmpty(parseObject.toJSONString())) {
            return false;
        }
        String contractRet = parseObject.getJSONArray("ret").getJSONObject(0).getString("contractRet");
        return "SUCCESS".equals(contractRet);
    }
    
/**
     * 通过HASH获取Transaction信息
     *
     * @param hash
     * @return
     */
    public String getTransactionById(String hash) {
        String url = tronUrl + "/walletsolidity/gettransactionbyid";
        Map<String, Object> map = new HashMap<>();
        map.put("value", hash);
        String param = JSON.toJSONString(map);
        return HttpClientUtils.postJson(url, param);
    }

重点!!!

/**
     * 
     *
     * @throws Throwable
     */
    public String sendTrc20(String privateKey, String toAddress, BigDecimal amount) throws Throwable {
        String ownerAddress = TronUtils.getAddressByPrivateKey(privateKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("contract_address", contract);
        jsonObject.put("function_selector", "transfer(address,uint256)");
        List<Type> inputParameters = new ArrayList<>();
        inputParameters.add(new Address(TronUtils.toHexAddress(toAddress).substring(2)));
        inputParameters.add(new Uint256(amount.multiply(decimal).toBigInteger()));
        String parameter = FunctionEncoder.encodeConstructor(inputParameters);
        jsonObject.put("parameter", parameter);
        jsonObject.put("owner_address", ownerAddress);
        jsonObject.put("call_value", 0);
        jsonObject.put("fee_limit", 50000000L);
        jsonObject.put("visible", true);
        String trans1 = HttpClientUtils.postJson(tronUrl + "/wallet/triggersmartcontract", jsonObject.toString());
        JSONObject result = JSONObject.parseObject(trans1);
        if (result.containsKey("Error")) {
            throw new DfzgRuntimeException(WestError.WEST_TIMEOUT);
        }
        JSONObject tx = result.getJSONObject("transaction");
        //填写备注
        tx.getJSONObject("raw_data").put("data", Hex.toHexString("备注信息".getBytes()));
        String txid = TronUtils.signAndBroadcast(tronUrl, privateKey, tx);
        if (txid != null) {
            return txid;
        }
        return null;
    }

有个需要注意的,不了解波场链机制的朋友,可以先在TronLink上转账模拟一下。波场链Transfer是需要能量和带宽的,如果需要归集的话,是需要给被归集的地址支付一些Trx的,不然不能Deal。

TRX Transfer

/**
     * TRX Transfer
     */
    public String sendTrx(BigDecimal amount,String toAddress,String note) throws Throwable {
        String url = tronUrl + "/wallet/createtransaction";
        JSONObject param = new JSONObject();
        String privateKey = "私钥";
        param.put("owner_address", TronUtils.getAddressByPrivateKey(privateKey));
        param.put("to_address",toAddress);
        param.put("amount",amount.multiply(decimal).toBigInteger());
        param.put("visible", true);
        String result = HttpClientUtils.postJson(url, param.toJSONString());
        if(StringUtils.isNotEmpty(result)){
            JSONObject transaction = JSONObject.parseObject(result);
            String error = transaction.getString("Error");
            if(!StringUtil.isEmpty(error) && error.contains("balance is not sufficient")){
                throw new DfzgRuntimeException(WestError.WEST_NO_MONEY);
            }else {
                transaction.getJSONObject("raw_data").put("data", Hex.toHexString(note.getBytes()));
                return TronUtils.signAndBroadcast(tronUrl, privateKey, transaction);
            }
        }
        throw new DfzgRuntimeException(WestError.WEST_TIMEOUT);
    }

TRX查询余额

/**
     * 查询TRX额度
     */
    public BigDecimal balanceOf(String address) {
        String url = tronUrl + "/wallet/getaccount";
        JSONObject param = new JSONObject();
        param.put("address", TronUtils.toHexAddress(address));
        String result = HttpClientUtils.postJson(url, param.toJSONString());
        BigInteger balance = BigInteger.ZERO;
        if (!StringUtils.isEmpty(result)) {
            JSONObject obj = JSONObject.parseObject(result);
            BigInteger b = obj.getBigInteger("balance");
            if(b != null){
                balance = b;
            }
        }
        return new BigDecimal(balance).divide(decimal,6, RoundingMode.FLOOR);
    }

好啦,以上这些就是我的全部内容。
希望大家用的开心~
欢迎打赏,想深入交流的可以加QQ:296563552

你可能感兴趣的:(java,区块链)