引き続きユーティリティクラスの作成です。
Walletに最低限必要な以下4つのメソッドを実装します。
getaccountaddress
getbalance
listtransactions
sendfrom
まず、JSONRequestクラスですが、メンバ変数はString型のid、method、List<Object>型のparamsです。
idはレスポンスに同じidが含まれて返ってくるだけで、取り合えずは使わないのでハードコードしてしまいます。
methodはそれぞれのメソッド文字列を保持します。
paramsはメソッドにより異なり、sendfromでは送り先アドレスや金額もこのparamsに保持させます。
- getaccountaddress
アカウント文字列を渡すと、アカウントの最新の受信用アドレスを返します。
public static String getaccountaddress(String accountStr) throws IOException, CoindException {
String method = "getaccountaddress";
List<Object> params = new ArrayList<>();
params.add(accountStr);
JSONResponse addressRes = connectCoind(createJSONString("1", method, params));
return addressRes.result.toString();
}
- getbalance
アカウント文字列を渡すと、アカウントの残高を返します。
public static String getbalance(String accountStr) throws IOException, CoindException {
String method = "getbalance";
List<Object> params = new ArrayList<>();
params.add(accountStr);
JSONResponse balanceRes = connectCoind(createJSONString("1", method, params));
return balanceRes.result.toString();
}
- listtransactions
アカウント文字列を渡すと、トランザクション履歴を返します。
何件目から何件目までという取得の仕方も可能ですが、今回は実装しません。
public static List<Map<String, String>> listtransactions(String accountStr) throws IOException, CoindException {
String method = "listtransactions";
List<Object> params = new ArrayList<>();
params.add(accountStr);
JSONResponse transactionsRes = connectCoind(createJSONString("1", method, params));
return (List<Map<String, String>>) transactionsRes.result;
}
- sendfrom
アカウント文字列、送信先アドレス、金額を渡し、成功するとそのトランザクションIDを返します。
送信先アドレスの無効、金額不足など、エラーの発生しやすいメソッドです。
public static String sendfrom(String accountStr, String toAddress, double amount) throws IOException, CoindException {
String method = "sendfrom";
List<Object> params = new ArrayList<>();
params.add(accountStr);
params.add(toAddress);
params.add(amount);
JSONResponse sendRes = connectCoind(createJSONString("1", method, params));
return sendRes.result.toString();
}
ちなみにアカウント名を空文字列にすれば、アカウント名を指定しなかったことになって残高などWallet全体の数字になるかと思いきや、空文字列もアカウントとしては有効で、空文字アカウントの残高が返されます。
エラー周辺で結構ハマりましたが、これで一通り必要な機能が実装できました。
0 コメント:
コメントを投稿