Updated on 2026-08-14

This commit is contained in:
Tangem 2019-07-08 15:13:52 +03:00
commit 9f38de003a
279 changed files with 20155 additions and 10 deletions

View file

@ -22,7 +22,9 @@ public enum Blockchain {
Binance("BINANCE", "BNB", 100000000.0, R.drawable.tangem2, "Binance"),
BinanceTestNet("BINANCE/test", "BNB", 100000000.0, R.drawable.tangem2, "Binance Testnet"),
Matic("MATIC", "MTX", 1.0, R.drawable.tangem2, "Matic"),
MaticTestNet("MATIC/test", "MTX", 1.0, R.drawable.tangem2, "Matic Testnet");
MaticTestNet("MATIC/test", "MTX", 1.0, R.drawable.tangem2, "Matic Testnet"),
Stellar("XLM", "XLM", 1000000.0, R.drawable.ic_logo_stellar, "Stellar"),
StellarTestNet("XLM/test", "XLM", 1000000.0, R.drawable.ic_logo_stellar, "Stellar Testnet");
Blockchain(String ID, String currency, double multiplier, int imageResource, String officialName) {
mID = ID;
@ -105,6 +107,9 @@ public enum Blockchain {
case "ETH":
return R.drawable.ic_logo_ethereum;
case "XLM":
return R.drawable.ic_logo_stellar;
}
return R.drawable.tangem2;
}

View file

@ -0,0 +1,169 @@
package com.tangem.data.network;
import com.tangem.App;
import com.tangem.data.Blockchain;
import com.tangem.util.LOG;
import com.tangem.wallet.R;
import com.tangem.wallet.TangemContext;
import org.stellar.sdk.Network;
import org.stellar.sdk.Server;
import org.stellar.sdk.requests.ErrorResponse;
import java.io.IOException;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
/**
* Created by dvol on 7.01.2019.
* <p>
* Request processor for Stellar Horizon Rest Api
* Every request live cycle:
* 1. In application create request and call {@link ServerApiStellar}.requestData(..)
* 2. Try send every request for max 4 times,
* 3. If all 4 times fail call DefaultObserver<StellarRequest>.onError (defined in .requestData(..)) and than
* {@link Listener}.onFail(...) callback
* Error can be acquired with {@link StellarRequest}.getError() method
* 4. If request network communication finished successfully then call DefaultObserver<StellarRequest.Base>.onComplete (defined in .requestData) and than
* {@link Listener}.onSuccess(...) callback
*/
public class ServerApiStellar {
private static String TAG = ServerApiStellar.class.getSimpleName();
/**
* TCP, SSL
* Used in BTC, BCH
*/
private Listener listener;
private int requestsCount = 0;
public boolean isRequestsSequenceCompleted() {
LOG.i(TAG, String.format("isRequestsSequenceCompleted: %s (%d requests left)", String.valueOf(requestsCount <= 0), requestsCount));
return requestsCount <= 0;
}
/**
* Interface for notification every request result
*/
public interface Listener {
/**
* Notify that request processing was successful
*
* @param stellarRequest - processed request containing received answer {@see stellarRequest.getAnswer() method}
*/
void onSuccess(StellarRequest.Base stellarRequest);
/**
* Notify that request processing was successful
*
* @param stellarRequest - processed request containing occurred error {@see stellarRequest.getError() method}
*/
void onFail(StellarRequest.Base stellarRequest);
}
/**
* Set notificaion listener
*
* @param listener
*/
public void setListener(Listener listener) {
this.listener = listener;
}
/**
* Start process request
*
* @param ctx
* @param stellarRequest
*/
public void requestData(TangemContext ctx, StellarRequest.Base stellarRequest) {
requestsCount++;
LOG.i(TAG, String.format("New request[%d]: %s", requestsCount, stellarRequest.getClass().getSimpleName()));
Observable<StellarRequest.Base> stellarObserver = Observable.just(stellarRequest)
.doOnEach(stellarRequest1 -> doStellarRequest(ctx, stellarRequest))
.flatMap(stellarRequest1 -> {
if (stellarRequest1.errorResponse != null) {
LOG.e(TAG, "Error response on " + stellarRequest.getClass().getSimpleName());
return Observable.error(stellarRequest.errorResponse);
} else
return Observable.just(stellarRequest1);
}
)
.retryWhen(errors -> errors
.filter(throwable -> (throwable instanceof IOException) || (throwable instanceof ErrorResponse))
.zipWith(Observable.range(1, 4), (n, i) -> i))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
stellarObserver.subscribe(new DefaultObserver<StellarRequest.Base>() {
@Override
public void onNext(StellarRequest.Base stellarRequest) {
LOG.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onNext ");
}
@Override
public void onError(Throwable e) {
requestsCount--;
LOG.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onError " + e.getMessage());
LOG.e(TAG, String.format("%d requests left in processing", requestsCount));
stellarRequest.setError(ctx.getString(R.string.cannot_obtain_data_from_blockchain));
//setErrorOccurred(e.getMessage());//;
listener.onFail(stellarRequest);
}
/**
* Called after completion request processing
*/
@Override
public void onComplete() {
requestsCount--;
LOG.e(TAG, String.format("%d requests left in processing", requestsCount));
if (stellarRequest.getError() != null) {
LOG.i(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error!=null");
listener.onFail(stellarRequest);
} else {
LOG.e(TAG, "requestData " + stellarRequest.getClass().getSimpleName() + " onComplete, error==null");
listener.onSuccess(stellarRequest);
}
}
});
}
private void doStellarRequest(TangemContext ctx, StellarRequest.Base stellarRequest) throws IOException {
stellarRequest.setError(null);
try {
Server server;
if (ctx.getBlockchain() == Blockchain.Stellar) {
Network.usePublicNetwork();
server = new Server(ServerURL.API_STELLAR);
} else if (ctx.getBlockchain() == Blockchain.StellarTestNet) {
Network.useTestNetwork();
server = new Server(ServerURL.API_STELLAR_TESTNET);
} else {
throw new IOException("Wrong blockchain for ServerApiStellar");
}
try {
LOG.e(TAG, "--- request " + stellarRequest.getClass().getSimpleName());
stellarRequest.process(server);
} catch (ErrorResponse errorResponse) {
LOG.e(TAG, "--- error response: " + errorResponse.getMessage());
stellarRequest.errorResponse = errorResponse;
stellarRequest.setError(errorResponse.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
stellarRequest.setError(App.Companion.getInstance().getString(R.string.cannot_obtain_data_from_blockchain_communication_error));
throw e;
}
}
}

View file

@ -12,4 +12,6 @@ class ServerURL {
static final String API_BINANCE = "https://dex.binance.org/";
static final String API_BINANCE_TESTNET = "https://testnet-dex.binance.org/";
static final String API_MATIC_TESTNET = "https://testnet2.matic.network";
static final String API_STELLAR = "https://horizon.stellar.org/";
static final String API_STELLAR_TESTNET = "https://horizon-testnet.stellar.org";
}

View file

@ -0,0 +1,84 @@
package com.tangem.data.network;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.Server;
import org.stellar.sdk.Transaction;
import org.stellar.sdk.requests.ErrorResponse;
import org.stellar.sdk.responses.AccountResponse;
import org.stellar.sdk.responses.LedgerResponse;
import org.stellar.sdk.responses.SubmitTransactionResponse;
import java.io.IOException;
/**
* Created by dvol on 7.01.2019.
*/
public class StellarRequest {
public static abstract class Base {
public ErrorResponse errorResponse;
private String error = null;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public abstract void process(Server server) throws IOException;
}
public static class Balance extends Base {
KeyPair accountKeyPair;
public AccountResponse accountResponse;
public Balance(String walletAddress) {
accountKeyPair = KeyPair.fromAccountId(walletAddress);
}
@Override
public void process(Server server) throws IOException {
accountResponse = server.accounts().account(accountKeyPair);
}
}
public static class SubmitTransaction extends Base {
public Transaction transaction;
public SubmitTransactionResponse response;
public SubmitTransaction(Transaction transaction) {
this.transaction = transaction;
}
@Override
public void process(Server server) throws IOException {
// // First, check to make sure that the destination account exists.
// // You could skip this, but if the account does not exist, you will be charged
// // the transaction fee when the transaction fails.
// // It will throw HttpResponseException if account does not exist or there was another error.
// server.accounts().account(targetAccount);
//
// // If there was no error, load up-to-date information on your account.
// AccountResponse sourceAccount = server.accounts().account(sourceAccount);
// And finally, send it off to Stellar!
response = server.submitTransaction(transaction);
}
}
public static class Ledgers extends Base {
public LedgerResponse ledgerResponse;
public Ledgers() {};
@Override
public void process(Server server) throws IOException {
int latestLedger = server.root().getCoreLatestLedger();
ledgerResponse = server.ledgers().ledger(latestLedger);
}
}
}

View file

@ -646,8 +646,10 @@ class LoadedWalletFragment : androidx.fragment.app.Fragment(), NfcAdapter.Reader
updateViews()
// Bitcoin, Litecoin, BitcoinCash
if (ctx.blockchain == Blockchain.Bitcoin || ctx.blockchain == Blockchain.BitcoinTestNet || ctx.blockchain == Blockchain.Litecoin || ctx.blockchain == Blockchain.BitcoinCash) {
// Bitcoin, Litecoin, BitcoinCash, Stellar
if (ctx.blockchain == Blockchain.Bitcoin || ctx.blockchain == Blockchain.BitcoinTestNet ||
ctx.blockchain == Blockchain.Litecoin || ctx.blockchain == Blockchain.BitcoinCash ||
ctx.blockchain == Blockchain.Stellar || ctx.blockchain == Blockchain.StellarTestNet ) {
ctx.coinData.setIsBalanceEqual(true)
}

View file

@ -15,6 +15,7 @@ import com.tangem.wallet.matic.MaticTokenEngine
import com.tangem.wallet.nftToken.NftTokenEngine
import com.tangem.wallet.rsk.RskEngine
import com.tangem.wallet.rsk.RskTokenEngine
import com.tangem.wallet.xlm.XlmEngine
import com.tangem.wallet.xrp.XrpEngine
/**
@ -43,6 +44,7 @@ object CoinEngineFactory {
Blockchain.Ripple -> XrpEngine()
Blockchain.Binance, Blockchain.BinanceTestNet -> BinanceEngine()
Blockchain.Matic, Blockchain.MaticTestNet -> MaticTokenEngine()
Blockchain.StellarTestNet, Blockchain.Stellar -> XlmEngine()
else -> null
}
}
@ -73,9 +75,9 @@ object CoinEngineFactory {
else if (Blockchain.Binance == context.blockchain || Blockchain.BinanceTestNet == context.blockchain)
BinanceEngine(context)
else if (Blockchain.Matic == context.blockchain || Blockchain.MaticTestNet == context.blockchain)
MaticTokenEngine(context
)
MaticTokenEngine(context)
else if (Blockchain.Stellar == context.blockchain || Blockchain.StellarTestNet == context.blockchain)
XlmEngine(context)
else
return null
} catch (e: Exception) {

View file

@ -97,7 +97,7 @@ public class TokenEngine extends CoinEngine {
public String getBalanceHTML() {
if (hasBalanceInfo()) {
try {
return " " + convertToAmount(coinData.getBalanceInInternalUnits()).toDescriptionString(getTokenDecimals()) + " <br><small><small> + " + convertToAmount(coinData.getBalanceAlterInInternalUnits()).toDescriptionString(getChainDecimals()) + " for fee</small></small>";
return " " + convertToAmount(coinData.getBalanceInInternalUnits()).toDescriptionString(getTokenDecimals()) + "<br><small><small>+ " + convertToAmount(coinData.getBalanceAlterInInternalUnits()).toDescriptionString(getChainDecimals()) + " for fee</small></small>";
} catch (Exception e) {
e.printStackTrace();
return "";

View file

@ -0,0 +1,137 @@
package com.tangem.wallet.xlm;
import android.os.Bundle;
import android.util.Log;
import com.tangem.wallet.CoinData;
import com.tangem.wallet.CoinEngine;
import org.bitcoinj.core.Coin;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.responses.AccountResponse;
import org.stellar.sdk.responses.LedgerResponse;
import java.math.BigDecimal;
/*
* Created by dvol on 7.01.2019.
*/
public class XlmData extends CoinData {
public static class AccountResponseEx extends AccountResponse {
AccountResponseEx(String accountId, Long sequenceNumber) {
super(KeyPair.fromAccountId(accountId), sequenceNumber);
}
}
private CoinEngine.Amount balance = null;
private Long sequenceNumber = 0L;
private CoinEngine.Amount baseReserve = new CoinEngine.Amount("0.5", "XLM");
private CoinEngine.Amount baseFee = new CoinEngine.Amount("0.00001", "XLM");
@Override
public void clearInfo() {
super.clearInfo();
balance = null;
}
CoinEngine.Amount getBalance() {
if (balance != null) {
return new CoinEngine.Amount(balance.subtract(getReserve()), "XLM");
} else {
return null;
}
}
CoinEngine.Amount getReserve() {
return new CoinEngine.Amount(baseReserve.multiply(BigDecimal.valueOf(2)), "XLM");
}
CoinEngine.Amount getBaseFee() {
return baseFee;
}
AccountResponse getAccountResponse() {
return new AccountResponseEx(getWallet(), sequenceNumber);
}
void setAccountResponse(AccountResponse accountResponse) {
if (accountResponse.getBalances().length > 0) {
AccountResponse.Balance balanceResponse = accountResponse.getBalances()[0];
balance = new CoinEngine.Amount(balanceResponse.getBalance(), "XLM");
}
sequenceNumber = accountResponse.getSequenceNumber();
setBalanceReceived(true);
}
void setLedgerResponse(LedgerResponse ledgerResponse) {
XlmEngine xlmEngine = new XlmEngine();
baseReserve = xlmEngine.convertToAmount(new CoinEngine.InternalAmount(ledgerResponse.getBaseReserveInStroops(), "stroops"));
baseFee = xlmEngine.convertToAmount(new CoinEngine.InternalAmount(ledgerResponse.getBaseFeeInStroops(), "stroops"));
}
public void incSequenceNumber() {
sequenceNumber++;
}
@Override
public void loadFromBundle(Bundle B) {
super.loadFromBundle(B);
if (B.containsKey("BalanceCurrency") && B.containsKey("BalanceDecimal")) {
balance = new CoinEngine.Amount(B.getString("BalanceDecimal"), B.getString("BalanceCurrency"));
} else {
balance = null;
}
if (B.containsKey("sequenceNumber")) {
sequenceNumber = B.getLong("sequenceNumber");
} else {
sequenceNumber = 0L;
}
if (B.containsKey("BaseReserveCurrency") && B.containsKey("BaseReserveDecimal")) {
baseReserve = new CoinEngine.Amount(B.getString("BaseReserveDecimal"), B.getString("BaseReserveCurrency"));
} else {
baseReserve = new CoinEngine.Amount("0.5", "XLM");
}
if (B.containsKey("BaseFeeCurrency") && B.containsKey("BaseFeeDecimal")) {
baseFee = new CoinEngine.Amount(B.getString("BaseFeeDecimal"), B.getString("BaseFeeCurrency"));
} else {
baseFee = new CoinEngine.Amount("0.00001", "XLM");
}
}
@Override
public void saveToBundle(Bundle B) {
super.saveToBundle(B);
try {
if (balance != null) {
B.putString("BalanceCurrency", balance.getCurrency());
B.putString("BalanceDecimal", balance.toValueString());
}
if (sequenceNumber != null) {
B.putLong("sequenceNumber", sequenceNumber);
}
if (baseReserve != null) {
B.putString("BaseReserveCurrency", baseReserve.getCurrency());
B.putString("BaseReserveDecimal", baseReserve.toValueString());
}
if (baseFee != null) {
B.putString("BaseFeeCurrency", baseFee.getCurrency());
B.putString("BaseFeeDecimal", baseFee.toValueString());
}
} catch (Exception e) {
Log.e("Can't save to bundle ", e.getMessage());
}
}
}

View file

@ -0,0 +1,528 @@
package com.tangem.wallet.xlm;
import android.net.Uri;
import android.text.InputFilter;
import android.util.Log;
import com.tangem.card_common.data.TangemCard;
import com.tangem.card_common.tasks.SignTask;
import com.tangem.card_common.util.Util;
import com.tangem.data.Blockchain;
import com.tangem.data.network.ServerApiStellar;
import com.tangem.data.network.StellarRequest;
import com.tangem.util.DecimalDigitsInputFilter;
import com.tangem.wallet.BalanceValidator;
import com.tangem.wallet.CoinData;
import com.tangem.wallet.CoinEngine;
import com.tangem.wallet.R;
import com.tangem.wallet.TangemContext;
import org.stellar.sdk.AssetTypeNative;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.PaymentOperation;
import org.stellar.sdk.Transaction;
import org.stellar.sdk.TransactionEx;
import java.io.IOException;
import java.math.BigDecimal;
/**
* Created by dvol on 7.01.2019.
* <p>
* PS. To create and fill testnet account just open https://friendbot.stellar.org/?addr=XXX in browser
**/
public class XlmEngine extends CoinEngine {
private static final String TAG = XlmEngine.class.getSimpleName();
public XlmData coinData = null;
public XlmEngine(TangemContext context) throws Exception {
super(context);
if (context.getCoinData() == null) {
coinData = new XlmData();
context.setCoinData(coinData);
} else if (context.getCoinData() instanceof XlmData) {
coinData = (XlmData) context.getCoinData();
} else {
throw new Exception("Invalid type of Blockchain data for XlmEngine");
}
}
public XlmEngine() {
super();
}
private static int getDecimals() {
return 7;
}
private void checkBlockchainDataExists() throws Exception {
if (coinData == null) throw new Exception("No blockchain data");
}
@Override
public boolean awaitingConfirmation() {
if (coinData == null) return false;
//TODO
return false;//coinData.getBalanceUnconfirmed() != 0;
}
@Override
public String getBalanceHTML() {
Amount balance = getBalance();
if (balance != null) {
return " " + balance.toDescriptionString(getDecimals()) + "<br><small><small>+ " + coinData.getReserve().toDescriptionString(getDecimals()) + " reserve</small></small>";
} else {
return "";
}
}
@Override
public String getBalanceCurrency() {
return "XLM";
}
@Override
public String getOfflineBalanceHTML() {
InternalAmount offlineInternalAmount = convertToInternalAmount(ctx.getCard().getOfflineBalance());
Amount offlineAmount = convertToAmount(offlineInternalAmount);
return offlineAmount.toDescriptionString(getDecimals());
}
@Override
public boolean isBalanceNotZero() {
if (coinData == null) return false;
if (coinData.getBalance() == null) return false;
return coinData.getBalance().notZero();
}
@Override
public boolean hasBalanceInfo() {
if (coinData == null) return false;
return coinData.getBalance() != null;
}
@Override
public boolean isExtractPossible() {
if (!hasBalanceInfo()) {
ctx.setMessage(R.string.cannot_obtain_data_from_blockchain);
} else if (!isBalanceNotZero()) {
ctx.setMessage(R.string.wallet_empty);
} else if (awaitingConfirmation()) {
ctx.setMessage(R.string.please_wait_while_previous);
} else {
return true;
}
return false;
}
@Override
public String getFeeCurrency() {
return "XLM";
}
@Override
public boolean validateAddress(String address) {
try {
KeyPair kp = KeyPair.fromAccountId(address);
// TODO is it possible to check address testNet or not
// if (ctx.getBlockchain() == Blockchain.StellarTestNet) {
// return false;
// }
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean isNeedCheckNode() {
return false;
}
@Override
public Uri getWalletExplorerUri() {
return Uri.parse((ctx.getBlockchain() == Blockchain.Stellar ? "http://stellarchain.io/address/" : "http://testnet.stellarchain.io/address/") + ctx.getCoinData().getWallet());
}
@Override
public Uri getShareWalletUri() {
//TODO - how to construct payment query intent for stellar?
if (ctx.getCard().getDenomination() != null) {
return Uri.parse(ctx.getCoinData().getWallet() + "?amount=" + convertToAmount(convertToInternalAmount(ctx.getCard().getDenomination())).toValueString());
} else {
return Uri.parse(ctx.getCoinData().getWallet());
}
}
@Override
public InputFilter[] getAmountInputFilters() {
return new InputFilter[]{new DecimalDigitsInputFilter(getDecimals())};
}
@Override
public boolean checkNewTransactionAmount(Amount amount) {
if (coinData == null) return false;
if (amount.compareTo(coinData.getBalance()) > 0) {
return false;
}
return true;
}
@Override
public boolean checkNewTransactionAmountAndFee(Amount amountValue, Amount feeValue, Boolean isIncludeFee) {
try {
checkBlockchainDataExists();
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (feeValue == null || amountValue == null)
return false;
if (feeValue.isZero() || amountValue.isZero())
return false;
if (isIncludeFee && (amountValue.compareTo(coinData.getBalance()) > 0 || amountValue.compareTo(feeValue) < 0))
return false;
if (!isIncludeFee && amountValue.add(feeValue).compareTo(coinData.getBalance()) > 0)
return false;
return true;
}
@Override
public boolean validateBalance(BalanceValidator balanceValidator) {
try {
if (((ctx.getCard().getOfflineBalance() == null) && !ctx.getCoinData().isBalanceReceived()) || (!ctx.getCoinData().isBalanceReceived() && (ctx.getCard().getRemainingSignatures() != ctx.getCard().getMaxSignatures()))) {
balanceValidator.setScore(0);
balanceValidator.setFirstLine("Unknown balance");
balanceValidator.setSecondLine("Balance cannot be verified. Swipe down to refresh.");
return false;
}
// Workaround before new back-end
// if (card.getRemainingSignatures() == card.getMaxSignatures()) {
// firstLine = "Verified balance";
// secondLine = "Balance confirmed in blockchain. ";
// secondLine += "Verified note identity. ";
// return;
// }
// if (coinData.getBalanceUnconfirmed() != 0) {
// balanceValidator.setScore(0);
// balanceValidator.setFirstLine("Transaction in progress");
// balanceValidator.setSecondLine("Wait for confirmation in blockchain");
// return false;
// }
if (coinData.isBalanceReceived() && coinData.isBalanceEqual()) {
balanceValidator.setScore(100);
balanceValidator.setFirstLine("Verified balance");
balanceValidator.setSecondLine("Balance confirmed in blockchain");
if (coinData.getBalance().isZero()) {
balanceValidator.setFirstLine("Empty wallet");
balanceValidator.setSecondLine("");
}
}
// rule 4 TODO: need to check SignedHashed against number of outputs in blockchain
// if((card.getRemainingSignatures() != card.getMaxSignatures()) && card.getBalance() != 0)
// {
// score = 80;
// firstLine = "Unguaranteed balance";
// secondLine = "Potential unsent transaction. Redeem immediately if accept. ";
// return;
// }
if ((ctx.getCard().getOfflineBalance() != null) && !coinData.isBalanceReceived() && (ctx.getCard().getRemainingSignatures() == ctx.getCard().getMaxSignatures()) && coinData.getBalance().notZero()) {
balanceValidator.setScore(80);
balanceValidator.setFirstLine("Verified offline balance");
balanceValidator.setSecondLine("Can't obtain balance from blockchain. Restore internet connection to be more confident. ");
}
// if(card.getFailedBalanceRequestCounter()!=0) {
// score -= 5 * card.getFailedBalanceRequestCounter();
// secondLine += "Not all nodes have returned balance. Swipe down or tap again. ";
// if(score <= 0)
// return;
// }
//
// if(card.isBalanceReceived() && !card.isBalanceEqual()) {
// score = 0;
// firstLine = "Disputed balance";
// secondLine += " Cannot obtain trusted balance at the moment. Try to tap and check this banknote later.";
// return;
// }
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public Amount getBalance() {
if (!hasBalanceInfo()) return null;
return coinData.getBalance();
}
@Override
public String evaluateFeeEquivalent(String fee) {
if (!coinData.getAmountEquivalentDescriptionAvailable()) return "";
try {
Amount feeAmount = new Amount(fee, getFeeCurrency());
return feeAmount.toEquivalentString(coinData.getRate());
} catch (Exception e) {
return "";
}
}
@Override
public String getBalanceEquivalent() {
if (coinData == null || !coinData.getAmountEquivalentDescriptionAvailable()) return "";
Amount balance = getBalance();
if (balance == null) return "";
return balance.toEquivalentString(coinData.getRate());
}
@Override
public String calculateAddress(byte[] pkUncompressed) {
KeyPair kp = KeyPair.fromPublicKey(pkUncompressed);
return kp.getAccountId();
}
private static BigDecimal multiplier = new BigDecimal("10000000");
@Override
public Amount convertToAmount(InternalAmount internalAmount) {
BigDecimal d = internalAmount.divide(multiplier);
return new Amount(d, getBalanceCurrency());
}
@Override
public Amount convertToAmount(String strAmount, String currency) {
return new Amount(strAmount, currency);
}
@Override
public InternalAmount convertToInternalAmount(Amount amount) {
BigDecimal d = amount.multiply(multiplier);
return new InternalAmount(d, "stroops");
}
@Override
public InternalAmount convertToInternalAmount(byte[] bytes) {
if (bytes == null) return null;
byte[] reversed = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) reversed[i] = bytes[bytes.length - i - 1];
return new InternalAmount(Util.byteArrayToLong(reversed), "stroops");
}
@Override
public byte[] convertToByteArray(InternalAmount internalAmount) {
byte[] bytes = Util.longToByteArray(internalAmount.longValueExact());
byte[] reversed = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) reversed[i] = bytes[bytes.length - i - 1];
return reversed;
}
@Override
public CoinData createCoinData() {
return new XlmData();
}
@Override
public String getUnspentInputsDescription() {
return "";
}
@Override
public SignTask.TransactionToSign constructTransaction(Amount amountValue, Amount feeValue, boolean IncFee, String targetAddress) throws Exception {
checkBlockchainDataExists();
if (IncFee) {
amountValue = new Amount(amountValue.subtract(feeValue), amountValue.getCurrency());
}
TransactionEx transaction = TransactionEx.buildEx(60, coinData.getAccountResponse(), new PaymentOperation.Builder(KeyPair.fromAccountId(targetAddress), new AssetTypeNative(), amountValue.toValueString()).build());
if (transaction.getFee() != convertToInternalAmount(feeValue).intValueExact()) {
throw new Exception("Invalid fee!");
}
return new SignTask.TransactionToSign() {
@Override
public boolean isSigningMethodSupported(TangemCard.SigningMethod signingMethod) {
return signingMethod == TangemCard.SigningMethod.Sign_Hash || signingMethod == TangemCard.SigningMethod.Sign_Raw;
}
@Override
public byte[][] getHashesToSign() throws Exception {
byte[][] dataForSign = new byte[1][];
dataForSign[0] = transaction.hash();
return dataForSign;
}
@Override
public byte[] getRawDataToSign() throws Exception {
return transaction.signatureBase();
}
@Override
public String getHashAlgToSign() {
return "sha-256";
}
@Override
public byte[] getIssuerTransactionSignature(byte[] dataToSignByIssuer) throws Exception {
throw new Exception("Issuer validation not supported!");
}
@Override
public byte[] onSignCompleted(byte[] signFromCard) throws Exception {
// Sign the transaction to prove you are actually the person sending it.
transaction.setSign(signFromCard);
byte[] txForSend = transaction.toEnvelopeXdrBase64().getBytes();
notifyOnNeedSendTransaction(txForSend);
return txForSend;
}
};
}
@Override
public void requestBalanceAndUnspentTransactions(BlockchainRequestsCallbacks blockchainRequestsCallbacks) {
final ServerApiStellar serverApi = new ServerApiStellar();
ServerApiStellar.Listener listener = new ServerApiStellar.Listener() {
@Override
public void onSuccess(StellarRequest.Base request) {
Log.i(TAG, "onSuccess: " + request.getClass().getSimpleName());
if (request instanceof StellarRequest.Balance) {
StellarRequest.Balance balanceRequest = (StellarRequest.Balance) request;
coinData.setAccountResponse(balanceRequest.accountResponse);
if (serverApi.isRequestsSequenceCompleted()) {
blockchainRequestsCallbacks.onComplete(!ctx.hasError());
} else {
blockchainRequestsCallbacks.onProgress();
}
} else if (request instanceof StellarRequest.Ledgers) {
StellarRequest.Ledgers ledgersRequest = (StellarRequest.Ledgers) request;
coinData.setLedgerResponse(ledgersRequest.ledgerResponse);
if (serverApi.isRequestsSequenceCompleted()) {
blockchainRequestsCallbacks.onComplete(!ctx.hasError());
} else {
blockchainRequestsCallbacks.onProgress();
}
} else {
ctx.setError("Invalid request logic");
blockchainRequestsCallbacks.onComplete(false);
}
}
@Override
public void onFail(StellarRequest.Base request) {
Log.i(TAG, "onFail: " + request.getClass().getSimpleName() + " " + request.getError());
ctx.setError(request.getError());
if (serverApi.isRequestsSequenceCompleted()) {
blockchainRequestsCallbacks.onComplete(false);
} else {
blockchainRequestsCallbacks.onProgress();
}
}
};
serverApi.setListener(listener);
serverApi.requestData(ctx, new StellarRequest.Balance(coinData.getWallet()));
serverApi.requestData(ctx, new StellarRequest.Ledgers());
}
@Override
public void requestFee(BlockchainRequestsCallbacks blockchainRequestsCallbacks, String targetAddress, Amount amount) throws Exception {
// TODO: get fee stats?
coinData.minFee = coinData.normalFee = coinData.maxFee = coinData.getBaseFee();
blockchainRequestsCallbacks.onComplete(true);
}
@Override
public void requestSendTransaction(BlockchainRequestsCallbacks blockchainRequestsCallbacks, byte[] txForSend) throws IOException {
final ServerApiStellar serverApi = new ServerApiStellar();
ServerApiStellar.Listener listener = new ServerApiStellar.Listener() {
@Override
public void onSuccess(StellarRequest.Base request) {
try {
if (!StellarRequest.SubmitTransaction.class.isInstance(request))
throw new Exception("Invalid request logic");
StellarRequest.SubmitTransaction submitTransactionRequest = (StellarRequest.SubmitTransaction) request;
if (submitTransactionRequest.response.isSuccess()) {
ctx.setError(null);
blockchainRequestsCallbacks.onComplete(true);
} else {
if (submitTransactionRequest.response.getExtras() != null && submitTransactionRequest.response.getExtras().getResultCodes() != null) {
String trResult = submitTransactionRequest.response.getExtras().getResultCodes().getTransactionResultCode();
if (submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes() != null && submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().size() > 0) {
trResult += "/" + submitTransactionRequest.response.getExtras().getResultCodes().getOperationsResultCodes().get(0);
}
ctx.setError(trResult);
} else {
ctx.setError("transaction failed");
}
blockchainRequestsCallbacks.onComplete(false);
}
} catch (Exception e) {
if (e.getMessage() != null) {
ctx.setError(e.getMessage());
blockchainRequestsCallbacks.onComplete(false);
} else {
ctx.setError(e.getClass().getName());
blockchainRequestsCallbacks.onComplete(false);
}
}
}
@Override
public void onFail(StellarRequest.Base request) {
ctx.setError(request.getError());
blockchainRequestsCallbacks.onComplete(false);
}
};
serverApi.setListener(listener);
Transaction transaction = TransactionEx.fromEnvelopeXdr(new String(txForSend));
coinData.incSequenceNumber();
serverApi.requestData(ctx, new StellarRequest.SubmitTransaction(transaction));
}
public boolean needMultipleLinesForBalance() {
return true;
}
public boolean allowSelectFeeLevel() {
return false;
}
public int pendingTransactionTimeoutInSeconds() { return 10; }
}

View file

@ -68,7 +68,7 @@ public class XrpEngine extends CoinEngine {
public String getBalanceHTML() {
Amount balance = getBalance();
if (balance != null) {
return " " + balance.toDescriptionString(getDecimals()) + " <br><small><small>+ " + convertToAmount(coinData.getReserveInInternalUnits()).toDescriptionString(getDecimals()) + " reserve</small></small>";
return " " + balance.toDescriptionString(getDecimals()) + "<br><small><small>+ " + convertToAmount(coinData.getReserveInInternalUnits()).toDescriptionString(getDecimals()) + " reserve</small></small>";
} else {
return "";
}