From b63feeed17ec34d69589974b3238d7bb4edf91e7 Mon Sep 17 00:00:00 2001 From: henry Date: Sun, 28 Jan 2018 21:18:38 -0400 Subject: [PATCH] Added ManagerRequest to make the code full async --- .../BitsharesFaucetApiGenerator.java | 44 +-- .../apigenerator/GrapheneApiGenerator.java | 58 ++- .../crystalwallet/dao/TransactionDao.java | 4 + .../manager/BitsharesAccountManager.java | 343 ++++++++++-------- .../manager/CryptoAccountManager.java | 4 +- .../crystalwallet/manager/ManagerRequest.java | 12 + 6 files changed, 244 insertions(+), 221 deletions(-) create mode 100644 app/src/main/java/cy/agorise/crystalwallet/manager/ManagerRequest.java diff --git a/app/src/main/java/cy/agorise/crystalwallet/apigenerator/BitsharesFaucetApiGenerator.java b/app/src/main/java/cy/agorise/crystalwallet/apigenerator/BitsharesFaucetApiGenerator.java index ec99d7c..8aa4b56 100644 --- a/app/src/main/java/cy/agorise/crystalwallet/apigenerator/BitsharesFaucetApiGenerator.java +++ b/app/src/main/java/cy/agorise/crystalwallet/apigenerator/BitsharesFaucetApiGenerator.java @@ -37,8 +37,9 @@ public abstract class BitsharesFaucetApiGenerator { * @param url The url of the faucet * @return The bitshares id of the registered account, or null */ - public static boolean registerBitsharesAccount(String accountName, String ownerKey, - String activeKey, String memoKey, String url){ + public static void registerBitsharesAccount(String accountName, String ownerKey, + String activeKey, String memoKey, String url, + final ApiRequest request){ CreateAccountPetition petition = new CreateAccountPetition(); final Account account = new Account(); account.name=accountName; @@ -62,8 +63,7 @@ public abstract class BitsharesFaucetApiGenerator { HashMap hashMap = new HashMap<>(); hashMap.put("account", hm); - final boolean[] answer = {false}; - final Object SYNC = new Object(); + try { ServiceGenerator sg = new ServiceGenerator(url); IWebService service = sg.getService(IWebService.class); @@ -78,56 +78,36 @@ public abstract class BitsharesFaucetApiGenerator { if (resp.account != null) { try { if(resp.account.name.equals(account.name)) { - synchronized (SYNC){ - answer[0] = true; - SYNC.notifyAll(); - } + request.getListener().success(true,request.getId()); }else{ - System.out.println("ERROR account name different" + resp.account.name); - //ERROR - synchronized (SYNC) { - SYNC.notifyAll(); - } + request.getListener().fail(request.getId()); } } catch (Exception e) { e.printStackTrace(); - synchronized (SYNC) { - SYNC.notifyAll(); - } + request.getListener().fail(request.getId()); } }else{ System.out.println("ERROR response doesn't have account " + response.message()); - //ERROR - synchronized (SYNC) { - SYNC.notifyAll(); - } + request.getListener().fail(request.getId()); } }else{ System.out.println("ERROR fetching info"); - //ERROR - synchronized (SYNC) { - SYNC.notifyAll(); - } + request.getListener().fail(request.getId()); } } @Override public void onFailure(Call call, Throwable t) { t.printStackTrace(); - synchronized (SYNC) { - SYNC.notifyAll(); - } + request.getListener().fail(request.getId()); } }); - synchronized (SYNC) { - SYNC.wait(60000); - } } catch (Exception e) { e.printStackTrace(); - } + request.getListener().fail(request.getId()); - return answer[0]; + } } /** diff --git a/app/src/main/java/cy/agorise/crystalwallet/apigenerator/GrapheneApiGenerator.java b/app/src/main/java/cy/agorise/crystalwallet/apigenerator/GrapheneApiGenerator.java index 15ea05f..8272895 100644 --- a/app/src/main/java/cy/agorise/crystalwallet/apigenerator/GrapheneApiGenerator.java +++ b/app/src/main/java/cy/agorise/crystalwallet/apigenerator/GrapheneApiGenerator.java @@ -12,8 +12,6 @@ import cy.agorise.crystalwallet.dao.BitsharesAssetDao; import cy.agorise.crystalwallet.dao.CryptoCoinBalanceDao; import cy.agorise.crystalwallet.dao.CryptoCurrencyDao; import cy.agorise.crystalwallet.dao.CrystalDatabase; -import cy.agorise.crystalwallet.dao.TransactionDao; -import cy.agorise.crystalwallet.manager.BitsharesAccountManager; import cy.agorise.crystalwallet.models.BitsharesAsset; import cy.agorise.crystalwallet.models.BitsharesAssetInfo; import cy.agorise.crystalwallet.models.CryptoCoinBalance; @@ -43,11 +41,9 @@ import cy.agorise.graphenej.api.TransactionBroadcastSequence; import cy.agorise.graphenej.interfaces.NodeErrorListener; import cy.agorise.graphenej.interfaces.SubscriptionListener; import cy.agorise.graphenej.interfaces.WitnessResponseListener; -import cy.agorise.graphenej.models.AccountBalanceUpdate; import cy.agorise.graphenej.models.AccountProperties; import cy.agorise.graphenej.models.BaseResponse; import cy.agorise.graphenej.models.BroadcastedTransaction; -import cy.agorise.graphenej.models.HistoricalTransfer; import cy.agorise.graphenej.models.SubscriptionResponse; import cy.agorise.graphenej.models.WitnessResponse; import cy.agorise.graphenej.operations.TransferOperation; @@ -353,12 +349,10 @@ public abstract class GrapheneApiGenerator { */ public static void subscribeBitsharesAccount(final long accountId, final String accountBitsharesId, final Context context){ - System.out.println("GrapheneAPI subscribe to account balance update"); if(!currentBitsharesListener.containsKey(accountId)){ CrystalDatabase db = CrystalDatabase.getAppDatabase(context); final BitsharesAssetDao bitsharesAssetDao = db.bitsharesAssetDao(); final CryptoCurrencyDao cryptoCurrencyDao = db.cryptoCurrencyDao(); - final TransactionDao transactionDao = db.transactionDao(); SubscriptionListener balanceListener = new SubscriptionListener() { @Override public ObjectType getInterestObjectType() { @@ -374,16 +368,15 @@ public abstract class GrapheneApiGenerator { BroadcastedTransaction transactionUpdate = (BroadcastedTransaction) update; for(BaseOperation operation : transactionUpdate.getTransaction().getOperations()){ if(operation instanceof TransferOperation){ - TransferOperation tOperation = (TransferOperation) operation; + final TransferOperation tOperation = (TransferOperation) operation; if(tOperation.getFrom().getObjectId().equals(accountBitsharesId) || tOperation.getTo().getObjectId().equals(accountBitsharesId)){ GrapheneApiGenerator.getAccountBalance(accountId,accountBitsharesId,context); - CryptoCoinTransaction transaction = new CryptoCoinTransaction(); + final CryptoCoinTransaction transaction = new CryptoCoinTransaction(); transaction.setAccountId(accountId); transaction.setAmount(tOperation.getAssetAmount().getAmount().longValue()); BitsharesAssetInfo info = bitsharesAssetDao.getBitsharesAssetInfoById(tOperation.getAssetAmount().getAsset().getObjectId()); if (info == null) { //The cryptoCurrency is not in the database, queringfor its data - final Object SYNC = new Object(); //Object to syn the answer ApiRequest assetRequest = new ApiRequest(0, new ApiRequestListener() { @Override public void success(Object answer, int idPetition) { @@ -394,40 +387,21 @@ public abstract class GrapheneApiGenerator { info.setCryptoCurrencyId(idCryptoCurrency); asset.setId((int)idCryptoCurrency); bitsharesAssetDao.insertBitsharesAssetInfo(info); - } - synchronized (SYNC){ - SYNC.notifyAll(); + saveTransaction(transaction,(int)info.getCryptoCurrencyId(),accountBitsharesId,tOperation,context); } } @Override public void fail(int idPetition) { - synchronized (SYNC){ - SYNC.notifyAll(); - } + //TODO error retrieving asset } }); ArrayList assets = new ArrayList<>(); assets.add(tOperation.getAssetAmount().getAsset().getObjectId()); GrapheneApiGenerator.getAssetById(assets,assetRequest); - - synchronized (SYNC){ - try {SYNC.wait(60000);} catch (InterruptedException ignore) {} - } - info = bitsharesAssetDao.getBitsharesAssetInfoById(tOperation.getAssetAmount().getAsset().getObjectId()); + }else{ + saveTransaction(transaction,(int)info.getCryptoCurrencyId(),accountBitsharesId,tOperation,context); } - if( info == null){ - //We couldn't retrieve the cryptocurrency - return; - } - transaction.setIdCurrency((int)info.getCryptoCurrencyId()); - transaction.setConfirmed(true); //graphene transaction are always confirmed - transaction.setFrom(tOperation.getFrom().getObjectId()); - transaction.setInput(!tOperation.getFrom().getObjectId().equals(accountBitsharesId)); - transaction.setTo(tOperation.getTo().getObjectId()); - transaction.setDate(new Date()); - transactionDao.insertTransaction(transaction); - //GrapheneApiGenerator.getBlockHeaderTime(, new ApiRequest(0, new BitsharesAccountManager.GetTransactionDate(transaction, db.transactionDao()))); } } } @@ -449,6 +423,26 @@ public abstract class GrapheneApiGenerator { } } + /** + * Fucniton to save a transaction retrieved from the update + * @param transaction The transaction db object + * @param currencyId The id of the currency on the database + * @param accountBitsharesId The id of the account in the bitshares network + * @param tOperation The transfer operation fetched from the update + * @param context The context of this app + */ + private static void saveTransaction(CryptoCoinTransaction transaction, int currencyId, + String accountBitsharesId, TransferOperation tOperation , + Context context){ + transaction.setIdCurrency(currencyId); + transaction.setConfirmed(true); //graphene transaction are always confirmed + transaction.setFrom(tOperation.getFrom().getObjectId()); + transaction.setInput(!tOperation.getFrom().getObjectId().equals(accountBitsharesId)); + transaction.setTo(tOperation.getTo().getObjectId()); + transaction.setDate(new Date()); + CrystalDatabase.getAppDatabase(context).transactionDao().insertTransaction(transaction); + } + /** * Cancels all bitshares account subscriptions */ diff --git a/app/src/main/java/cy/agorise/crystalwallet/dao/TransactionDao.java b/app/src/main/java/cy/agorise/crystalwallet/dao/TransactionDao.java index 5b6673a..151b9f9 100644 --- a/app/src/main/java/cy/agorise/crystalwallet/dao/TransactionDao.java +++ b/app/src/main/java/cy/agorise/crystalwallet/dao/TransactionDao.java @@ -7,6 +7,7 @@ import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; +import java.util.Date; import java.util.List; import cy.agorise.crystalwallet.models.CryptoCoinTransaction; @@ -32,6 +33,9 @@ public interface TransactionDao { @Query("SELECT * FROM crypto_coin_transaction WHERE id = :id") LiveData getById(long id); + @Query("SELECT * FROM crypto_coin_transaction WHERE date = :date and 'from' = :from and 'to' = :to and amount = :amount ") + CryptoCoinTransaction getByTransaction(Date date, String from, String to, long amount); + @Insert(onConflict = OnConflictStrategy.REPLACE) public long[] insertTransaction(CryptoCoinTransaction... transactions); diff --git a/app/src/main/java/cy/agorise/crystalwallet/manager/BitsharesAccountManager.java b/app/src/main/java/cy/agorise/crystalwallet/manager/BitsharesAccountManager.java index b7757bc..36048fc 100644 --- a/app/src/main/java/cy/agorise/crystalwallet/manager/BitsharesAccountManager.java +++ b/app/src/main/java/cy/agorise/crystalwallet/manager/BitsharesAccountManager.java @@ -57,103 +57,151 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI private final static String BITSHARES_TESTNET_CHAIN_ID= "9cf6f255a208100d2bb275a3c52f4b1589b7ec9c9bfc2cb2a5fe6411295106d8"; @Override - public CryptoNetAccount createAccountFromSeed(CryptoNetAccount account, Context context) { + public void createAccountFromSeed(CryptoNetAccount account, final ManagerRequest request, final Context context) { if(account instanceof GrapheneAccount) { - GrapheneAccount grapheneAccount = (GrapheneAccount) account; - boolean created = BitsharesFaucetApiGenerator.registerBitsharesAccount(grapheneAccount.getName(), + final GrapheneAccount grapheneAccount = (GrapheneAccount) account; + ApiRequest creationRequest = new ApiRequest(1, new ApiRequestListener() { + @Override + public void success(Object answer, int idPetition) { + getAccountInfoByName(grapheneAccount.getName(), new ManagerRequest() { + @Override + public void success(Object answer) { + GrapheneAccount fetch = (GrapheneAccount) answer; + fetch.setSeedId(grapheneAccount.getSeedId()); + fetch.setCryptoNet(grapheneAccount.getCryptoNet()); + fetch.setAccountIndex(grapheneAccount.getAccountIndex()); + + CrystalDatabase db = CrystalDatabase.getAppDatabase(context); + long idAccount = db.cryptoNetAccountDao().insertCryptoNetAccount(fetch)[0]; + fetch.setId(idAccount); + db.grapheneAccountInfoDao().insertGrapheneAccountInfo(new GrapheneAccountInfo(fetch)); + subscribeBitsharesAccount(fetch.getId(),fetch.getAccountId(),context); + request.success(fetch); + } + + @Override + public void fail() { + //TODO get account data fail + } + }); + + } + + @Override + public void fail(int idPetition) { + request.fail(); + } + }); + BitsharesFaucetApiGenerator.registerBitsharesAccount(grapheneAccount.getName(), new Address(ECKey.fromPublicOnly(grapheneAccount.getOwnerKey(context).getPubKey())).toString(), new Address(ECKey.fromPublicOnly(grapheneAccount.getActiveKey(context).getPubKey())).toString(), - new Address(ECKey.fromPublicOnly(grapheneAccount.getMemoKey(context).getPubKey())).toString(),GrapheneApiGenerator.faucetUrl); - - if(created) { - GrapheneAccount fetch = this.getAccountInfoByName(grapheneAccount.getName()); - fetch.setSeedId(grapheneAccount.getSeedId()); - fetch.setCryptoNet(grapheneAccount.getCryptoNet()); - fetch.setAccountIndex(grapheneAccount.getAccountIndex()); - - CrystalDatabase db = CrystalDatabase.getAppDatabase(context); - long idAccount = db.cryptoNetAccountDao().insertCryptoNetAccount(fetch)[0]; - fetch.setId(idAccount); - db.grapheneAccountInfoDao().insertGrapheneAccountInfo(new GrapheneAccountInfo(fetch)); - - GrapheneApiGenerator.subscribeBitsharesAccount(fetch.getId(), fetch.getAccountId(), context); - BitsharesAccountManager.refreshAccountTransactions(fetch.getId(), context); - GrapheneApiGenerator.getAccountBalance(fetch.getId(), fetch.getAccountId(), context); - return fetch; - } + new Address(ECKey.fromPublicOnly(grapheneAccount.getMemoKey(context).getPubKey())).toString(), + GrapheneApiGenerator.faucetUrl, creationRequest); } - return null; } @Override - public CryptoNetAccount importAccountFromSeed(CryptoNetAccount account, Context context) { + public void importAccountFromSeed(CryptoNetAccount account, final Context context) { if(account instanceof GrapheneAccount) { - GrapheneAccount grapheneAccount = (GrapheneAccount) account; + final GrapheneAccount grapheneAccount = (GrapheneAccount) account; if(grapheneAccount.getAccountId() == null){ - GrapheneAccount fetch = this.getAccountInfoByName(grapheneAccount.getName()); - if(fetch == null) { - //TODO grapaheneAccount null, error fetching - return null; - } - grapheneAccount.setAccountId(fetch.getAccountId()); + this.getAccountInfoByName(grapheneAccount.getName(), new ManagerRequest() { + @Override + public void success(Object answer) { + GrapheneAccount fetch = (GrapheneAccount) answer; + grapheneAccount.setAccountId(fetch.getAccountId()); + CrystalDatabase db = CrystalDatabase.getAppDatabase(context); + db.cryptoNetAccountDao().insertCryptoNetAccount(grapheneAccount); + db.grapheneAccountInfoDao().insertGrapheneAccountInfo(new GrapheneAccountInfo(grapheneAccount)); + subscribeBitsharesAccount(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); + } + + @Override + public void fail() { + //TODO get account data fail + } + }); + }else if(grapheneAccount.getName() == null){ - GrapheneAccount fetch = this.getAccountInfoById(grapheneAccount.getAccountId()); - if(fetch == null) { - //TODO grapaheneAccount null, error fetching - return null; - } - grapheneAccount.setName(fetch.getName()); + this.getAccountInfoById(grapheneAccount.getAccountId(), new ManagerRequest() { + @Override + public void success(Object answer) { + GrapheneAccount fetch = (GrapheneAccount) answer; + grapheneAccount.setName(fetch.getName()); + CrystalDatabase db = CrystalDatabase.getAppDatabase(context); + db.cryptoNetAccountDao().insertCryptoNetAccount(grapheneAccount); + db.grapheneAccountInfoDao().insertGrapheneAccountInfo(new GrapheneAccountInfo(grapheneAccount)); + subscribeBitsharesAccount(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); + } + + @Override + public void fail() { + //TODO get account data fail + } + }); + }else { + CrystalDatabase db = CrystalDatabase.getAppDatabase(context); + db.cryptoNetAccountDao().insertCryptoNetAccount(grapheneAccount); + db.grapheneAccountInfoDao().insertGrapheneAccountInfo(new GrapheneAccountInfo(grapheneAccount)); + subscribeBitsharesAccount(grapheneAccount.getId(), grapheneAccount.getAccountId(), context); } - - CrystalDatabase db = CrystalDatabase.getAppDatabase(context); - db.cryptoNetAccountDao().insertCryptoNetAccount(grapheneAccount); - db.grapheneAccountInfoDao().insertGrapheneAccountInfo(new GrapheneAccountInfo(grapheneAccount)); - - GrapheneApiGenerator.subscribeBitsharesAccount(grapheneAccount.getId(), grapheneAccount.getAccountId(), context); - BitsharesAccountManager.refreshAccountTransactions(account.getId(), context); - GrapheneApiGenerator.getAccountBalance(grapheneAccount.getId(), grapheneAccount.getAccountId(), context); - return grapheneAccount; } - return null; } @Override - public void loadAccountFromDB(CryptoNetAccount account, Context context) { + public void loadAccountFromDB(CryptoNetAccount account, final Context context) { if(account instanceof GrapheneAccount){ - GrapheneAccount grapheneAccount = (GrapheneAccount) account; - CrystalDatabase db = CrystalDatabase.getAppDatabase(context); - GrapheneAccountInfo info = db.grapheneAccountInfoDao().getByAccountId(account.getId()); + final GrapheneAccount grapheneAccount = (GrapheneAccount) account; + final CrystalDatabase db = CrystalDatabase.getAppDatabase(context); + final GrapheneAccountInfo info = db.grapheneAccountInfoDao().getByAccountId(account.getId()); grapheneAccount.loadInfo(info); if(grapheneAccount.getAccountId() == null){ - GrapheneAccount fetch = this.getAccountInfoByName(grapheneAccount.getName()); - if(fetch != null){ - info.setAccountId(fetch.getAccountId()); - grapheneAccount.setAccountId(fetch.getAccountId()); - db.grapheneAccountInfoDao().insertGrapheneAccountInfo(info); - } + this.getAccountInfoByName(grapheneAccount.getName(), new ManagerRequest() { + @Override + public void success(Object answer) { + GrapheneAccount fetch = (GrapheneAccount) answer; + info.setAccountId(fetch.getAccountId()); + grapheneAccount.setAccountId(fetch.getAccountId()); + db.grapheneAccountInfoDao().insertGrapheneAccountInfo(info); + subscribeBitsharesAccount(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); + } + + @Override + public void fail() { + //TODO account data retrieve failed + } + }); }else if(grapheneAccount.getName() == null){ - GrapheneAccount fetch = this.getAccountInfoById(grapheneAccount.getAccountId()); - if(fetch != null) { - info.setName(fetch.getName()); - grapheneAccount.setName(fetch.getName()); - db.grapheneAccountInfoDao().insertGrapheneAccountInfo(info); - } - } + this.getAccountInfoById(grapheneAccount.getAccountId(), new ManagerRequest() { + @Override + public void success(Object answer) { + GrapheneAccount fetch = (GrapheneAccount) answer; + info.setName(fetch.getName()); + grapheneAccount.setName(fetch.getName()); + db.grapheneAccountInfoDao().insertGrapheneAccountInfo(info); + subscribeBitsharesAccount(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); + } - if(grapheneAccount.getName() == null || grapheneAccount.getAccountId() == null) { - //TODO grapaheneAccount null, error fetching - return; + @Override + public void fail() { + //TODO account data retrieve failed + } + }); + }else{ + subscribeBitsharesAccount(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); } - - GrapheneApiGenerator.subscribeBitsharesAccount(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); - BitsharesAccountManager.refreshAccountTransactions(account.getId(),context); - GrapheneApiGenerator.getAccountBalance(grapheneAccount.getId(),grapheneAccount.getAccountId(),context); } } + private void subscribeBitsharesAccount(long accountId, String accountBitsharesID, Context context){ + GrapheneApiGenerator.subscribeBitsharesAccount(accountId,accountBitsharesID,context); + BitsharesAccountManager.refreshAccountTransactions(accountId,context); + GrapheneApiGenerator.getAccountBalance(accountId,accountBitsharesID,context); + } + /** * Process the bitshares manager request * @param request The request Object @@ -189,7 +237,6 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI if(answer != null && answer instanceof AccountProperties) { AccountProperties prop = (AccountProperties) answer; //TODO change the way to compare keys - BrainKey bk = new BrainKey(importRequest.getMnemonic(), 0); System.out.println(bk.getPublicAddress("BTS").toString()); for(PublicKey activeKey : prop.owner.getKeyAuthList()){ @@ -220,7 +267,7 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI GrapheneApiGenerator.getAccountIdByName(importRequest.getAccountName(),checkAccountName); } - private void validateCreateAccount(ValidateCreateBitsharesAccountRequest createRequest){ + private void validateCreateAccount(final ValidateCreateBitsharesAccountRequest createRequest){ // Generate seed or find key Context context = createRequest.getContext(); AccountSeed seed = AccountSeed.getAccountSeed(SeedType.BIP39, context); @@ -233,12 +280,19 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI account.setSeedId(idSeed); account.setAccountIndex(0); account.setCryptoNet(CryptoNet.BITSHARES); - GrapheneAccount answer =(GrapheneAccount) this.createAccountFromSeed(account,context); - if (answer != null){ - createRequest.setAccountExists(false); - createRequest.setAccount(answer);; - } - createRequest.setAccountExists(false); + this.createAccountFromSeed(account,new ManagerRequest(){ + + @Override + public void success(Object answer) { + createRequest.setAccountExists(false); + createRequest.setAccount((GrapheneAccount)answer); + } + + @Override + public void fail() { + createRequest.setAccountExists(true); + } + },context ); } @@ -272,95 +326,79 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI */ private void validateSendRequest(final ValidateBitsharesSendRequest sendRequest){ //TODO feeAsset - String idAsset = getAssetInfoByName(sendRequest.getAsset()); - Asset feeAsset = new Asset(idAsset); - UserAccount fromUserAccount =new UserAccount(sendRequest.getSourceAccount().getAccountId()); + final String idAsset = getAssetInfoByName(sendRequest.getAsset()); + final Asset feeAsset = new Asset(idAsset); + final UserAccount fromUserAccount =new UserAccount(sendRequest.getSourceAccount().getAccountId()); - GrapheneAccount toUserGrapheneAccount = this.getAccountInfoByName(sendRequest.getToAccount()); - //TODO bad user to user account - UserAccount toUserAccount = new UserAccount(toUserGrapheneAccount.getAccountId()); - TransferOperationBuilder builder = new TransferOperationBuilder() - .setSource(fromUserAccount) - .setDestination(toUserAccount) - .setTransferAmount(new AssetAmount(UnsignedLong.valueOf(sendRequest.getAmount()), new Asset(idAsset))) - .setFee(new AssetAmount(UnsignedLong.valueOf(0), feeAsset)); - if(sendRequest.getMemo() != null) { - //builder.setMemo(new Memo(fromUserAccount,toUserAccount,0,sendRequest.getMemo().getBytes())); - //TODO memo - } - ArrayList operationList = new ArrayList<>(); - operationList.add(builder.build()); - - ECKey privateKey = sendRequest.getSourceAccount().getActiveKey(sendRequest.getContext()); - - Transaction transaction = new Transaction(privateKey, null, operationList); - transaction.setChainId(BITSHARES_TESTNET_CHAIN_ID); - - ApiRequest transactionRequest = new ApiRequest(0, new ApiRequestListener() { + //TODO cached to accounts + this.getAccountInfoByName(sendRequest.getToAccount(), new ManagerRequest() { @Override - public void success(Object answer, int idPetition) { - sendRequest.setSend(true); + public void success(Object answer) { + GrapheneAccount toUserGrapheneAccount = (GrapheneAccount) answer; + UserAccount toUserAccount = new UserAccount(toUserGrapheneAccount.getAccountId()); + TransferOperationBuilder builder = new TransferOperationBuilder() + .setSource(fromUserAccount) + .setDestination(toUserAccount) + .setTransferAmount(new AssetAmount(UnsignedLong.valueOf(sendRequest.getAmount()), new Asset(idAsset))) + .setFee(new AssetAmount(UnsignedLong.valueOf(0), feeAsset)); + if(sendRequest.getMemo() != null) { + //builder.setMemo(new Memo(fromUserAccount,toUserAccount,0,sendRequest.getMemo().getBytes())); + //TODO memo + } + ArrayList operationList = new ArrayList<>(); + operationList.add(builder.build()); + + ECKey privateKey = sendRequest.getSourceAccount().getActiveKey(sendRequest.getContext()); + + Transaction transaction = new Transaction(privateKey, null, operationList); + transaction.setChainId(BITSHARES_TESTNET_CHAIN_ID); + + ApiRequest transactionRequest = new ApiRequest(0, new ApiRequestListener() { + @Override + public void success(Object answer, int idPetition) { + sendRequest.setSend(true); + } + + @Override + public void fail(int idPetition) { + sendRequest.setSend(false); + } + }); + + GrapheneApiGenerator.broadcastTransaction(transaction,feeAsset, transactionRequest); } @Override - public void fail(int idPetition) { - sendRequest.setSend(false); + public void fail() { + //TODO bad user to user account } }); - GrapheneApiGenerator.broadcastTransaction(transaction,feeAsset, transactionRequest); } /** * Returns the account info from a graphene id * @param grapheneId The graphene id of the account */ - private GrapheneAccount getAccountInfoById(String grapheneId){ - final Object SYNC = new Object(); - long timeout = 60000; + private void getAccountInfoById(String grapheneId, ManagerRequest request){ - AccountIdOrNameListener listener = new AccountIdOrNameListener(SYNC); + AccountIdOrNameListener listener = new AccountIdOrNameListener(request); - ApiRequest request = new ApiRequest(0, listener); - GrapheneApiGenerator.getAccountById(grapheneId,request); - - long cTime = System.currentTimeMillis(); - - while(!listener.ready && (System.currentTimeMillis()-cTime) < timeout){ - synchronized (SYNC){ - try { - SYNC.wait(100); - } catch (InterruptedException ignore) {} - } - } - - return listener.account; + ApiRequest accountRequest = new ApiRequest(0, listener); + GrapheneApiGenerator.getAccountById(grapheneId,accountRequest); } /** * Gets account info by its name * @param grapheneName The name of the account to retrieve */ - private GrapheneAccount getAccountInfoByName(String grapheneName){ - final Object SYNC = new Object(); - long timeout = 60000; + private void getAccountInfoByName(String grapheneName, ManagerRequest request){ - AccountIdOrNameListener listener = new AccountIdOrNameListener(SYNC); + AccountIdOrNameListener listener = new AccountIdOrNameListener(request); - ApiRequest request = new ApiRequest(0, listener); - GrapheneApiGenerator.getAccountByName(grapheneName,request); + ApiRequest accountRequest = new ApiRequest(0, listener); + GrapheneApiGenerator.getAccountByName(grapheneName,accountRequest); - long cTime = System.currentTimeMillis(); - - while(!listener.ready && (System.currentTimeMillis()-cTime) < timeout){ - synchronized (SYNC){ - try { - SYNC.wait(100); - } catch (InterruptedException ignore) {} - } - } - - return listener.account; } //TODO expand function to be more generic @@ -554,13 +592,12 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI * Class to retrieve the account id or the account name, if one of those is missing */ private class AccountIdOrNameListener implements ApiRequestListener{ - final Object SYNC; - boolean ready = false; + final ManagerRequest request; GrapheneAccount account; - AccountIdOrNameListener(Object SYNC) { - this.SYNC = SYNC; + AccountIdOrNameListener(ManagerRequest request) { + this.request = request; } @Override @@ -572,18 +609,12 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI account.setName(props.name); } - synchronized (SYNC){ - ready = true; - SYNC.notifyAll(); - } + request.success(account); } @Override public void fail(int idPetition) { - synchronized (SYNC){ - ready = true; - SYNC.notifyAll(); - } + request.fail(); } } @@ -649,7 +680,9 @@ public class BitsharesAccountManager implements CryptoAccountManager, CryptoNetI dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); try { transaction.setDate(dateFormat.parse(((BlockHeader) answer).timestamp)); - transactionDao.insertTransaction(transaction); + if (transactionDao.getByTransaction(transaction.getDate(),transaction.getFrom(),transaction.getTo(),transaction.getAmount()) == null) { + transactionDao.insertTransaction(transaction); + } } catch (ParseException e) { e.printStackTrace(); } diff --git a/app/src/main/java/cy/agorise/crystalwallet/manager/CryptoAccountManager.java b/app/src/main/java/cy/agorise/crystalwallet/manager/CryptoAccountManager.java index e1e3b6d..9941e8e 100644 --- a/app/src/main/java/cy/agorise/crystalwallet/manager/CryptoAccountManager.java +++ b/app/src/main/java/cy/agorise/crystalwallet/manager/CryptoAccountManager.java @@ -18,14 +18,14 @@ public interface CryptoAccountManager { * @param account The values to be created, * @returnThe CruptoNetAccount created, or null if it couldn't be created */ - public CryptoNetAccount createAccountFromSeed(CryptoNetAccount account, Context context); + public void createAccountFromSeed(CryptoNetAccount account, ManagerRequest request, Context context); /** * Imports a CryptoCoin account from a seed * @param account A CryptoNetAccount with the parameters to be imported * @returnThe CruptoNetAccount imported */ - public CryptoNetAccount importAccountFromSeed(CryptoNetAccount account, Context context); + public void importAccountFromSeed(CryptoNetAccount account, Context context); /** * Loads account data from the database diff --git a/app/src/main/java/cy/agorise/crystalwallet/manager/ManagerRequest.java b/app/src/main/java/cy/agorise/crystalwallet/manager/ManagerRequest.java new file mode 100644 index 0000000..cfd6464 --- /dev/null +++ b/app/src/main/java/cy/agorise/crystalwallet/manager/ManagerRequest.java @@ -0,0 +1,12 @@ +package cy.agorise.crystalwallet.manager; + +/** + * Created by henry on 28/1/2018. + */ + +public interface ManagerRequest { + + public void success(Object answer); + + public void fail(); +}