Git Product home page Git Product logo

java-stellar-sdk's Introduction

java-stellar-sdk

Test and Deploy Maven Central Version javadoc

The Java Stellar SDK library provides APIs to build transactions and connect to Horizon and Soroban-RPC Server.

Installation

Apache Maven

<dependency>
    <groupId>network.lightsail</groupId>
    <artifactId>stellar-sdk</artifactId>
    <version>0.44.0</version>
</dependency>

Gradle

implementation 'network.lightsail:stellar-sdk:0.44.0'

You can find instructions on how to install this dependency using alternative package managers here.

JAR

Download the latest jar from the GitHub repo's releases tab. Add the jar package to your project according to how your environment is set up.

Basic Usage

For some examples on how to use this library, take a look at the Get Started docs in the developers site.

Documentation

Javadoc is available at https://javadoc.io/doc/network.lightsail/stellar-sdk

Integrate into Android project

If you want to integrate this SDK on Android platforms with API level 28 and above, you don't need any additional configuration. However, if you need to include it on lower platforms, you may also need to add the Java Stellar SDK Android SPI.

Contributing

For information on how to contribute, please refer to our contribution guide.

License

java-stellar-sdk is licensed under an Apache-2.0 license. See the LICENSE file for details.

java-stellar-sdk's People

Contributors

abuiles avatar ardevd avatar bartekn avatar bjfish avatar davejohnclark avatar efritze avatar ifropc avatar irisli avatar jakeurban avatar jillesvangurp avatar jmayeux-circle avatar jonlorusso avatar juandynomite avatar lijamie98 avatar marcelosalloum avatar michaeljmonte avatar nikhilsaraf avatar nullstyle avatar overcat avatar quanglam2807 avatar sreuland avatar synesso avatar tamirms avatar tomerweller avatar vinamogit avatar westonal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-stellar-sdk's Issues

Error message/exception when server connection parameters are wrong should be more informative

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Not a JSON Object: "Welcome"
at com.google.gson.Gson.fromJson(Gson.java:826)
at com.google.gson.Gson.fromJson(Gson.java:779)
at com.google.gson.Gson.fromJson(Gson.java:728)
at org.stellar.sdk.requests.ResponseHandler.handleResponse(ResponseHandler.java:45)
at org.apache.http.client.fluent.Response.handleResponse(Response.java:90)
at org.stellar.sdk.requests.AccountsRequestBuilder.execute(AccountsRequestBuilder.java:35)
at org.stellar.sdk.requests.AccountsRequestBuilder.execute(AccountsRequestBuilder.java:39)
at org.mifos.connector.stellar.SendTransaction.main(SendTransaction.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Page.getNextPage returns an empty Page object

Calling Page.getNextPage returns an empty Page object when even when there is more content. It looks like the getNextPage method doesn't have enough type information to construct the correct TypeToken (the type T has been erased by this point, so the TypeToken will just be TypeToken<Page> rather than e.g. TypeToken<Page<OperationResponse>>).

The first Page response is request with the correct concrete type, and the TypeToken is available in the ResponseHandler.handleResponse method. I've put together a branch with a quick-fix for this that preserves the input TypeToken on any object implementing a new TypedResponse interface. This lets it be re-used within getNextPage.

You can see it at davejohnclark@7960f78 if this looks reasonable I'm happy to tidy this up and get a PR raised.

Support the Stellar memo convention.

stellar/stellar-protocol#28

Steps that need to happen when you handle an incoming message:

  1. you receive a tx
  2. Do you already have a preimage of the memo?
  3. no -> Fetch the preimage
    • Look up the home domain of the source account
      • Fetch the stellar.toml
    • or, Look for a "msg_server" key on the account
    • ask the MESSAGE_SERVER for the preimage of the tx memo
  4. Check signature on any signed blocks.
  5. Are there blocks that are encrypted?
    • Do we have the key?
    • yes -> decrypt
    • no -> ignore

after processing, the sdk should for each operation provide:

  • note
  • user info
  • routing info

We need to think a bit how we are going to implement this in the various sdk's @nullstyle

Page.getNextPage throws a Null pointer exception when you're on the last page

To reproduce:

      Page<Path>` paths;
      paths = server.paths()
          .sourceAccount(sourceAccountKeyPair)
          .destinationAccount(targetAccountKeyPair)
          .destinationAsset(targetAsset)
          .destinationAmount(bigDecimalToStellarBalance(amount))
          .execute();

      while (paths != null) {
        for (final Path path : paths.getRecords())
        {
...
        }

        paths = paths.getNextPage();
      }

I'm not sure what the actually intended exit condition is for the last page. It would be helpful to document this. I will work around this by checking getLinks() and getNext() for null.

SEP-0005 (and BIP-39)

99% of the code is already done in BitcoinJ and really just a matter of rewriting the Key derivation to use the right "ed25519 seed" instead of "Bitcoin seed"

@bartekn Do you already have something planned or should I go ahead and prepare a PR ?

Document various enums and flags

In writing code for setting account flags, it would be nice to be able to use the relevant enum:

import static org.stellar.sdk.xdr.AccountFlags.*;
new SetOptionsOperation.Builder()
    .setSetFlags(AUTH_REQUIRED_FLAG.getValue() | AUTH_REVOCABLE_FLAG.getValue())
    .build();

// the above is more clear than:
new SetOptionsOperation.Builder()
    .setSetFlags(1 | 2)
    .build();

…but the XDR bits are not documented, so someone wouldn't know those exist without browsing the source. It would be nice if these were documented somehow (not sure how easy that is since the XDR is generated).

Transactions deserialized in a page do not contain memo data.

Basically when deserializing a page of transactions, the memo fields for all of the transactions will be null. This is easily reproducible using the TransactionPageDeserializerTest.testDeserialize method.

We tracked this down to the PageDeserializer not registering the TransactionDeserializer. I would have put in a pull request for it, however there are two issues.

  1. This might have been by desgin.
  2. If we register TransactionDeserializer in PageDeserializer , TransactionPageDeserializerTest.testDeserialize will fail because of the JSON: Memo: An empty "memo" is not being generated for a transaction even if "memo_type" is "text" issue I added over in the Horizon code base.

The use of interfaces is inconsistent.

Specifically TransactionBuilderAccount is an interface for exactly one class. Interfaces are also a potential backwards compatibility problem (adding methods breaks backwards compatibility unless you use the java 8 feature of adding default implementations), so use sparingly.

The API method for using this SDK in android has an exception

java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; in class Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; or its superclasses (declaration of 'org.apache.http.conn.ssl.AllowAllHostnameVerifier' appears in /system/framework/framework.jar:classes2.dex)

when I wirte this:“
String uri = "https://horizon-testnet.stellar.org";
Server server=null;
try {
server = new Server(uri);
}catch (Throwable e){
e.printStackTrace();
System.out.println("==========异常");
}

”then,has an exception,

factory functions, constructors, and builders are intermixed.

This is inconsistent, and steepens the learning curve by making the user look for all three when introduced to a new class.

My personal preference is factory functions combined with builders, with the required parameters in the builders constructor parameters. I'd skip the public constructors altogether, since their naming is by nature not self-explanatory in the presence of multiple variants.

Documentation is not sufficiently cross-linked:

For example: sdk.AccountCreditedEffect doesn't contain a link to the method which creates it. Such a link would be helpful for a newb trying to program against the API without any examples to work from.

java doc the ranges

For example: AccountsRequestBuilder.limit. What is the maximum value? Is it a constant set by the server or is it configurable at the server?

Try using a signature checker as part of the build.

A signature checker can automatically determine if your api is still compatible or if it will break your clients. Making a signature checker part of your build can help you avoid accidental breaking changes of the most superficial variety.

Cannot use a network : Constructor not visible.

The following does not compile.

private String PRIVATE_NETWORK = System.getenv("NETWORK_PASSPHRASE");
Network.use(new Network(PRIVATE_NETWORK));

The error message is:

The constructor Network(String) is not visible.

What is the way to use to a custom network?

"Signers" class name should not be plural

final Server stellarServer = new Server ("https://horizon-testnet.stellar.org");
final AccountsRequestBuilder accountsRequest = stellarServer.accounts();

...
Page accountsPage = accountsRequest.execute();
...
final List pageOfAccounts = accountsPage.getRecords();
for (int i = 0; i < pageOfAccounts.size(); i++) {
final Account account = pageOfAccounts.get(i);
...
final Account.Balance[] balances = account.getBalances();
final Account.Signers[] signers = account.getSigners();

If my understanding is correct, each instance of Signers actually represents one Signer. So it should not be plural. Just as Balance is not plural

AllowTrustOperation asset code is not trimmed after being parsed from XDR

Perhaps this is intentional, but it doesn't seem correct.

A roundtrip from AllowTrustOperation to XDR and back will keep unprintable characters at the tail of the asset code, if the code does not exactly meet 4 or 12 characters.

New failing test case:

  @Test
  public void testAllowTrustOperationAssetCodeBuffer() throws IOException, FormatException {
    // GC5SIC4E3V56VOHJ3OZAX5SJDTWY52JYI2AFK6PUGSXFVRJQYQXXZBZF
    KeyPair source = KeyPair.fromSecretSeed("SC4CGETADVYTCR5HEAVZRB3DZQY5Y4J7RFNJTRA6ESMHIPEZUSTE2QDK");
    // GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR
    KeyPair trustor = KeyPair.fromSecretSeed("SDHZGHURAYXKU2KMVHPOXI6JG2Q4BSQUQCEOY72O3QQTCLR2T455PMII");

    String assetCode = "USDABC";
    boolean authorize = true;

    AllowTrustOperation operation = new AllowTrustOperation.Builder(trustor, assetCode, authorize)
        .setSourceAccount(source)
        .build();

    org.stellar.sdk.xdr.Operation xdr = operation.toXdr();
    AllowTrustOperation parsedOperation = (AllowTrustOperation) Operation.fromXdr(xdr);

    assertEquals(assetCode, parsedOperation.getAssetCode());
  }
org.junit.ComparisonFailure: 
Expected :USDABC
Actual   :USDABC□□□□□□

NullPointerException when submitting transaction to create account.

I am using the following to create a new account.

	public void submitCreateAccountTxn(String fromAccId, String toAccId, String amt, String memo)
			throws IOException {
		Network.use(new Network(NETWORK_PASSPHRASE));
		Server server = new Server(HORIZON_END_POINT);
		KeyPair source = KeyPair.fromAccountId(fromAccId);
		KeyPair destination = KeyPair.fromAccountId(toAccId);
		
		AccountResponse sourceAccount = server.accounts().account(source);
		Transaction txn = new Transaction.Builder(sourceAccount)
				.addOperation(new CreateAccountOperation.Builder(destination, amt).build()).addMemo(Memo.text(memo))
				.build();
		txn.sign(source);

		SubmitTransactionResponse response = server.submitTransaction(txn);
}

It fails as follows:

Exception in thread "main" java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NullPointerException
	at org.stellar.sdk.xdr.Signature.encode(Signature.java:23)
	at org.stellar.sdk.xdr.DecoratedSignature.encode(DecoratedSignature.java:36)
	at org.stellar.sdk.xdr.TransactionEnvelope.encode(TransactionEnvelope.java:42)
	at org.stellar.sdk.Transaction.toEnvelopeXdrBase64(Transaction.java:191)
	at org.stellar.sdk.Server.submitTransaction(Server.java:120)
	... 8 more

What am I missing?

Unknown enum value when decoding TransactionResult

I submitted a transaction to Stellar Core v9.0.1 through the HTTP interface and I got the following response:
{"status":"ERROR","error":"AAAAAAAAJxD////7AAAAAA=="}
According to the documentation for Stellar Core tx command, the error field is of type TransactionResult.
So I'm trying to decode it this way:

import org.stellar.sdk.xdr.TransactionResult;

TransactionResult result = TransactionResult.decode(new XdrDataInputStream(new ByteArrayInputStream("AAAAAAAAJxD////7AAAAAA==".getBytes())));

However I'm getting the following exception:

java.lang.RuntimeException: Unknown enum value: 1249395759
	at org.stellar.sdk.xdr.TransactionResultCode.decode(TransactionResultCode.java:71)
	at org.stellar.sdk.xdr.TransactionResult$TransactionResultResult.decode(TransactionResult.java:104)
	at org.stellar.sdk.xdr.TransactionResult.decode(TransactionResult.java:66)

Am I doing something wrong? Have there been any protocol changes that are causing this?

Memo text with unicode characters doesn't decode/encode properly.

I couldn't properly decode memo texts with unicode symbols in it. It appears the Java SDK only handles memo texts with standard ascii characters.

The test below gets a base64 transaction envelope, decodes the envelope to its XDR representation, and re-encodes the XDR representation back to a base64 string. The input envelope and output envelope should match.

For standard ascii characters, the test works.
For non-standard ascii characters (e.g. €) , the test fails.

//helper method for tests below.
public static String backAndForthEnvelope(String envelope) throws IOException{
       
        //String to XDR
        byte[] bytes = java.util.Base64.getDecoder().decode(envelope.getBytes(StandardCharsets.UTF_8));
        org.stellar.sdk.xdr.TransactionEnvelope xdrTransactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
        
        
        //XDR back to String
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        XdrDataOutputStream xdrOutputStream = new XdrDataOutputStream(byteOutputStream);
        TransactionEnvelope.encode(xdrOutputStream, xdrTransactionEnvelope);
        String newEnvelope = new String(java.util.Base64.getEncoder().encode(byteOutputStream.toByteArray()), StandardCharsets.UTF_8) ;
        
        return newEnvelope;

        
    }
    
     @Test
    public void backAndForthWithAsciiMemo() throws IOException{
        //this works.
        //memo text: School Fees.
        String envelope = "AAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAZAA8tDoAAAAOAAAAAAAAAAEAAAASR29sZCA+IFNpbHZlciDwn5iAAAAAAAABAAAAAAAAAAEAAAAAEURBrJXnOPJmyScoCMGaC70bS+v4Bi+LLNkzqZzlDoYAAAABR09MRAAAAAAqtSMXMNX3IbReWi00sNc2mAGI291mwUXeI6mCSk4QfQAAAAAdzWUAAAAAAAAAAAA=";
        assertEquals(envelope, backAndForthEnvelope(envelope));
        
    }

@Test
    public void backAndForthEuroMemo() throws IOException{
        //this doesn't work.
        //memo text: Not Euros €
        String envelope = "AAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAZAA8tDoAAAAOAAAAAAAAAAEAAAANTm90IEV1cm9zIOKCrAAAAAAAAAEAAAAAAAAAAQAAAAAcxcusLBr20f4AF4AA+nWmCYeoFL17Tzv3KVNIcKsKFQAAAAAAAAAAHc1lAAAAAAAAAAAA";
        assertEquals(envelope, backAndForthEnvelope(envelope));
        
    }

Any help on this issue will be much appreciated.

Distributed Exchange is not ok

i make two Transaction, example:
ManageOfferOperation theOne= new ManageOfferOperation.Builder(newAsset, new AssetTypeNative(), "1000", "100").build();
ManageOfferOperation theTwo= new ManageOfferOperation.Builder(new AssetTypeNative(), newAsset, "100", "1000").build();
Transaction transactionA = new Transaction.Builder(accountA).addOperation(operation).addMemo(Memo.text("A")).build();

then submit two transaction and SubmitTransactionResponse return success,but i check the account ,the exchange is not happen. how can t to do?

javadoc the defaults

For example: AccountsRequestBuilder.limit. What is it if I don't set it? Is setting it required?

Federation.resolve needs better error returns

Currently Federation.resolve throws plain RuntimeExceptions for some kinds of errors, returns a FederationResponse containing just nulls for others, and also directly exposes the IOException. This makes error handling for the caller inconsistent and fragile. It will also make it harder for you to keep your changes in this area backwards compatible in the future.

TransactionsRequestBuilder has bug

public TransactionResponse transaction(String transactionId) throws IOException {
this.setSegments("transaction", transactionId);
return this.transaction(this.buildUri());
}

transaction --> transactions

Offers for Account has a error

class AssetDeserializer implements JsonDeserializer {
@OverRide
public Asset deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String type = json.getAsJsonObject().get("asset_type").getAsString();
if (type == "native") {
return new AssetTypeNative();
} else {
String code = json.getAsJsonObject().get("asset_code").getAsString();
String issuer = json.getAsJsonObject().get("asset_issuer").getAsString();
return Asset.createNonNativeAsset(code, KeyPair.fromAccountId(issuer));
}
}
}

type == "native" is not equal

Exception while decoding a transaction envelope containing a custom asset operation

    //This works.
    @Test 
    public void decodeTransactionEnvelopeWithNativeAsset() throws IOException {

        String transactionEnvelopeToDecode = "AAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAZAA8tDoAAAAEAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAHMXLrCwa9tH+ABeAAPp1pgmHqBS9e0879ylTSHCrChUAAAAAAAAAAB3NZQAAAAAAAAAAAA==";
        Base64 base64Codec = new Base64();

        byte[] bytes = base64Codec.decode(transactionEnvelopeToDecode);

        TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
        //no exceptions thrown here :)

        org.stellar.sdk.xdr.Transaction tx = transactionEnvelope.getTx();

        assertEquals(100, tx.getFee().getUint32().intValue());
        //this works.Yoopie!

    }

    //This doesn't work.
    @Test 
    public void decodeTransactionEnvelopeWithCustomAsset() throws IOException {

        String transactionEnvelopeToDecode = "AAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAZAA8tDoAAAALAAAAAAAAAAEAAAAZR29sZCBwYXltZW50IGZvciBzZXJ2aWNlcwAAAAAAAAEAAAAAAAAAAQAAAAARREGslec48mbJJygIwZoLvRtL6/gGL4ss2TOpnOUOhgAAAAFHT0xEAAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAADuaygAAAAAAAAAAAA==";

        Base64 base64Codec = new Base64();

        byte[] bytes = base64Codec.decode(transactionEnvelopeToDecode);

        TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
        //TransactionEnvelope.decode is throwing the following exception :(
//        **Caused by: java.lang.RuntimeException: Unknown enum value: 21450572**
//	at org.stellar.sdk.xdr.AssetType.decode(AssetType.java:41) ~[stellar-1.jar:0.1.12]
//	at org.stellar.sdk.xdr.Asset.decode(Asset.java:72) ~[stellar-1.jar:0.1.12]
//	at org.stellar.sdk.xdr.PaymentOp.decode(PaymentOp.java:50) ~[stellar-1.jar:0.1.12]
//	at org.stellar.sdk.xdr.Operation$OperationBody.decode(Operation.java:207) ~[stellar-1.jar:0.1.12]
//	at org.stellar.sdk.xdr.Operation.decode(Operation.java:78) ~[stellar-1.jar:0.1.12]
//	at org.stellar.sdk.xdr.Transaction.decode(Transaction.java:121) ~[stellar-1.jar:0.1.12]
//	at org.stellar.sdk.xdr.TransactionEnvelope.decode(TransactionEnvelope.java:47) ~[stellar-1.jar:0.1.12]

        //unreachable code below.
        org.stellar.sdk.xdr.Transaction tx = transactionEnvelope.getTx();

        assertEquals(100, tx.getFee().getUint32().intValue());

    }

Provide the sdk in the popular maven repos

Developers who develop for the jvm (be it in java, scala, kotlin or the like) usually like to add their dependencies in the usual build tools. Therefore it would make sense to put the sdk on jcenter and maven central.

Issue while fetching offerid for a successful transaction with manage offer operation

I am getting nullpointer exception while I am trying to fetch the offer id from the SubmitTransactionResponse Object.

ManageOfferOperation manageOfferOp = new ManageOfferOperation.Builder(sendingAsset, receivingAsset, "12", "0.5").setOfferId(0).setSourceAccount(issuingAccount).build();
		
		Transaction manageOffer = new Transaction.Builder(source)
		  .addOperation(manageOfferOp)
		  .build();
		manageOffer.sign(issuingKeys);
		
		System.out.println("Transaction xdr " + manageOffer.toEnvelopeXdrBase64());
		SubmitTransactionResponse  subtranresponse= server.submitTransaction(manageOffer);
			
		System.out.println("subtranresponse.isSuccess(): "+ subtranresponse.isSuccess());
		if(subtranresponse.isSuccess())
		{
			Long offerid=subtranresponse.getOfferIdFromResult(0);
			if(null!=subtranresponse.getOfferIdFromResult(0)){
				System.out.println("offerid: "+ offerid);
				System.out.println("subtranresponse.getEnvelopeXdr(): "+ subtranresponse.getEnvelopeXdr());
				System.out.println("subtranresponse.getResultXdr(): "+ subtranresponse.getResultXdr());
			System.out.println("Offer submitted successfully" + subtranresponse.getOfferIdFromResult(0));
			System.out.println("Get hash:"+ subtranresponse.getHash() + "Ledger: "+ subtranresponse.getLedger().toString()) ;
			}
		}

I am getting nullpointerexception in Long offerid=subtranresponse.getOfferIdFromResult(0); line

This behavior is random. When I retry submitting the txn with same code and input param, I get the success response with proper offer-id.

However value of subtranresponse.isSuccess() is always true.

Tried using local horizon server as well as Stellar's horizon.

Precision of `Price`

A Price instance can be created from a String representation of a BigDecimal, with the caveat that it is an approximate value.

Are there any invariants on the input String in regard to number of significant digits? I've found that it can give some nasty results, but I don't know if the values I'm providing are outside expected usage.

e.g. "14327483647.52312312" approximates to 1 / 0.

A user may create a ManageOfferOperation with a value such as this and would get quite an unexpected result. It would be good to understand the input invariants and assert them.

Additionally, it would be good to understand how much variance can be expected on the approximated result.

Balances should have Asset and KeyPair instances

Since asset are generally represented by the Asset class, it's a little surprising that there is no way to get an Asset instance from a Balance. This makes example code I'm writing to check balances for particular assets pretty awkward:

for (AccountResponse.Balance balance : accountToCheck.getBalances()) {
  if (!balance.getAssetType().equals("native") &&
      balance.getAssetCode().equals(someSpecialAsset.getCode()) &&
      balance.getAssetIssuer().equals(someSpecialAsset.getIssuer().getAccountId())) {
    // do something useful with this balance
  }
}

when it could just be:

for (AccountResponse.Balance balance : accountToCheck.getBalances()) {
  if (balance.getAsset().equals(someSpecialAsset)) {
    // do something useful with this balance
  }
}

In addition, a balance’s getAssetIssuer() returns a String, which is different from asset’s getIssuer() and most other places in the SDK, where a KeyPair is returned. That makes the code above doubly awkward:

balance.getAssetIssuer().equals(someSpecialAsset.getIssuer().getAccountId())

It would be a lot more convenient if it returned a KeyPair (or if a different getter returned a KeyPair to preserve backward-compatibility).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.