Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: optimize fee calculation #618

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ As this project is pre 1.0, breaking changes may happen for minor version bumps.
- feat: Add `Server.loadAccount` to load the `Account` object used for building transactions, supporting `MuxedAccount`.
- feat: Add support for `MuxedAccount` to `SorobanServer.getAccount`.
- feat: `FeeBumpTransaction` supports transactions that include Soroban operations.
- refactor: `TransactionBuilder#TransactionBuilder(Transaction)` has been removed, because the TransactionBuilder constructed from the transaction may be inconsistent with what the user expects.
- fix: When calling `TransactionBuilder.build()`, the Soroban resource fee will be included in the `fee` of the built transaction.
- fix: fix the issue where invoking `SorobanServer.prepareTransaction` for transactions that have already set `SorobanData` could result in unexpected high fees.

## 0.44.0
### Update
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/org/stellar/sdk/SorobanServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,11 @@ private Transaction assembleTransaction(
"unsupported transaction: must contain exactly one InvokeHostFunctionOperation, BumpSequenceOperation, or RestoreFootprintOperation");
}

// TODO: exclude exists soroban resource fee from tx fee
long classicFeeNum = transaction.getFee();
if (transaction.getSorobanData() != null) {
classicFeeNum -= transaction.getSorobanData().getResourceFee().getInt64();
}

long minResourceFeeNum =
Optional.ofNullable(simulateTransactionResponse.getMinResourceFee()).orElse(0L);
long fee = classicFeeNum + minResourceFeeNum;
Expand Down
34 changes: 7 additions & 27 deletions src/main/java/org/stellar/sdk/TransactionBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import lombok.NonNull;
Expand Down Expand Up @@ -38,31 +37,6 @@ public TransactionBuilder(
preconditions = TransactionPreconditions.builder().build();
}

/**
* Construct a new transaction builder from a transaction.
*
* @param transaction the transaction to rebuild
*/
public TransactionBuilder(Transaction transaction) {
AbstractTransaction abstractTransaction =
Transaction.fromEnvelopeXdr(transaction.toEnvelopeXdrBase64(), transaction.getNetwork());

if (!(abstractTransaction instanceof Transaction)) {
// This should never happen
throw new IllegalArgumentException(
"TransactionBuilder can only be used to rebuild a Transaction");
}
Transaction tx = (Transaction) abstractTransaction;

this.sourceAccount = new Account(tx.getSourceAccount(), tx.getSequenceNumber() - 1);
this.memo = tx.getMemo();
this.operations = Arrays.asList(tx.getOperations());
this.baseFee = tx.getFee() / tx.getOperations().length;
this.network = tx.getNetwork();
this.preconditions = tx.getPreconditions();
this.sorobanData = tx.getSorobanData();
}

public int getOperationsCount() {
return operations.size();
}
Expand Down Expand Up @@ -204,10 +178,16 @@ public Transaction build() {
long sequenceNumber = sourceAccount.getIncrementedSequenceNumber();
Operation[] operations = new Operation[this.operations.size()];
operations = this.operations.toArray(operations);

long fee = operations.length * baseFee;
if (sorobanData != null) {
fee += sorobanData.getResourceFee().getInt64();
}

Transaction transaction =
new Transaction(
sourceAccount.getAccountId(),
operations.length * baseFee,
fee,
sequenceNumber,
operations,
memo,
Expand Down
8 changes: 4 additions & 4 deletions src/test/java/org/stellar/sdk/SorobanServerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1048,8 +1048,8 @@ public void testPrepareTransactionWithSorobanData()
+ " \"jsonrpc\": \"2.0\",\n"
+ " \"id\": \"7a469b9d6ed4444893491be530862ce3\",\n"
+ " \"result\": {\n"
+ " \"transactionData\": \"AAAAAAAAAAIAAAAGAAAAAem354u9STQWq5b3Ed1j9tOemvL7xV0NPwhn4gXg0AP8AAAAFAAAAAEAAAAH8dTe2OoI0BnhlDbH0fWvXmvprkBvBAgKIcL9busuuMEAAAABAAAABgAAAAHpt+eLvUk0FquW9xHdY/bTnpry+8VdDT8IZ+IF4NAD/AAAABAAAAABAAAAAgAAAA8AAAAHQ291bnRlcgAAAAASAAAAAAAAAABYt8SiyPKXqo89JHEoH9/M7K/kjlZjMT7BjhKnPsqYoQAAAAEAHifGAAAFlAAAAIgAAAAAAAAAAg==\",\n"
+ " \"minResourceFee\": \"58181\",\n"
+ " \"transactionData\": \"AAAAAAAAAAEAAAAGAAAAAdeSi3LCcDzP6vfrn/TvTVBKVai5efybRQ6iyEK00c5hAAAAFAAAAAEAAAACAAAAAAAAAABPFZKkWLE8Tlrm5Jx81FUrXpm6EhpW/s8TXPUyf0D5PgAAAAAAAAAAbjEdZhNooxW4Z5oCpgPDCmGnVRwOxutuDO14EQ4kFmoAA3kUAAACGAAAASAAAAAAAAG4Sw==\",\n"
+ " \"minResourceFee\": \"12500\",\n"
+ " \"events\": [\n"
+ " \"AAAAAQAAAAAAAAAAAAAAAgAAAAAAAAADAAAADwAAAAdmbl9jYWxsAAAAAA0AAAAg6bfni71JNBarlvcR3WP2056a8vvFXQ0/CGfiBeDQA/wAAAAPAAAACWluY3JlbWVudAAAAAAAABAAAAABAAAAAgAAABIAAAAAAAAAAFi3xKLI8peqjz0kcSgf38zsr+SOVmMxPsGOEqc+ypihAAAAAwAAAAo=\",\n"
+ " \"AAAAAQAAAAAAAAAB6bfni71JNBarlvcR3WP2056a8vvFXQ0/CGfiBeDQA/wAAAACAAAAAAAAAAIAAAAPAAAACWZuX3JldHVybgAAAAAAAA8AAAAJaW5jcmVtZW50AAAAAAAAAwAAABQ=\"\n"
Expand Down Expand Up @@ -1126,7 +1126,7 @@ public MockResponse dispatch(@NotNull RecordedRequest recordedRequest)

SorobanTransactionData sorobanData =
SorobanTransactionData.fromXdrBase64(
"AAAAAAAAAAIAAAAGAAAAAem354u9STQWq5b3Ed1j9tOemvL7xV0NPwhn4gXg0AP8AAAAFAAAAAEAAAAH8dTe2OoI0BnhlDbH0fWvXmvprkBvBAgKIcL9busuuMEAAAABAAAABgAAAAHpt+eLvUk0FquW9xHdY/bTnpry+8VdDT8IZ+IF4NAD/AAAABAAAAABAAAAAgAAAA8AAAAHQ291bnRlcgAAAAASAAAAAAAAAABYt8SiyPKXqo89JHEoH9/M7K/kjlZjMT7BjhKnPsqYoQAAAAEAHifGAAAFlAAAAIgAAAAAAAAAAg==");
"AAAAAAAAAAEAAAAGAAAAAdeSi3LCcDzP6vfrn/TvTVBKVai5efybRQ6iyEK00c5hAAAAFAAAAAEAAAACAAAAAAAAAABPFZKkWLE8Tlrm5Jx81FUrXpm6EhpW/s8TXPUyf0D5PgAAAAAAAAAAbjEdZhNooxW4Z5oCpgPDCmGnVRwOxutuDO14EQ4kFmoAA3kUAAACGAAAASAAAAAAAAG4Sw==");
InvokeHostFunctionOperation operation =
InvokeHostFunctionOperation.builder()
.hostFunction(
Expand All @@ -1140,7 +1140,7 @@ public MockResponse dispatch(@NotNull RecordedRequest recordedRequest)
Transaction expectedTx =
new Transaction(
transaction.getSourceAccount(),
transaction.getFee() + 58181L,
50000 + 12500, // baseFee + Soroban Fee
transaction.getSequenceNumber(),
new Operation[] {operation},
transaction.getMemo(),
Expand Down
54 changes: 0 additions & 54 deletions src/test/java/org/stellar/sdk/TransactionBuilderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import org.stellar.sdk.exception.FormatException;
import org.stellar.sdk.operations.BumpSequenceOperation;
import org.stellar.sdk.operations.CreateAccountOperation;
import org.stellar.sdk.operations.InvokeHostFunctionOperation;
import org.stellar.sdk.xdr.*;
Expand Down Expand Up @@ -930,58 +928,6 @@ public void testNoNetworkSet() throws FormatException {
}
}

@Test
public void testBuilderFromTx() {
KeyPair source =
KeyPair.fromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS");

Account account = new Account(source.getAccountId(), 2908908335136768L);
BumpSequenceOperation operation0 = BumpSequenceOperation.builder().bumpTo(1L).build();
BumpSequenceOperation operation1 = BumpSequenceOperation.builder().bumpTo(2L).build();
LedgerKey ledgerKey =
LedgerKey.builder()
.discriminant(LedgerEntryType.ACCOUNT)
.account(
LedgerKey.LedgerKeyAccount.builder()
.accountID(
KeyPair.fromAccountId(
"GB7TAYRUZGE6TVT7NHP5SMIZRNQA6PLM423EYISAOAP3MKYIQMVYP2JO")
.getXdrAccountId())
.build())
.build();
SorobanTransactionData sorobanData =
SorobanTransactionData.builder()
.resources(
SorobanResources.builder()
.footprint(
LedgerFootprint.builder()
.readOnly(new LedgerKey[] {ledgerKey})
.readWrite(new LedgerKey[] {})
.build())
.readBytes(new Uint32(new XdrUnsignedInteger(699)))
.writeBytes(new Uint32(new XdrUnsignedInteger(0)))
.instructions(new Uint32(new XdrUnsignedInteger(34567)))
.build())
.resourceFee(new Int64(100L))
.ext(ExtensionPoint.builder().discriminant(0).build())
.build();

Transaction transaction =
new Transaction(
account.getAccountId(),
980,
account.getIncrementedSequenceNumber(),
new org.stellar.sdk.operations.Operation[] {operation0, operation1},
new MemoText("hello"),
new TransactionPreconditions(
null, null, BigInteger.ZERO, 0, new ArrayList<>(), new TimeBounds(100, 200)),
sorobanData, // For testing purposes, it is impossible to occur in a real environment.
Network.PUBLIC);

TransactionBuilder builder = new TransactionBuilder(transaction);
assertEquals(transaction, builder.build());
}

@Test
public void voidBuilderSorobanDataXdrString() {
KeyPair source =
Expand Down
Loading