From 8a4cefe1fc358f5b9305d5404bc28ee73a73a1d5 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Wed, 29 May 2019 18:22:17 +0200 Subject: [PATCH 01/19] refactored to object id classes --- .../main/java/ch/decent/sdk/DCoreConstants.kt | 12 +- .../src/main/java/ch/decent/sdk/DCoreSdk.kt | 5 +- .../main/java/ch/decent/sdk/api/AccountApi.kt | 36 ++--- .../main/java/ch/decent/sdk/api/AssetApi.kt | 31 ++-- .../main/java/ch/decent/sdk/api/BalanceApi.kt | 17 +-- .../main/java/ch/decent/sdk/api/ContentApi.kt | 38 ++--- .../main/java/ch/decent/sdk/api/HistoryApi.kt | 30 ++-- .../java/ch/decent/sdk/api/MessagingApi.kt | 20 +-- .../main/java/ch/decent/sdk/api/MiningApi.kt | 17 +-- .../java/ch/decent/sdk/api/PurchaseApi.kt | 17 +-- .../main/java/ch/decent/sdk/api/SeederApi.kt | 4 +- .../java/ch/decent/sdk/api/SubscriptionApi.kt | 13 +- .../java/ch/decent/sdk/api/TransactionApi.kt | 6 +- .../java/ch/decent/sdk/api/ValidationApi.kt | 14 +- .../java/ch/decent/sdk/crypto/Credentials.kt | 6 +- .../main/java/ch/decent/sdk/crypto/Wallet.kt | 4 +- .../java/ch/decent/sdk/crypto/WalletFile.kt | 4 +- .../main/java/ch/decent/sdk/model/Account.kt | 6 +- .../ch/decent/sdk/model/AccountBalance.kt | 6 +- .../ch/decent/sdk/model/AccountOptions.kt | 5 +- .../ch/decent/sdk/model/AccountStatistics.kt | 6 +- .../main/java/ch/decent/sdk/model/Asset.kt | 12 +- .../java/ch/decent/sdk/model/AssetAmount.kt | 5 +- .../java/ch/decent/sdk/model/AssetData.kt | 2 +- .../ch/decent/sdk/model/AssetFormatter.kt | 2 +- .../java/ch/decent/sdk/model/BlockHeader.kt | 2 +- .../java/ch/decent/sdk/model/ChainObject.kt | 61 -------- .../ch/decent/sdk/model/ChainProperties.kt | 2 +- .../java/ch/decent/sdk/model/CoAuthors.kt | 2 +- .../main/java/ch/decent/sdk/model/Config.kt | 6 +- .../main/java/ch/decent/sdk/model/Content.kt | 10 +- .../ch/decent/sdk/model/ContentSummary.kt | 23 +++ .../ch/decent/sdk/model/DynamicGlobalProps.kt | 4 +- .../java/ch/decent/sdk/model/ExchangeRate.kt | 2 +- .../src/main/java/ch/decent/sdk/model/Fee.kt | 3 +- .../java/ch/decent/sdk/model/FeeSchedule.kt | 6 +- .../ch/decent/sdk/model/GlobalProperties.kt | 4 +- .../ch/decent/sdk/model/MessageResponse.kt | 20 +-- .../main/java/ch/decent/sdk/model/Miner.kt | 6 +- .../main/java/ch/decent/sdk/model/MinerId.kt | 2 +- .../ch/decent/sdk/model/MinerVotingInfo.kt | 2 +- .../main/java/ch/decent/sdk/model/ObjectId.kt | 135 ++++++++++++++++++ .../java/ch/decent/sdk/model/ObjectType.kt | 121 +++++++++------- .../ch/decent/sdk/model/OperationHistory.kt | 2 +- .../main/java/ch/decent/sdk/model/Purchase.kt | 11 +- .../main/java/ch/decent/sdk/model/Seeder.kt | 6 +- .../java/ch/decent/sdk/model/SignedBlock.kt | 2 +- .../java/ch/decent/sdk/model/Subscription.kt | 5 +- .../ch/decent/sdk/model/TransactionDetail.kt | 6 +- .../java/ch/decent/sdk/model/TypeAdapters.kt | 46 ++++-- .../ch/decent/sdk/model/VestingBalance.kt | 3 +- .../model/operation/AccountCreateOperation.kt | 8 +- .../model/operation/AccountUpdateOperation.kt | 8 +- .../operation/AddOrUpdateContentOperation.kt | 10 +- .../operation/AssetClaimFeesOperation.kt | 11 +- .../model/operation/AssetCreateOperation.kt | 6 +- .../operation/AssetFundPoolsOperation.kt | 11 +- .../model/operation/AssetIssueOperation.kt | 12 +- .../operation/AssetPublishFeedOperation.kt | 12 +- .../model/operation/AssetReserveOperation.kt | 9 +- .../operation/AssetUpdateAdvancedOperation.kt | 10 +- .../AssetUpdateMonitoredOperation.kt | 10 +- .../model/operation/AssetUpdateOperation.kt | 14 +- .../sdk/model/operation/CustomOperation.kt | 6 +- .../LeaveRatingAndCommentOperation.kt | 4 +- .../sdk/model/operation/OperationType.kt | 3 +- .../operation/PurchaseContentOperation.kt | 6 +- .../model/operation/RemoveContentOperation.kt | 9 +- .../model/operation/SendMessageOperation.kt | 6 +- .../sdk/model/operation/TransferOperation.kt | 8 +- .../sdk/model/operation/UnknownOperation.kt | 9 ++ .../net/model/request/GenerateContentKeys.kt | 12 +- .../GetAccountBalanceForTransaction.kt | 16 +-- .../net/model/request/GetAccountBalances.kt | 18 +-- .../sdk/net/model/request/GetAccountById.kt | 12 +- .../net/model/request/GetAccountHistory.kt | 21 +-- .../net/model/request/GetAccountReferences.kt | 8 +- .../decent/sdk/net/model/request/GetAssets.kt | 12 +- .../sdk/net/model/request/GetAssetsData.kt | 11 +- .../net/model/request/GetBuyingByConsumer.kt | 11 +- .../sdk/net/model/request/GetBuyingByUri.kt | 11 +- .../sdk/net/model/request/GetContentById.kt | 12 +- .../sdk/net/model/request/GetFeedsByMiner.kt | 13 +- .../sdk/net/model/request/GetFullAccounts.kt | 9 +- .../request/GetHistoryBuyingsByConsumer.kt | 11 +- .../sdk/net/model/request/GetKeyReferences.kt | 6 +- .../net/model/request/GetMessageObjects.kt | 14 +- .../net/model/request/GetMinerByAccount.kt | 11 +- .../decent/sdk/net/model/request/GetMiners.kt | 12 +- .../model/request/GetNamedAccountBalances.kt | 6 +- .../sdk/net/model/request/GetObjects.kt | 4 +- .../model/request/GetOpenBuyingsByConsumer.kt | 11 +- .../model/request/GetProposedTransactions.kt | 11 +- .../request/GetRelativeAccountHistory.kt | 14 +- .../sdk/net/model/request/GetRequiredFees.kt | 11 +- .../decent/sdk/net/model/request/GetSeeder.kt | 12 +- .../sdk/net/model/request/GetSubscription.kt | 11 +- .../net/model/request/GetVestingBalances.kt | 14 +- .../ListActiveSubscriptionsByAuthor.kt | 12 +- .../ListActiveSubscriptionsByConsumer.kt | 12 +- .../model/request/ListPublishingManagers.kt | 7 +- .../request/ListSubscriptionsByAuthor.kt | 12 +- .../request/ListSubscriptionsByConsumer.kt | 12 +- .../sdk/net/model/request/LookupAccounts.kt | 6 +- .../sdk/net/model/request/LookupMiners.kt | 16 --- .../net/model/request/RestoreEncryptionKey.kt | 12 +- .../request/SearchAccountBalanceHistory.kt | 18 +-- .../net/model/request/SearchAccountHistory.kt | 20 ++- .../sdk/net/model/request/SearchAccounts.kt | 14 +- .../sdk/net/model/request/SearchBuyings.kt | 19 +-- .../sdk/net/model/request/SearchContent.kt | 12 +- .../sdk/net/model/request/SearchFeedback.kt | 9 +- .../net/model/request/SearchMinerVoting.kt | 9 +- .../model/request/VerifyAccountAuthority.kt | 7 +- .../sdk/net/serialization/Serializer.kt | 11 +- .../src/test/java/ch/decent/sdk/CrytpoTest.kt | 15 +- .../src/test/java/ch/decent/sdk/Helpers.kt | 7 +- .../src/test/java/ch/decent/sdk/Scratchpad.kt | 7 +- .../java/ch/decent/sdk/api/AssetApiTest.kt | 16 +-- .../java/ch/decent/sdk/api/BalanceApiTest.kt | 8 +- .../java/ch/decent/sdk/api/ContentApiTest.kt | 14 +- .../java/ch/decent/sdk/api/HistoryApiTest.kt | 6 +- .../java/ch/decent/sdk/api/MiningApiTest.kt | 8 +- .../java/ch/decent/sdk/api/OperationsTest.kt | 15 +- .../java/ch/decent/sdk/api/SeederApiTest.kt | 6 +- .../ch/decent/sdk/api/ValidationApiTest.kt | 4 +- .../java/ch/decent/sdk/api/java/ApiTest.java | 78 +++++----- .../java/ch/decent/sdk/model/AssetTest.kt | 12 +- .../java/ch/decent/sdk/net/SerializerTest.kt | 25 ++-- 129 files changed, 822 insertions(+), 903 deletions(-) delete mode 100644 library/src/main/java/ch/decent/sdk/model/ChainObject.kt create mode 100644 library/src/main/java/ch/decent/sdk/model/ContentSummary.kt create mode 100644 library/src/main/java/ch/decent/sdk/model/ObjectId.kt create mode 100644 library/src/main/java/ch/decent/sdk/model/operation/UnknownOperation.kt delete mode 100644 library/src/main/java/ch/decent/sdk/net/model/request/LookupMiners.kt diff --git a/library/src/main/java/ch/decent/sdk/DCoreConstants.kt b/library/src/main/java/ch/decent/sdk/DCoreConstants.kt index bc265502..d75e88c3 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreConstants.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreConstants.kt @@ -1,8 +1,10 @@ package ch.decent.sdk +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Asset +import ch.decent.sdk.model.AssetDataObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.AssetOptions -import ch.decent.sdk.model.toChainObject import ch.decent.sdk.utils.PRECISION_MAX import ch.decent.sdk.utils.RATING_MAX @@ -10,15 +12,16 @@ object DCoreConstants { private const val DCT_PRECISION: Byte = 8 private const val DCT_SUPPLY = 7319777577456900 - @JvmField val DCT_ASSET_ID = "1.3.0".toChainObject() + @JvmField val PROXY_TO_SELF = AccountObjectId(3) + @JvmField val DCT_ASSET_ID = AssetObjectId() @JvmField val DCT = Asset( DCT_ASSET_ID, "DCT", DCT_PRECISION, - "1.2.1".toChainObject(), + AccountObjectId(1), "", AssetOptions(maxSupply = DCT_SUPPLY), - "2.3.0".toChainObject() + AssetDataObjectId(0) ) const val ALXT_SYMBOL = "ALXT" @@ -34,5 +37,6 @@ object DCoreConstants { val PRECISION_ALLOWED = 0..PRECISION_MAX const val UIA_DESCRIPTION_MAX_CHARS = 1000 const val BASIS_POINTS_TOTAL = 10000 + const val MAX_INSTANCE_ID = 281474976710655 } diff --git a/library/src/main/java/ch/decent/sdk/DCoreSdk.kt b/library/src/main/java/ch/decent/sdk/DCoreSdk.kt index 16a0a8a5..51a028f9 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreSdk.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreSdk.kt @@ -4,8 +4,6 @@ import ch.decent.sdk.crypto.Address import ch.decent.sdk.model.AddressAdapter import ch.decent.sdk.model.AuthMap import ch.decent.sdk.model.AuthMapAdapter -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ChainObjectAdapter import ch.decent.sdk.model.CoAuthors import ch.decent.sdk.model.CoAuthorsAdapter import ch.decent.sdk.model.DateTimeAdapter @@ -14,6 +12,7 @@ import ch.decent.sdk.model.FeeParamAdapter import ch.decent.sdk.model.FeeParameter import ch.decent.sdk.model.MinerId import ch.decent.sdk.model.MinerIdAdapter +import ch.decent.sdk.model.ObjectIdFactory import ch.decent.sdk.model.OperationTypeAdapter import ch.decent.sdk.model.OperationTypeFactory import ch.decent.sdk.model.PubKey @@ -93,7 +92,7 @@ class DCoreSdk private constructor( .disableHtmlEscaping() .registerTypeAdapterFactory(OperationTypeFactory) .registerTypeAdapterFactory(StaticVariantFactory) - .registerTypeAdapter(ChainObject::class.java, ChainObjectAdapter) + .registerTypeAdapterFactory(ObjectIdFactory) .registerTypeAdapter(Address::class.java, AddressAdapter) .registerTypeAdapter(LocalDateTime::class.java, DateTimeAdapter) .registerTypeAdapter(AuthMap::class.java, AuthMapAdapter) diff --git a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt b/library/src/main/java/ch/decent/sdk/api/AccountApi.kt index bb4e1642..19fed37d 100644 --- a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/AccountApi.kt @@ -8,21 +8,23 @@ import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.crypto.ECKeyPair import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.Account +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AccountOptions import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.Authority -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.ObjectId import ch.decent.sdk.model.SearchAccountHistoryOrder import ch.decent.sdk.model.SearchAccountsOrder import ch.decent.sdk.model.TransactionConfirmation import ch.decent.sdk.model.TransactionDetail +import ch.decent.sdk.model.TransactionDetailObjectId +import ch.decent.sdk.model.isValidId import ch.decent.sdk.model.operation.AccountCreateOperation import ch.decent.sdk.model.operation.AccountUpdateOperation import ch.decent.sdk.model.operation.TransferOperation -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.net.model.request.GetAccountById import ch.decent.sdk.net.model.request.GetAccountByName import ch.decent.sdk.net.model.request.GetAccountCount @@ -56,7 +58,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return an account if exist, [ObjectNotFoundException] if not found */ - fun get(id: ChainObject): Single = getAll(listOf(id)).map { it.first() } + fun get(id: AccountObjectId): Single = getAll(listOf(id)).map { it.first() } /** * Get account object by name. @@ -75,7 +77,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return an account if exist, [ObjectNotFoundException] if not found, or [IllegalStateException] if the account name or id is not valid */ fun get(nameOrId: String): Single = when { - ChainObject.isValid(nameOrId) -> get(nameOrId.toChainObject()) + ObjectId.isValid(nameOrId) -> get(nameOrId.toObjectId()) Account.isValidName(nameOrId) -> getByName(nameOrId) else -> Single.error(IllegalArgumentException("not a valid account name or id")) } @@ -92,7 +94,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of account object ids */ - fun findAllReferencesByKeys(keys: List
): Single>> = GetKeyReferences(keys).toRequest() + fun findAllReferencesByKeys(keys: List
): Single>> = GetKeyReferences(keys).toRequest() /** * Get all accounts that refer to the account id in their owner or active authorities. @@ -101,7 +103,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of account object ids */ - fun findAllReferencesByAccount(accountId: ChainObject): Single> = + fun findAllReferencesByAccount(accountId: AccountObjectId): Single> = GetAccountReferences(accountId).toRequest() /** @@ -111,7 +113,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return an account list if found, [ObjectNotFoundException] otherwise */ - fun getAll(accountIds: List): Single> = GetAccountById(accountIds).toRequest() + fun getAll(accountIds: List): Single> = GetAccountById(accountIds).toRequest() /** * Fetch all objects relevant to the specified accounts and subscribe to updates. @@ -144,7 +146,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return map of account names to corresponding IDs */ @JvmOverloads - fun listAllRelative(lowerBound: String, limit: Int = 1000): Single> = + fun listAllRelative(lowerBound: String, limit: Int = 1000): Single> = LookupAccounts(lowerBound, limit).toRequest() /** @@ -161,7 +163,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { fun findAll( searchTerm: String, order: SearchAccountsOrder = SearchAccountsOrder.NAME_DESC, - id: ChainObject = ObjectType.NULL_OBJECT.genericId, + id: AccountObjectId? = null, limit: Int = 1000 ): Single> = SearchAccounts(searchTerm, order, id, limit).toRequest() @@ -169,7 +171,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * Search account history. * * @param accountId object id of the account, 1.2.* - * @param from object id of the history object to start from, use [ObjectType.NULL_OBJECT.genericId] to ignore + * @param from object id of the history object to start from * @param order order of items * @param limit number of entries, max 100 * @@ -178,8 +180,8 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { @Deprecated(message = "Use history API") @JvmOverloads fun searchAccountHistory( - accountId: ChainObject, - from: ChainObject = ObjectType.NULL_OBJECT.genericId, + accountId: AccountObjectId, + from: TransactionDetailObjectId? = null, order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, limit: Int = 100 ): Single> = SearchAccountHistory(accountId, order, from, limit).toRequest() @@ -217,8 +219,8 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { encrypted: Boolean = true, fee: Fee = Fee() ): Single = - if ((memo.isNullOrBlank() || !encrypted) && ChainObject.isValid(nameOrId)) { - Single.just(TransferOperation(credentials.account, nameOrId.toChainObject(), amount, memo?.let { Memo(it) }, fee)) + if ((memo.isNullOrBlank() || !encrypted) && nameOrId.isValidId()) { + Single.just(TransferOperation(credentials.account, nameOrId.toObjectId(), amount, memo?.let { Memo(it) }, fee)) } else { get(nameOrId).map { receiver -> val msg = memo?.let { if (encrypted) Memo(memo, credentials, receiver) else Memo(memo) } @@ -265,7 +267,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { */ @JvmOverloads fun createAccountOperation( - registrar: ChainObject, + registrar: AccountObjectId, name: String, address: Address, fee: Fee = Fee() @@ -325,7 +327,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { active: Authority? = null, owner: Authority? = null, fee: Fee = Fee() - ): Single = createUpdateOperation(credentials.account.objectId, fee) + ): Single = createUpdateOperation(credentials.account.toString(), fee) .map { it.apply { this.options = options diff --git a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt b/library/src/main/java/ch/decent/sdk/api/AssetApi.kt index 2683ddfc..38113536 100644 --- a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/AssetApi.kt @@ -5,17 +5,20 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Asset import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.AssetData +import ch.decent.sdk.model.AssetDataObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.AssetOptions -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.ExchangeRate import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo import ch.decent.sdk.model.MonitoredAssetOptions import ch.decent.sdk.model.RealSupply import ch.decent.sdk.model.TransactionConfirmation +import ch.decent.sdk.model.isValidId import ch.decent.sdk.model.operation.AssetClaimFeesOperation import ch.decent.sdk.model.operation.AssetCreateOperation import ch.decent.sdk.model.operation.AssetFundPoolsOperation @@ -23,7 +26,7 @@ import ch.decent.sdk.model.operation.AssetIssueOperation import ch.decent.sdk.model.operation.AssetReserveOperation import ch.decent.sdk.model.operation.AssetUpdateAdvancedOperation import ch.decent.sdk.model.operation.AssetUpdateOperation -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.net.model.request.GetAssets import ch.decent.sdk.net.model.request.GetAssetsData import ch.decent.sdk.net.model.request.GetRealSupply @@ -42,7 +45,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return asset or [ObjectNotFoundException] */ - fun get(assetId: ChainObject): Single = getAll(listOf(assetId)).map { it.single() } + fun get(assetId: AssetObjectId): Single = getAll(listOf(assetId)).map { it.single() } /** * Get assets by id. @@ -51,7 +54,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return list of assets or [ObjectNotFoundException] */ - fun getAll(assetIds: List): Single> = GetAssets(assetIds).toRequest() + fun getAll(assetIds: List): Single> = GetAssets(assetIds).toRequest() /** * Return current core asset supply. @@ -67,7 +70,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return asset dynamic data or [ObjectNotFoundException] */ - fun getAssetsData(assetId: List): Single> = GetAssetsData(assetId).toRequest() + fun getAssetsData(assetId: List): Single> = GetAssetsData(assetId).toRequest() /** * Get asset dynamic data by id. @@ -76,7 +79,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return asset dynamic data or [ObjectNotFoundException] */ - fun getAssetData(assetId: ChainObject): Single = getAssetsData(listOf(assetId)).map { it.single() } + fun getAssetData(assetId: AssetDataObjectId): Single = getAssetsData(listOf(assetId)).map { it.single() } /** * Get assets alphabetically by symbol name. @@ -120,7 +123,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * @param roundingMode rounding mode to use when rounding to target asset precision */ @JvmOverloads - fun convertFromDCT(assetId: ChainObject, amount: Long, roundingMode: RoundingMode = RoundingMode.CEILING): Single = + fun convertFromDCT(assetId: AssetObjectId, amount: Long, roundingMode: RoundingMode = RoundingMode.CEILING): Single = get(assetId).map { it.convertFromDCT(amount, roundingMode) } /** @@ -131,7 +134,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * @param roundingMode rounding mode to use when rounding to target asset precision */ @JvmOverloads - fun convertToDCT(assetId: ChainObject, amount: Long, roundingMode: RoundingMode = RoundingMode.CEILING): Single = + fun convertToDCT(assetId: AssetObjectId, amount: Long, roundingMode: RoundingMode = RoundingMode.CEILING): Single = get(assetId).map { it.convertToDCT(amount, roundingMode) } @@ -149,7 +152,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { */ @JvmOverloads fun createAssetCreateOperation( - issuer: ChainObject, + issuer: AccountObjectId, symbol: String, precision: Byte, description: String, @@ -210,7 +213,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun createAssetUpdateOperation( assetIdOrSymbol: String, - newIssuer: ChainObject? = null, + newIssuer: AccountObjectId? = null, fee: Fee = Fee() ): Single = get(assetIdOrSymbol).map { AssetUpdateOperation(it.issuer, it.id, it.description, newIssuer, it.options.maxSupply, it.options.exchangeRate, it.options.exchangeable, fee) @@ -237,7 +240,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { description: String? = null, exchangeable: Boolean? = null, maxSupply: Long? = null, - newIssuer: ChainObject? = null, + newIssuer: AccountObjectId? = null, fee: Fee = Fee() ): Single = createAssetUpdateOperation(assetIdOrSymbol, newIssuer, fee) .map { @@ -305,7 +308,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { fun createAssetIssueOperation( assetIdOrSymbol: String, amount: Long, - to: ChainObject? = null, + to: AccountObjectId? = null, memo: Memo? = null, fee: Fee = Fee() ): Single = get(assetIdOrSymbol).map { AssetIssueOperation(it.issuer, AssetAmount(amount, it.id), to ?: it.issuer, memo, fee) } @@ -326,7 +329,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { credentials: Credentials, assetIdOrSymbol: String, amount: Long, - to: ChainObject? = null, + to: AccountObjectId? = null, memo: Memo? = null, fee: Fee = Fee() ): Single = createAssetIssueOperation(assetIdOrSymbol, amount, to, memo, fee) @@ -451,6 +454,6 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { } } - private fun get(idOrSymbol: String) = if (ChainObject.isValid(idOrSymbol)) get(idOrSymbol.toChainObject()) else getByName(idOrSymbol) + private fun get(idOrSymbol: String) = if (idOrSymbol.isValidId()) get(idOrSymbol.toObjectId()) else getByName(idOrSymbol) } diff --git a/library/src/main/java/ch/decent/sdk/api/BalanceApi.kt b/library/src/main/java/ch/decent/sdk/api/BalanceApi.kt index 1087df13..de7d13fc 100644 --- a/library/src/main/java/ch/decent/sdk/api/BalanceApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/BalanceApi.kt @@ -4,9 +4,10 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.DCoreConstants +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AmountWithAsset import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.VestingBalance import ch.decent.sdk.net.model.request.GetAccountBalances import ch.decent.sdk.net.model.request.GetNamedAccountBalances @@ -23,7 +24,7 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return amount for asset */ - fun get(accountId: ChainObject, asset: ChainObject): Single = getAll(accountId, listOf(asset)).map { it.single() } + fun get(accountId: AccountObjectId, asset: AssetObjectId): Single = getAll(accountId, listOf(asset)).map { it.single() } /** * Get account balance by id. @@ -34,7 +35,7 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of amounts for different assets */ @JvmOverloads - fun getAll(accountId: ChainObject, assets: List = emptyList()): Single> = GetAccountBalances(accountId, assets).toRequest() + fun getAll(accountId: AccountObjectId, assets: List = emptyList()): Single> = GetAccountBalances(accountId, assets).toRequest() /** * get account balance by name. @@ -44,7 +45,7 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return amount for asset */ - fun get(name: String, asset: ChainObject): Single = + fun get(name: String, asset: AssetObjectId): Single = getAll(name, listOf(asset)).map { it.single() } /** @@ -56,7 +57,7 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of amounts for different assets */ @JvmOverloads - fun getAll(name: String, assets: List = emptyList()): Single> = GetNamedAccountBalances(name, assets).toRequest() + fun getAll(name: String, assets: List = emptyList()): Single> = GetNamedAccountBalances(name, assets).toRequest() /** * Get account balance by name. @@ -66,7 +67,7 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a pair of asset to amount */ - fun getWithAsset(accountId: ChainObject, assetSymbol: String = DCoreConstants.DCT_SYMBOL): Single = + fun getWithAsset(accountId: AccountObjectId, assetSymbol: String = DCoreConstants.DCT_SYMBOL): Single = getAllWithAsset(accountId, listOf(assetSymbol)).map { it.single() } /** @@ -77,7 +78,7 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of pairs of assets to amounts */ - fun getAllWithAsset(accountId: ChainObject, assetSymbols: List): Single> = + fun getAllWithAsset(accountId: AccountObjectId, assetSymbols: List): Single> = api.assetApi.getAllByName(assetSymbols).flatMap { assets -> getAll(accountId, assets.map { it.id }).map { it.map { balance -> AmountWithAsset(assets.single { it.id == balance.assetId }, balance) } @@ -117,6 +118,6 @@ class BalanceApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of vesting balances with additional information */ - fun getAllVesting(accountId: ChainObject): Single> = GetVestingBalances(accountId).toRequest() + fun getAllVesting(accountId: AccountObjectId): Single> = GetVestingBalances(accountId).toRequest() } diff --git a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt b/library/src/main/java/ch/decent/sdk/api/ContentApi.kt index cd796b12..d090871e 100644 --- a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/ContentApi.kt @@ -5,17 +5,19 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.ApplicationType import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.CategoryType -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.CoAuthors import ch.decent.sdk.model.Content import ch.decent.sdk.model.ContentKeys +import ch.decent.sdk.model.ContentObjectId +import ch.decent.sdk.model.ContentSummary import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.PubKey +import ch.decent.sdk.model.PurchaseObjectId import ch.decent.sdk.model.RegionalPrice import ch.decent.sdk.model.Regions import ch.decent.sdk.model.SearchContentOrder @@ -44,7 +46,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return generated key and key parts */ - fun generateKeys(seeders: List): Single = GenerateContentKeys(seeders).toRequest() + fun generateKeys(seeders: List): Single = GenerateContentKeys(seeders).toRequest() /** * Get content by id. @@ -53,7 +55,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a content if found, [ch.decent.sdk.exception.ObjectNotFoundException] otherwise */ - fun get(contentId: ChainObject): Single = GetContentById(listOf(contentId)).toRequest().map { it.single() } + fun get(contentId: ContentObjectId): Single = GetContentById(listOf(contentId)).toRequest().map { it.single() } /** * Get contents by ids. @@ -62,7 +64,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a content if found, empty list otherwise */ - fun getAll(contentId: List): Single> = GetContentById(contentId).toRequest() + fun getAll(contentId: List): Single> = GetContentById(contentId).toRequest() .onErrorResumeNext { if (it is ObjectNotFoundException) Single.just(emptyList()) else Single.error(it) } /** @@ -82,7 +84,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of publishing managers */ - fun listAllPublishersRelative(lowerBound: String, limit: Int = 100): Single> = ListPublishingManagers(lowerBound, limit).toRequest() + fun listAllPublishersRelative(lowerBound: String, limit: Int = 100): Single> = ListPublishingManagers(lowerBound, limit).toRequest() /** * Restores encryption key from key parts stored in buying object. @@ -92,7 +94,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return AES encryption key */ - fun restoreEncryptionKey(elGamalPrivate: PubKey, purchaseId: ChainObject): Single = RestoreEncryptionKey(elGamalPrivate, purchaseId).toRequest() + fun restoreEncryptionKey(elGamalPrivate: PubKey, purchaseId: PurchaseObjectId): Single = RestoreEncryptionKey(elGamalPrivate, purchaseId).toRequest() /** * Search for term in contents (author, title and description). @@ -113,9 +115,9 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { user: String = "", regionCode: String = Regions.ALL.code, type: String = contentType(ApplicationType.DECENT_CORE, CategoryType.NONE), - startId: ChainObject = ObjectType.NULL_OBJECT.genericId, + startId: ContentObjectId? = null, limit: Int = 100 - ): Single> = SearchContent(term, order, user, regionCode, type, startId, limit).toRequest() + ): Single> = SearchContent(term, order, user, regionCode, type, startId, limit).toRequest() /** * Create a purchase content operation. @@ -130,7 +132,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun createPurchaseOperation( credentials: Credentials, - contentId: ChainObject, + contentId: ContentObjectId, fee: Fee = Fee() ): Single = get(contentId).map { PurchaseContentOperation(credentials, it, fee) } @@ -168,7 +170,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun purchase( credentials: Credentials, - contentId: ChainObject, + contentId: ContentObjectId, fee: Fee = Fee() ): Single = createPurchaseOperation(credentials, contentId, fee).flatMap { api.broadcastApi.broadcastWithCallback(credentials.keyPair, it) @@ -209,7 +211,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun createTransfer( credentials: Credentials, - id: ChainObject, + id: ContentObjectId, amount: AssetAmount, memo: String? = null, fee: Fee = Fee() @@ -231,7 +233,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun transfer( credentials: Credentials, - id: ChainObject, + id: ContentObjectId, amount: AssetAmount, memo: String? = null, fee: Fee = Fee() @@ -248,7 +250,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * When set, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ @JvmOverloads - fun createRemoveContentOperation(content: ChainObject, fee: Fee = Fee()): Single = + fun createRemoveContentOperation(content: ContentObjectId, fee: Fee = Fee()): Single = get(content).map { RemoveContentOperation(it.author, it.uri, fee) } /** @@ -271,7 +273,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * When set, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ @JvmOverloads - fun remove(credentials: Credentials, content: ChainObject, fee: Fee = Fee()): Single = + fun remove(credentials: Credentials, content: ContentObjectId, fee: Fee = Fee()): Single = createRemoveContentOperation(content, fee).flatMap { api.broadcastApi.broadcastWithCallback(credentials.keyPair, it) } @@ -306,7 +308,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { */ @JvmOverloads fun createAddContentOperation( - author: ChainObject, + author: AccountObjectId, coAuthors: CoAuthors, uri: String, price: List, @@ -379,7 +381,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { */ @JvmOverloads fun createUpdateContentOperation( - content: ChainObject, + content: ContentObjectId, fee: Fee = Fee() ): Single = get(content).map { createUpdateContentOperation(it, fee) } @@ -425,7 +427,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun update( credentials: Credentials, - content: ChainObject, + content: ContentObjectId, synopsis: Synopsis? = null, price: List? = null, coAuthors: CoAuthors? = null, diff --git a/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt b/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt index 906227e3..8f093757 100644 --- a/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt @@ -3,10 +3,11 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.BalanceChange -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.OperationHistory +import ch.decent.sdk.model.OperationHistoryObjectId import ch.decent.sdk.net.model.request.GetAccountBalanceForTransaction import ch.decent.sdk.net.model.request.GetAccountHistory import ch.decent.sdk.net.model.request.GetRelativeAccountHistory @@ -24,8 +25,8 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return an balance operation change */ fun getOperation( - accountId: ChainObject, - operationId: ChainObject + accountId: AccountObjectId, + operationId: OperationHistoryObjectId ): Single = GetAccountBalanceForTransaction(accountId, operationId).toRequest() /** @@ -33,18 +34,19 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @param accountId object id of the account whose history should be queried, 1.2.* * @param limit number of entries, max 100 - * @param startId id of the history object to start from, use [ObjectType.OPERATION_HISTORY_OBJECT.genericId] to ignore - * @param stopId id of the history object to stop at, use [ObjectType.OPERATION_HISTORY_OBJECT.genericId] to ignore + * @param startId id of the history object to start from + * @param stopId id of the history object to stop at * * @return a list of operations performed by account, ordered from most recent to oldest */ @JvmOverloads fun listOperations( - accountId: ChainObject, - startId: ChainObject = ObjectType.OPERATION_HISTORY_OBJECT.genericId, - stopId: ChainObject = ObjectType.OPERATION_HISTORY_OBJECT.genericId, + accountId: AccountObjectId, + startId: OperationHistoryObjectId? = null, + stopId: OperationHistoryObjectId? = null, limit: Int = 100 - ): Single> = GetAccountHistory(accountId, stopId, limit, startId).toRequest() + ): Single> = + GetAccountHistory(accountId, stopId ?: OperationHistoryObjectId(), limit, startId ?: OperationHistoryObjectId()).toRequest() /** * Get account history of operations. @@ -56,7 +58,7 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of operations performed by account, ordered from most recent to oldest */ fun listOperationsRelative( - accountId: ChainObject, + accountId: AccountObjectId, start: Int = 0, limit: Int = 100 ): Single> = GetRelativeAccountHistory(accountId, 0, limit, start).toRequest() @@ -76,9 +78,9 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of balance changes */ fun findAllOperations( - accountId: ChainObject, - assets: List = emptyList(), - recipientAccount: ChainObject? = null, + accountId: AccountObjectId, + assets: List = emptyList(), + recipientAccount: AccountObjectId? = null, fromBlock: Long = 0, toBlock: Long = 0, startOffset: Long = 0, diff --git a/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt b/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt index 4258f787..e6b4070a 100644 --- a/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt @@ -5,15 +5,15 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo import ch.decent.sdk.model.Message import ch.decent.sdk.model.MessagePayload import ch.decent.sdk.model.MessagePayloadReceiver import ch.decent.sdk.model.MessageResponse -import ch.decent.sdk.model.operation.SendMessageOperation import ch.decent.sdk.model.TransactionConfirmation +import ch.decent.sdk.model.operation.SendMessageOperation import ch.decent.sdk.net.model.request.GetMessageObjects import io.reactivex.Single import io.reactivex.functions.BiFunction @@ -29,7 +29,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return list of message operation responses */ - fun getAllOperations(sender: ChainObject? = null, receiver: ChainObject? = null, maxCount: Int = 1000): Single> = + fun getAllOperations(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = 1000): Single> = GetMessageObjects(sender, receiver, maxCount).toRequest() /** @@ -41,7 +41,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return list of messages */ - fun getAll(sender: ChainObject? = null, receiver: ChainObject? = null, maxCount: Int = 1000): Single> = + fun getAll(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = 1000): Single> = GetMessageObjects(sender, receiver, maxCount).toRequest() .map { it.map { Message.create(it) }.flatten() } @@ -57,8 +57,8 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { */ fun getAllDecrypted( credentials: Credentials, - sender: ChainObject? = null, - receiver: ChainObject? = null, + sender: AccountObjectId? = null, + receiver: AccountObjectId? = null, maxCount: Int = 1000 ): Single> = require(sender == credentials.account || receiver == credentials.account) @@ -101,7 +101,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { @JvmOverloads fun createMessageOperation( credentials: Credentials, - messages: List>, + messages: List>, fee: Fee = Fee() ): Single = Single.zip( api.accountApi.get(credentials.account), @@ -126,7 +126,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { */ fun createMessageOperationUnencrypted( credentials: Credentials, - messages: List>, + messages: List>, fee: Fee = Fee() ): Single = Single.just( SendMessageOperation(api.core.gson.toJson(MessagePayload(credentials.account, messages)), credentials.account, fee = fee) @@ -142,7 +142,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { */ fun send( credentials: Credentials, - messages: List>, + messages: List>, fee: Fee = Fee() ): Single = createMessageOperation(credentials, messages, fee).flatMap { api.broadcastApi.broadcastWithCallback(credentials.keyPair, it) @@ -158,7 +158,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { */ fun sendUnencrypted( credentials: Credentials, - messages: List>, + messages: List>, fee: Fee = Fee() ): Single = createMessageOperationUnencrypted(credentials, messages, fee).flatMap { api.broadcastApi.broadcastWithCallback(credentials.keyPair, it) diff --git a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt b/library/src/main/java/ch/decent/sdk/api/MiningApi.kt index 42714a7c..53b691b0 100644 --- a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/MiningApi.kt @@ -5,10 +5,11 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Miner import ch.decent.sdk.model.MinerId +import ch.decent.sdk.model.MinerObjectId import ch.decent.sdk.model.MinerVotes import ch.decent.sdk.model.MinerVotingInfo import ch.decent.sdk.model.SearchMinerVotingOrder @@ -56,7 +57,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { * */ // todo model - fun getFeedsByMiner(account: ChainObject, count: Int = 100) = GetFeedsByMiner(account, count).toRequest() + fun getFeedsByMiner(account: AccountObjectId, count: Int = 100) = GetFeedsByMiner(account, count).toRequest() /** * Get the miner owned by a given account. @@ -65,7 +66,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return the miner object, or [ObjectNotFoundException] if the account does not have a miner */ - fun getMinerByAccount(account: ChainObject): Single = GetMinerByAccount(account).toRequest() + fun getMinerByAccount(account: AccountObjectId): Single = GetMinerByAccount(account).toRequest() /** * Get the total number of miners registered in DCore. @@ -81,7 +82,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of miners */ - fun getMiners(minerIds: List): Single> = GetMiners(minerIds).toRequest() + fun getMiners(minerIds: List): Single> = GetMiners(minerIds).toRequest() /** * Returns map of the first 1000 miners by their name to miner account @@ -134,7 +135,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { fun findAllVotingInfo( searchTerm: String, order: SearchMinerVotingOrder = SearchMinerVotingOrder.NAME_DESC, - id: ChainObject? = null, + id: MinerObjectId? = null, accountName: String? = null, onlyMyVotes: Boolean = false, limit: Int = 1000 @@ -151,8 +152,8 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a transaction confirmation */ fun createVoteOperation( - accountId: ChainObject, - minerIds: List, + accountId: AccountObjectId, + minerIds: List, fee: Fee = Fee() ): Single = getMiners(minerIds).flatMap { miners -> @@ -171,7 +172,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { */ fun vote( credentials: Credentials, - minerIds: List, + minerIds: List, fee: Fee = Fee() ): Single = createVoteOperation(credentials.account, minerIds, fee).flatMap { diff --git a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt b/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt index e1d4f814..300275b7 100644 --- a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt @@ -4,10 +4,11 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.Purchase +import ch.decent.sdk.model.PurchaseObjectId import ch.decent.sdk.model.SearchPurchasesOrder import ch.decent.sdk.model.TransactionConfirmation import ch.decent.sdk.model.operation.LeaveRatingAndCommentOperation @@ -29,7 +30,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of history purchases */ - fun getAllHistory(accountId: ChainObject): Single> = GetHistoryBuyingsByConsumer(accountId).toRequest() + fun getAllHistory(accountId: AccountObjectId): Single> = GetHistoryBuyingsByConsumer(accountId).toRequest() /** * Get a list of open purchases. @@ -54,7 +55,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of open purchases */ - fun getAllOpenByAccount(accountId: ChainObject): Single> = GetOpenBuyingsByConsumer(accountId).toRequest() + fun getAllOpenByAccount(accountId: AccountObjectId): Single> = GetOpenBuyingsByConsumer(accountId).toRequest() /** * Get consumer purchase by content uri. @@ -65,7 +66,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return an account if found, [ch.decent.sdk.exception.ObjectNotFoundException] otherwise */ fun get( - consumer: ChainObject, + consumer: AccountObjectId, uri: String ): Single = GetBuyingByUri(consumer, uri).toRequest() @@ -82,9 +83,9 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { */ @JvmOverloads fun findAll( - consumer: ChainObject, + consumer: AccountObjectId, term: String = "", - from: ChainObject = ObjectType.NULL_OBJECT.genericId, + from: PurchaseObjectId? = null, order: SearchPurchasesOrder = SearchPurchasesOrder.PURCHASED_DESC, limit: Int = 100 ): Single> = SearchBuyings(consumer, order, from, term, limit).toRequest() @@ -103,7 +104,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { uri: String, user: String? = null, count: Int = 100, - startId: ChainObject = ObjectType.NULL_OBJECT.genericId + startId: PurchaseObjectId? = null ): Single> = SearchFeedback(user, uri, startId, count).toRequest() /** @@ -120,7 +121,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { */ fun createRateAndCommentOperation( uri: String, - consumer: ChainObject, + consumer: AccountObjectId, rating: Byte, comment: String, fee: Fee = Fee() diff --git a/library/src/main/java/ch/decent/sdk/api/SeederApi.kt b/library/src/main/java/ch/decent/sdk/api/SeederApi.kt index 676e7e83..857082de 100644 --- a/library/src/main/java/ch/decent/sdk/api/SeederApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/SeederApi.kt @@ -4,7 +4,7 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.exception.ObjectNotFoundException -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Regions import ch.decent.sdk.model.Seeder import ch.decent.sdk.net.model.request.GetSeeder @@ -22,7 +22,7 @@ class SeederApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a seeder object or [ObjectNotFoundException] if not found */ - fun get(accountId: ChainObject): Single = GetSeeder(accountId).toRequest() + fun get(accountId: AccountObjectId): Single = GetSeeder(accountId).toRequest() /** * Get a list of seeders by price, in increasing order. diff --git a/library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt b/library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt index 47822c7e..636cc938 100644 --- a/library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt @@ -4,8 +4,9 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi import ch.decent.sdk.exception.ObjectNotFoundException -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Subscription +import ch.decent.sdk.model.SubscriptionObjectId import ch.decent.sdk.net.model.request.GetSubscription import ch.decent.sdk.net.model.request.ListActiveSubscriptionsByAuthor import ch.decent.sdk.net.model.request.ListActiveSubscriptionsByConsumer @@ -23,7 +24,7 @@ class SubscriptionApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return the subscription object corresponding to the provided ID, [ObjectNotFoundException] otherwise */ // todo subscriptions: wait for subscribe operation to test - fun get(id: ChainObject): Single = GetSubscription(id).toRequest() + fun get(id: SubscriptionObjectId): Single = GetSubscription(id).toRequest() /** * Get a list of active (not expired) subscriptions by account (consumer). @@ -33,7 +34,7 @@ class SubscriptionApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of active subscription objects */ - fun getAllActiveByConsumer(consumer: ChainObject, count: Int): Single> = + fun getAllActiveByConsumer(consumer: AccountObjectId, count: Int): Single> = ListActiveSubscriptionsByConsumer(consumer, count).toRequest() /** @@ -44,7 +45,7 @@ class SubscriptionApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of active subscription objects */ - fun getAllActiveByAuthor(author: ChainObject, count: Int): Single> = + fun getAllActiveByAuthor(author: AccountObjectId, count: Int): Single> = ListActiveSubscriptionsByAuthor(author, count).toRequest() /** @@ -55,7 +56,7 @@ class SubscriptionApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of subscription objects */ - fun getAllByConsumer(consumer: ChainObject, count: Int): Single> = + fun getAllByConsumer(consumer: AccountObjectId, count: Int): Single> = ListSubscriptionsByConsumer(consumer, count).toRequest() /** @@ -66,6 +67,6 @@ class SubscriptionApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return a list of subscription objects */ - fun getAllByAuthor(author: ChainObject, count: Int): Single> = + fun getAllByAuthor(author: AccountObjectId, count: Int): Single> = ListSubscriptionsByAuthor(author, count).toRequest() } diff --git a/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt b/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt index b3b1911d..2b74713e 100644 --- a/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt @@ -3,11 +3,11 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi -import ch.decent.sdk.model.operation.BaseOperation -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.ProcessedTransaction import ch.decent.sdk.model.Transaction import ch.decent.sdk.model.TransactionConfirmation +import ch.decent.sdk.model.operation.BaseOperation import ch.decent.sdk.net.model.request.GetProposedTransactions import ch.decent.sdk.net.model.request.GetRecentTransactionById import ch.decent.sdk.net.model.request.GetTransaction @@ -46,7 +46,7 @@ class TransactionApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a set of proposed transactions */ // todo model - fun getAllProposed(accountId: ChainObject) = GetProposedTransactions(accountId).toRequest() + fun getAllProposed(accountId: AccountObjectId) = GetProposedTransactions(accountId).toRequest() /** * If the transaction has not expired, this method will return the transaction for the given ID or it will return [ch.decent.sdk.exception.ObjectNotFoundException]. diff --git a/library/src/main/java/ch/decent/sdk/api/ValidationApi.kt b/library/src/main/java/ch/decent/sdk/api/ValidationApi.kt index eebc9ec8..4f792b82 100644 --- a/library/src/main/java/ch/decent/sdk/api/ValidationApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/ValidationApi.kt @@ -7,12 +7,12 @@ import ch.decent.sdk.DCoreConstants import ch.decent.sdk.crypto.Address import ch.decent.sdk.exception.DCoreException import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.operation.OperationType +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.ProcessedTransaction import ch.decent.sdk.model.Transaction import ch.decent.sdk.model.operation.BaseOperation import ch.decent.sdk.model.operation.EmptyOperation +import ch.decent.sdk.model.operation.OperationType import ch.decent.sdk.net.model.request.GetPotentialSignatures import ch.decent.sdk.net.model.request.GetRequiredFees import ch.decent.sdk.net.model.request.GetRequiredSignatures @@ -81,7 +81,8 @@ class ValidationApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of fee asset amounts */ @JvmOverloads - fun getFees(op: List, assetId: ChainObject = DCoreConstants.DCT.id): Single> = GetRequiredFees(op, assetId).toRequest() + fun getFees(op: List, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID): Single> = + GetRequiredFees(op, assetId).toRequest() /** * Returns fee for operation. @@ -92,7 +93,8 @@ class ValidationApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a fee asset amount */ @JvmOverloads - fun getFee(op: BaseOperation, assetId: ChainObject = DCoreConstants.DCT.id): Single = getFees(listOf(op), assetId).map { it.single() } + fun getFee(op: BaseOperation, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID): Single = + getFees(listOf(op), assetId).map { it.single() } /** * Returns fees for operation type, not valid for operation per size fees: @@ -110,7 +112,7 @@ class ValidationApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a fee asset amount */ @JvmOverloads - fun getFeesForType(types: List, assetId: ChainObject = DCoreConstants.DCT.id): Single> = + fun getFeesForType(types: List, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID): Single> = require(listOf( OperationType.ASSET_CREATE_OPERATION, OperationType.ASSET_ISSUE_OPERATION, @@ -139,6 +141,6 @@ class ValidationApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a fee asset amount */ @JvmOverloads - fun getFeeForType(type: OperationType, assetId: ChainObject = DCoreConstants.DCT.id): Single = + fun getFeeForType(type: OperationType, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID): Single = getFeesForType(listOf(type), assetId).map { it.single() } } diff --git a/library/src/main/java/ch/decent/sdk/crypto/Credentials.kt b/library/src/main/java/ch/decent/sdk/crypto/Credentials.kt index 154b61a6..642f32eb 100644 --- a/library/src/main/java/ch/decent/sdk/crypto/Credentials.kt +++ b/library/src/main/java/ch/decent/sdk/crypto/Credentials.kt @@ -1,10 +1,10 @@ package ch.decent.sdk.crypto -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId data class Credentials( - val account: ChainObject, + val account: AccountObjectId, val keyPair: ECKeyPair ) { - constructor(account: ChainObject, encodedPrivate: String) : this(account, ECKeyPair.fromBase58(encodedPrivate)) + constructor(account: AccountObjectId, encodedPrivate: String) : this(account, ECKeyPair.fromBase58(encodedPrivate)) } diff --git a/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt b/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt index c8385a5a..e64d30b0 100644 --- a/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt +++ b/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt @@ -2,7 +2,7 @@ package ch.decent.sdk.crypto import ch.decent.sdk.DCoreSdk import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.CipherKeyPairAdapter import ch.decent.sdk.model.ExtraKeysAdapter import ch.decent.sdk.model.PubKey @@ -124,7 +124,7 @@ object Wallet { } data class ExtraKeys( - val account: ChainObject, + val account: AccountObjectId, val keys: List
) diff --git a/library/src/main/java/ch/decent/sdk/crypto/WalletFile.kt b/library/src/main/java/ch/decent/sdk/crypto/WalletFile.kt index 3d790d71..ae656905 100644 --- a/library/src/main/java/ch/decent/sdk/crypto/WalletFile.kt +++ b/library/src/main/java/ch/decent/sdk/crypto/WalletFile.kt @@ -1,11 +1,11 @@ package ch.decent.sdk.crypto -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import java.util.* data class WalletFile( val version: Int, - val accountId: ChainObject, + val accountId: AccountObjectId, val cipherText: String, val salt: String, val iv: String, diff --git a/library/src/main/java/ch/decent/sdk/model/Account.kt b/library/src/main/java/ch/decent/sdk/model/Account.kt index e7bebde4..4e7881a0 100644 --- a/library/src/main/java/ch/decent/sdk/model/Account.kt +++ b/library/src/main/java/ch/decent/sdk/model/Account.kt @@ -5,14 +5,14 @@ import com.google.gson.annotations.SerializedName import java.util.regex.Pattern data class Account( - @SerializedName("id") val id: ChainObject, - @SerializedName("registrar") val registrar: ChainObject, + @SerializedName("id") val id: AccountObjectId, + @SerializedName("registrar") val registrar: AccountObjectId, @SerializedName("name") val name: String, @SerializedName("owner") val owner: Authority, @SerializedName("active") val active: Authority, @SerializedName("options") val options: AccountOptions, @SerializedName("rights_to_publish") val rightsToPublish: Publishing, - @SerializedName("statistics") val statistics: ChainObject, + @SerializedName("statistics") val statistics: AccountStatsObjectId, @SerializedName("top_n_control_flags") @UInt8 val topControlFlags: Short ) { diff --git a/library/src/main/java/ch/decent/sdk/model/AccountBalance.kt b/library/src/main/java/ch/decent/sdk/model/AccountBalance.kt index 32f12163..7864a4b5 100644 --- a/library/src/main/java/ch/decent/sdk/model/AccountBalance.kt +++ b/library/src/main/java/ch/decent/sdk/model/AccountBalance.kt @@ -4,8 +4,8 @@ import ch.decent.sdk.model.types.Int64 import com.google.gson.annotations.SerializedName data class AccountBalance( - @SerializedName("id") val id: ChainObject, - @SerializedName("owner") val owner: ChainObject, - @SerializedName("asset_type") val assetType: ChainObject, + @SerializedName("id") val id: AccountBalanceObjectId, + @SerializedName("owner") val owner: AccountObjectId, + @SerializedName("asset_type") val assetType: AssetObjectId, @SerializedName("balance") @Int64 val balance: Long ) diff --git a/library/src/main/java/ch/decent/sdk/model/AccountOptions.kt b/library/src/main/java/ch/decent/sdk/model/AccountOptions.kt index 6ee6e33d..5949171f 100644 --- a/library/src/main/java/ch/decent/sdk/model/AccountOptions.kt +++ b/library/src/main/java/ch/decent/sdk/model/AccountOptions.kt @@ -1,5 +1,6 @@ package ch.decent.sdk.model +import ch.decent.sdk.DCoreConstants import ch.decent.sdk.crypto.Address import ch.decent.sdk.model.types.UInt16 import ch.decent.sdk.model.types.UInt32 @@ -7,7 +8,7 @@ import com.google.gson.annotations.SerializedName data class AccountOptions( @SerializedName("memo_key") val memoKey: Address, - @SerializedName("voting_account") val votingAccount: ChainObject, + @SerializedName("voting_account") val votingAccount: AccountObjectId, @SerializedName("num_miner") @UInt16 val numMiner: Int, @SerializedName("votes") val votes: Set, @SerializedName("extensions") val extensions: List, @@ -18,7 +19,7 @@ data class AccountOptions( constructor(public: Address) : this( public, - ChainObject.parse("1.2.3"), + DCoreConstants.PROXY_TO_SELF, 0, emptySet(), emptyList(), diff --git a/library/src/main/java/ch/decent/sdk/model/AccountStatistics.kt b/library/src/main/java/ch/decent/sdk/model/AccountStatistics.kt index 40b30606..8a95d346 100644 --- a/library/src/main/java/ch/decent/sdk/model/AccountStatistics.kt +++ b/library/src/main/java/ch/decent/sdk/model/AccountStatistics.kt @@ -4,9 +4,9 @@ import ch.decent.sdk.model.types.Int64 import com.google.gson.annotations.SerializedName data class AccountStatistics( - @SerializedName("id") val id: ChainObject, - @SerializedName("owner") val owner: ChainObject, - @SerializedName("most_recent_op") val mostRecentOp: ChainObject, + @SerializedName("id") val id: AccountStatsObjectId, + @SerializedName("owner") val owner: AccountObjectId, + @SerializedName("most_recent_op") val mostRecentOp: AccountTransactionObjectId, @SerializedName("total_ops") val totalOps: Long, @SerializedName("total_core_in_orders") @Int64 val totalCoreInOrders: Long, @SerializedName("pending_fees") @Int64 val pendingFees: Long, diff --git a/library/src/main/java/ch/decent/sdk/model/Asset.kt b/library/src/main/java/ch/decent/sdk/model/Asset.kt index 1f79d57a..645ae938 100644 --- a/library/src/main/java/ch/decent/sdk/model/Asset.kt +++ b/library/src/main/java/ch/decent/sdk/model/Asset.kt @@ -7,13 +7,13 @@ import java.math.BigDecimal import java.math.RoundingMode data class Asset( - @SerializedName("id") override val id: ChainObject, + @SerializedName("id") override val id: AssetObjectId, @SerializedName("symbol") override val symbol: String, @SerializedName("precision") @UInt8 override val precision: Byte, - @SerializedName("issuer") val issuer: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, @SerializedName("description") val description: String, @SerializedName("options") val options: AssetOptions, - @SerializedName("dynamic_asset_data_id") val dataId: ChainObject, + @SerializedName("dynamic_asset_data_id") val dataId: AssetDataObjectId, @SerializedName("monitored_asset_opts") val monitoredAssetOpts: MonitoredAssetOptions? = null ) : AssetFormatter { @@ -22,10 +22,6 @@ data class Asset( @JvmStatic fun isValidSymbol(symbol: String) = regex.matches(symbol) } - init { - check(id.objectType == ObjectType.ASSET_OBJECT) - } - /** * Converts DCT [amount] according conversion rate. * Throws an [IllegalArgumentException] if the quote or base [amount] is not greater then zero. @@ -48,7 +44,7 @@ data class Asset( * * @return [AssetAmount] for converted amount */ - private fun convert(amount: Long, toAssetId: ChainObject, roundingMode: RoundingMode): AssetAmount { + private fun convert(amount: Long, toAssetId: AssetObjectId, roundingMode: RoundingMode): AssetAmount { val quoteAmount: BigDecimal = options.exchangeRate.quote.amount.toBigDecimal() val baseAmount: BigDecimal = options.exchangeRate.base.amount.toBigDecimal() require(quoteAmount > BigDecimal.ZERO) { "Quote amount ($quoteAmount) must be greater then zero" } diff --git a/library/src/main/java/ch/decent/sdk/model/AssetAmount.kt b/library/src/main/java/ch/decent/sdk/model/AssetAmount.kt index 6b4237f0..54b5b2ec 100644 --- a/library/src/main/java/ch/decent/sdk/model/AssetAmount.kt +++ b/library/src/main/java/ch/decent/sdk/model/AssetAmount.kt @@ -6,13 +6,10 @@ import com.google.gson.annotations.SerializedName data class AssetAmount @JvmOverloads constructor( @SerializedName("amount") @Int64 val amount: Long, - @SerializedName("asset_id") val assetId: ChainObject = DCoreConstants.DCT_ASSET_ID + @SerializedName("asset_id") val assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID ) { - constructor(amount: Long, asset: String) : this(amount, asset.toChainObject()) - init { require(amount >= 0) { "amount must be greater or equal to 0" } - require(assetId.objectType == ObjectType.ASSET_OBJECT) { "object id is not an asset" } } } diff --git a/library/src/main/java/ch/decent/sdk/model/AssetData.kt b/library/src/main/java/ch/decent/sdk/model/AssetData.kt index b284440d..c088ced5 100644 --- a/library/src/main/java/ch/decent/sdk/model/AssetData.kt +++ b/library/src/main/java/ch/decent/sdk/model/AssetData.kt @@ -4,7 +4,7 @@ import com.google.gson.annotations.SerializedName import java.math.BigInteger data class AssetData( - @SerializedName("id") val id: ChainObject = ObjectType.ASSET_OBJECT.genericId, + @SerializedName("id") val id: AssetDataObjectId, @SerializedName("current_supply") val currentSupply: BigInteger, @SerializedName("asset_pool") val assetPool: BigInteger, @SerializedName("core_pool") val corePool: BigInteger diff --git a/library/src/main/java/ch/decent/sdk/model/AssetFormatter.kt b/library/src/main/java/ch/decent/sdk/model/AssetFormatter.kt index 52819c8d..938a71dc 100644 --- a/library/src/main/java/ch/decent/sdk/model/AssetFormatter.kt +++ b/library/src/main/java/ch/decent/sdk/model/AssetFormatter.kt @@ -6,7 +6,7 @@ import java.text.NumberFormat interface AssetFormatter { - val id: ChainObject + val id: AssetObjectId val symbol: String val precision: Byte diff --git a/library/src/main/java/ch/decent/sdk/model/BlockHeader.kt b/library/src/main/java/ch/decent/sdk/model/BlockHeader.kt index b3b7fc94..885590ec 100644 --- a/library/src/main/java/ch/decent/sdk/model/BlockHeader.kt +++ b/library/src/main/java/ch/decent/sdk/model/BlockHeader.kt @@ -6,6 +6,6 @@ import org.threeten.bp.LocalDateTime data class BlockHeader( @SerializedName("previous") val previous: String, @SerializedName("timestamp") val timestamp: LocalDateTime, - @SerializedName("miner") val miner: ChainObject, + @SerializedName("miner") val miner: MinerObjectId, @SerializedName("transaction_merkle_root") val transactionMerkleRoot: String ) diff --git a/library/src/main/java/ch/decent/sdk/model/ChainObject.kt b/library/src/main/java/ch/decent/sdk/model/ChainObject.kt deleted file mode 100644 index 14f76780..00000000 --- a/library/src/main/java/ch/decent/sdk/model/ChainObject.kt +++ /dev/null @@ -1,61 +0,0 @@ -package ch.decent.sdk.model - -import ch.decent.sdk.model.types.UInt64 -import java.math.BigInteger - -@Suppress("MagicNumber") -class ChainObject { - - val objectType: ObjectType - @UInt64 val instance: BigInteger - - private constructor(id: String) { - val g = regex.matchEntire(id)!!.groupValues - objectType = ObjectType.fromSpaceType(g[1].toInt(), g[2].toInt()) - instance = g[3].toBigInteger() - } - - internal constructor(objectType: ObjectType) { - this.objectType = objectType - this.instance = BigInteger.ZERO - } - - internal val fullInstance: Long - get() = (objectType.space.toLong().shl(56) or objectType.type.toLong().shl(48) or instance.toLong()) - - /** - * - * @return: A String containing the full object apiId in the form {space}.{type}.{instance} - */ - val objectId: String - get() = String.format("%d.%d.%d", objectType.space, objectType.type, instance) - - override fun toString(): String = objectId - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as ChainObject - - if (objectType != other.objectType) return false - if (instance != other.instance) return false - - return true - } - - override fun hashCode(): Int { - var result = objectType.hashCode() - result = 31 * result + instance.hashCode() - return result - } - - companion object { - private val regex = Regex("""(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?""") - - @JvmStatic fun parse(id: String) = if (isValid(id)) ChainObject(id) else throw IllegalArgumentException() - @JvmStatic fun isValid(id: String): Boolean = regex.matchEntire(id.trim()) != null - } -} - -fun String.toChainObject() = ChainObject.parse(this) diff --git a/library/src/main/java/ch/decent/sdk/model/ChainProperties.kt b/library/src/main/java/ch/decent/sdk/model/ChainProperties.kt index 31340d1b..9220d016 100644 --- a/library/src/main/java/ch/decent/sdk/model/ChainProperties.kt +++ b/library/src/main/java/ch/decent/sdk/model/ChainProperties.kt @@ -3,7 +3,7 @@ package ch.decent.sdk.model import com.google.gson.annotations.SerializedName data class ChainProperties( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: ChainPropertyObjectId, @SerializedName("chain_id") val chainId: String, @SerializedName("immutable_parameters") val parameters: ChainParameters ) diff --git a/library/src/main/java/ch/decent/sdk/model/CoAuthors.kt b/library/src/main/java/ch/decent/sdk/model/CoAuthors.kt index ccb1a85a..240b7224 100644 --- a/library/src/main/java/ch/decent/sdk/model/CoAuthors.kt +++ b/library/src/main/java/ch/decent/sdk/model/CoAuthors.kt @@ -3,4 +3,4 @@ package ch.decent.sdk.model import ch.decent.sdk.model.types.UInt32 //sums to 10000 so Int is ok -data class CoAuthors(@UInt32 val authors: Map) +data class CoAuthors(@UInt32 val authors: Map) diff --git a/library/src/main/java/ch/decent/sdk/model/Config.kt b/library/src/main/java/ch/decent/sdk/model/Config.kt index 3758cf74..a4d449ba 100644 --- a/library/src/main/java/ch/decent/sdk/model/Config.kt +++ b/library/src/main/java/ch/decent/sdk/model/Config.kt @@ -72,7 +72,7 @@ data class Config( @SerializedName("GRAPHENE_DEFAULT_MINER_PAY_PER_BLOCK") val grapheneDefaultMinerPayPerBlock: BigInteger, @SerializedName("GRAPHENE_DEFAULT_MINER_PAY_VESTING_SECONDS") val grapheneDefaultMinerPayVestingSeconds: Int, @SerializedName("GRAPHENE_MAX_INTEREST_APR") val grapheneMaxInterestApr: Int, - @SerializedName("GRAPHENE_MINER_ACCOUNT") val grapheneMinerAccount: ChainObject, - @SerializedName("GRAPHENE_NULL_ACCOUNT") val grapheneNullAccount: ChainObject, - @SerializedName("GRAPHENE_TEMP_ACCOUNT") val grapheneTempAccount: ChainObject + @SerializedName("GRAPHENE_MINER_ACCOUNT") val grapheneMinerAccount: AccountObjectId, + @SerializedName("GRAPHENE_NULL_ACCOUNT") val grapheneNullAccount: AccountObjectId, + @SerializedName("GRAPHENE_TEMP_ACCOUNT") val grapheneTempAccount: AccountObjectId ) diff --git a/library/src/main/java/ch/decent/sdk/model/Content.kt b/library/src/main/java/ch/decent/sdk/model/Content.kt index 9651860e..d7e25c4c 100644 --- a/library/src/main/java/ch/decent/sdk/model/Content.kt +++ b/library/src/main/java/ch/decent/sdk/model/Content.kt @@ -8,8 +8,8 @@ import org.threeten.bp.LocalDateTime import java.math.BigInteger data class Content( - @SerializedName("id") val id: ChainObject, - @SerializedName("author") val author: ChainObject, + @SerializedName("id") val id: ContentObjectId, + @SerializedName("author") val author: AccountObjectId, @SerializedName("co_authors") val coAuthors: CoAuthors, @SerializedName("expiration") val expiration: LocalDateTime, @SerializedName("created") val created: LocalDateTime, @@ -18,9 +18,9 @@ data class Content( @SerializedName("size") @UInt64 val size: BigInteger, @SerializedName("quorum") @UInt32 val quorum: Int, @SerializedName("URI") val uri: String, - @SerializedName("key_parts") val keyParts: Map, - @SerializedName("last_proof") val lastProof: Map, - @SerializedName("seeder_price") @Int64 val seederPrice: Map, + @SerializedName("key_parts") val keyParts: Map, + @SerializedName("last_proof") val lastProof: Map, + @SerializedName("seeder_price") @Int64 val seederPrice: Map, @SerializedName("is_blocked") val isBlocked: String, @SerializedName("_hash") val hash: String, @SerializedName("AVG_rating") @UInt64 val rating: BigInteger, diff --git a/library/src/main/java/ch/decent/sdk/model/ContentSummary.kt b/library/src/main/java/ch/decent/sdk/model/ContentSummary.kt new file mode 100644 index 00000000..3068b0f9 --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/model/ContentSummary.kt @@ -0,0 +1,23 @@ +package ch.decent.sdk.model + +import ch.decent.sdk.model.types.UInt32 +import ch.decent.sdk.model.types.UInt64 +import com.google.gson.annotations.SerializedName +import org.threeten.bp.LocalDateTime +import java.math.BigInteger + +data class ContentSummary( + @SerializedName("id") val id: ContentObjectId, + @SerializedName("author") val author: String, + @SerializedName("price") val price: AssetAmount, + @SerializedName("synopsis") val synopsis: String, + @SerializedName("_hash") val hash: String, + @SerializedName("status") val status: String, + @SerializedName("URI") val uri: String, + @SerializedName("AVG_rating") @UInt32 val rating: Long, + @SerializedName("size") @UInt64 val size: BigInteger, + @SerializedName("expiration") val expiration: LocalDateTime, + @SerializedName("created") val created: LocalDateTime, + @SerializedName("co_authors") val coAuthors: CoAuthors, + @SerializedName("times_bought") @UInt32 val timesBought: Long +) diff --git a/library/src/main/java/ch/decent/sdk/model/DynamicGlobalProps.kt b/library/src/main/java/ch/decent/sdk/model/DynamicGlobalProps.kt index fc9a024c..76085c70 100644 --- a/library/src/main/java/ch/decent/sdk/model/DynamicGlobalProps.kt +++ b/library/src/main/java/ch/decent/sdk/model/DynamicGlobalProps.kt @@ -9,11 +9,11 @@ import org.threeten.bp.LocalDateTime import java.math.BigInteger data class DynamicGlobalProps( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: DynamicGlobalPropertyObjectId, @SerializedName("head_block_number") @UInt32 val headBlockNumber: Long, @SerializedName("head_block_id") val headBlockId: String, @SerializedName("time") val time: LocalDateTime, - @SerializedName("current_miner") val currentMiner: ChainObject, + @SerializedName("current_miner") val currentMiner: MinerObjectId, @SerializedName("next_maintenance_time") val nextMaintenanceTime: LocalDateTime, @SerializedName("last_budget_time") val lastBudgetTime: LocalDateTime, @SerializedName("miner_budget_from_fees") @Int64 val minerBudgetFromFees: Long, diff --git a/library/src/main/java/ch/decent/sdk/model/ExchangeRate.kt b/library/src/main/java/ch/decent/sdk/model/ExchangeRate.kt index 0f48ed76..f634ab0e 100644 --- a/library/src/main/java/ch/decent/sdk/model/ExchangeRate.kt +++ b/library/src/main/java/ch/decent/sdk/model/ExchangeRate.kt @@ -14,7 +14,7 @@ data class ExchangeRate( * @param base base value in DCT * @param quote quote value in UIA */ - @JvmStatic fun forCreateOp(base: Long, quote: Long): ExchangeRate = ExchangeRate(AssetAmount(base), AssetAmount(quote, "1.3.1".toChainObject())) + @JvmStatic fun forCreateOp(base: Long, quote: Long): ExchangeRate = ExchangeRate(AssetAmount(base), AssetAmount(quote, AssetObjectId())) } } diff --git a/library/src/main/java/ch/decent/sdk/model/Fee.kt b/library/src/main/java/ch/decent/sdk/model/Fee.kt index 4fa09eb2..25888255 100644 --- a/library/src/main/java/ch/decent/sdk/model/Fee.kt +++ b/library/src/main/java/ch/decent/sdk/model/Fee.kt @@ -10,13 +10,12 @@ import ch.decent.sdk.model.types.Int64 * @param amount fee amount, if null the fee amount will be fetched from DCore */ data class Fee @JvmOverloads constructor( - val assetId: ChainObject = DCoreConstants.DCT_ASSET_ID, + val assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID, @Int64 val amount: Long? = null ) { init { require((amount ?: 0) >= 0) { "amount must be greater or equal to 0" } - require(assetId.objectType == ObjectType.ASSET_OBJECT) { "object id is not an asset" } } } diff --git a/library/src/main/java/ch/decent/sdk/model/FeeSchedule.kt b/library/src/main/java/ch/decent/sdk/model/FeeSchedule.kt index 6715efdd..c8aa4fa4 100644 --- a/library/src/main/java/ch/decent/sdk/model/FeeSchedule.kt +++ b/library/src/main/java/ch/decent/sdk/model/FeeSchedule.kt @@ -1,10 +1,12 @@ package ch.decent.sdk.model -import ch.decent.sdk.model.operation.OperationType import ch.decent.sdk.model.types.UInt32 import com.google.gson.annotations.SerializedName data class FeeSchedule( - @SerializedName("parameters") val parameters: Map, + /** + * operation types int keys + */ + @SerializedName("parameters") val parameters: Map, @SerializedName("scale") @UInt32 val scale: Long ) diff --git a/library/src/main/java/ch/decent/sdk/model/GlobalProperties.kt b/library/src/main/java/ch/decent/sdk/model/GlobalProperties.kt index 76c15d6f..452db00a 100644 --- a/library/src/main/java/ch/decent/sdk/model/GlobalProperties.kt +++ b/library/src/main/java/ch/decent/sdk/model/GlobalProperties.kt @@ -4,8 +4,8 @@ import ch.decent.sdk.model.types.UInt32 import com.google.gson.annotations.SerializedName data class GlobalProperties( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: GlobalPropertyObjectId, @SerializedName("parameters") val parameters: GlobalParameters, @SerializedName("next_available_vote_id") @UInt32 val nextAvailableVoteId: Long, - @SerializedName("active_miners") val activeMiners: List + @SerializedName("active_miners") val activeMiners: List ) diff --git a/library/src/main/java/ch/decent/sdk/model/MessageResponse.kt b/library/src/main/java/ch/decent/sdk/model/MessageResponse.kt index 33717270..8bc03058 100644 --- a/library/src/main/java/ch/decent/sdk/model/MessageResponse.kt +++ b/library/src/main/java/ch/decent/sdk/model/MessageResponse.kt @@ -14,11 +14,11 @@ import java.math.BigInteger import java.nio.charset.Charset data class Message( - val operationId: ChainObject, + val operationId: MessagingObjectId, val timestamp: LocalDateTime, - val sender: ChainObject, + val sender: AccountObjectId, val senderAddress: Address?, - val receiver: ChainObject, + val receiver: AccountObjectId, val receiverAddress: Address?, val message: String, val nonce: BigInteger = BigInteger.ZERO, @@ -60,23 +60,23 @@ data class Message( } data class MessageResponse( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: MessagingObjectId, @SerializedName("created") val created: LocalDateTime, - @SerializedName("sender") val sender: ChainObject, + @SerializedName("sender") val sender: AccountObjectId, @SerializedName("sender_pubkey") val senderAddress: Address?, @SerializedName("receivers_data") val receiversData: List, @SerializedName("text") val text: String ) data class MessageReceiver( - @SerializedName("receiver") val receiver: ChainObject, + @SerializedName("receiver") val receiver: AccountObjectId, @SerializedName("receiver_pubkey") val receiverAddress: Address?, @SerializedName("nonce") @UInt64 val nonce: BigInteger, @SerializedName("data") val data: String ) data class MessagePayload( - @SerializedName("from") val from: ChainObject, + @SerializedName("from") val from: AccountObjectId, @SerializedName("receivers_data") val receiversData: List, @SerializedName("pub_from") val fromAddress: Address? = null ) { @@ -85,13 +85,13 @@ data class MessagePayload( * unencrypted message payload constructor */ constructor( - from: ChainObject, - messages: List> + from: AccountObjectId, + messages: List> ) : this(from, messages.map { MessagePayloadReceiver(it.first, Memo(it.second).message) }) } data class MessagePayloadReceiver( - @SerializedName("to") val to: ChainObject, + @SerializedName("to") val to: AccountObjectId, @SerializedName("data") val data: String, @SerializedName("pub_to") val toAddress: Address? = null, @SerializedName("nonce") @UInt64 val nonce: BigInteger? = null diff --git a/library/src/main/java/ch/decent/sdk/model/Miner.kt b/library/src/main/java/ch/decent/sdk/model/Miner.kt index 2be80d3a..e1369d3a 100644 --- a/library/src/main/java/ch/decent/sdk/model/Miner.kt +++ b/library/src/main/java/ch/decent/sdk/model/Miner.kt @@ -8,11 +8,11 @@ import com.google.gson.annotations.SerializedName import java.math.BigInteger data class Miner( - @SerializedName("id") val id: ChainObject, - @SerializedName("miner_account") val minerAccount: ChainObject, + @SerializedName("id") val id: MinerObjectId, + @SerializedName("miner_account") val minerAccount: AccountObjectId, @SerializedName("last_aslot") @UInt64 val lastAslot: BigInteger, @SerializedName("signing_key") val signingKey: Address, - @SerializedName("pay_vb") val payVb: ChainObject, + @SerializedName("pay_vb") val payVb: VestingBalanceObjectId?, @SerializedName("vote_id") val voteId: String, @SerializedName("total_votes") @UInt64 val totalVotes: BigInteger, @SerializedName("url") val url: String, diff --git a/library/src/main/java/ch/decent/sdk/model/MinerId.kt b/library/src/main/java/ch/decent/sdk/model/MinerId.kt index 63151b8d..a2f7e63a 100644 --- a/library/src/main/java/ch/decent/sdk/model/MinerId.kt +++ b/library/src/main/java/ch/decent/sdk/model/MinerId.kt @@ -2,5 +2,5 @@ package ch.decent.sdk.model data class MinerId( val name: String, - val id: ChainObject + val id: MinerObjectId ) diff --git a/library/src/main/java/ch/decent/sdk/model/MinerVotingInfo.kt b/library/src/main/java/ch/decent/sdk/model/MinerVotingInfo.kt index eeccac61..528f0b19 100644 --- a/library/src/main/java/ch/decent/sdk/model/MinerVotingInfo.kt +++ b/library/src/main/java/ch/decent/sdk/model/MinerVotingInfo.kt @@ -5,7 +5,7 @@ import com.google.gson.annotations.SerializedName import java.math.BigInteger data class MinerVotingInfo( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: MinerObjectId, @SerializedName("name") val name: String, @SerializedName("url") val url: String, @SerializedName("total_votes") @UInt64 val votes: BigInteger, diff --git a/library/src/main/java/ch/decent/sdk/model/ObjectId.kt b/library/src/main/java/ch/decent/sdk/model/ObjectId.kt new file mode 100644 index 00000000..a38edcfe --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/model/ObjectId.kt @@ -0,0 +1,135 @@ +package ch.decent.sdk.model + +import ch.decent.sdk.DCoreConstants + +open class ObjectId( + val space: Int, + val type: Int, + val instance: Long +) { + + init { + check(this.instance <= DCoreConstants.MAX_INSTANCE_ID) + } + + internal constructor(type: ObjectType, instance: Long) : this(type.space, type.type, instance) + + @Suppress("MagicNumber") + internal val fullInstance: Long + get() = (objectType.space.toLong().shl(56) or objectType.type.toLong().shl(48) or instance) + + val objectType: ObjectType + get() = ObjectType.values().find { it.space == space && it.type == type } ?: ObjectType.UNKNOWN_OBJECT + + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as ObjectId + + if (space != other.space) return false + if (type != other.type) return false + if (instance != other.instance) return false + + return true + } + + override fun hashCode(): Int { + var result = space + result = 31 * result + type + result = 31 * result + instance.hashCode() + return result + } + + override fun toString(): String { + return "$space.$type.$instance" + } + + companion object { + private val klasses = mapOf( + ObjectType.BASE_OBJECT to BaseObjectId::class, + ObjectType.ACCOUNT_OBJECT to AccountObjectId::class, + ObjectType.ASSET_OBJECT to AssetObjectId::class, + ObjectType.MINER_OBJECT to MinerObjectId::class, + ObjectType.CUSTOM_OBJECT to CustomObjectId::class, + ObjectType.PROPOSAL_OBJECT to ProposalObjectId::class, + ObjectType.OPERATION_HISTORY_OBJECT to OperationHistoryObjectId::class, + ObjectType.WITHDRAW_PERMISSION_OBJECT to WithdrawPermissionObjectId::class, + ObjectType.VESTING_BALANCE_OBJECT to VestingBalanceObjectId::class, + ObjectType.GLOBAL_PROPERTY_OBJECT to GlobalPropertyObjectId::class, + ObjectType.DYNAMIC_GLOBAL_PROPERTY_OBJECT to DynamicGlobalPropertyObjectId::class, + ObjectType.RESERVED_OBJECT to ReservedObjectId::class, + ObjectType.ASSET_DYNAMIC_DATA to AssetDataObjectId::class, + ObjectType.ACCOUNT_BALANCE_OBJECT to AccountBalanceObjectId::class, + ObjectType.ACCOUNT_STATISTICS_OBJECT to AccountStatsObjectId::class, + ObjectType.TRANSACTION_OBJECT to TransactionObjectId::class, + ObjectType.BLOCK_SUMMARY_OBJECT to BlockSummaryObjectId::class, + ObjectType.ACCOUNT_TRANSACTION_HISTORY_OBJECT to AccountTransactionObjectId::class, + ObjectType.CHAIN_PROPERTY_OBJECT to ChainPropertyObjectId::class, + ObjectType.MINER_SCHEDULE_OBJECT to MinerScheduleObjectId::class, + ObjectType.BUDGET_RECORD_OBJECT to BudgetRecordObjectId::class, + ObjectType.PURCHASE_OBJECT to PurchaseObjectId::class, + ObjectType.CONTENT_OBJECT to ContentObjectId::class, + ObjectType.PUBLISHER_OBJECT to PublisherObjectId::class, + ObjectType.SUBSCRIPTION_OBJECT to SubscriptionObjectId::class, + ObjectType.SEEDING_STATISTICS_OBJECT to SeedingStatsObjectId::class, + ObjectType.TRANSACTION_DETAIL_OBJECT to TransactionDetailObjectId::class, + ObjectType.MESSAGING_OBJECT to MessagingObjectId::class + ) + private val regex = Regex("""(\d+)\.(\d+)\.(\d+)""") + + @JvmStatic fun isValid(id: String): Boolean = regex.matches(id.trim()) + + @JvmStatic fun parse(id: String): ObjectId = + if (isValid(id)) regex.matchEntire(id)!!.groupValues.iterator().let { + it.next() + ObjectId(it.next().toInt(), it.next().toInt(), it.next().toLong()) + } + else throw IllegalArgumentException("cannot parse id $id") + + @JvmStatic fun parseToType(id: String): ObjectId = parse(id).let { + when { + it.objectType == ObjectType.NULL_OBJECT -> NullObjectId + klasses.containsKey(it.objectType) -> klasses.getValue(it.objectType).constructors.single().call(it.instance) + else -> it + } + } + } +} + +inline fun String.isValidId(): Boolean = ObjectId.isValid(this) && ObjectId.parseToType(this) is T + +inline fun String.toObjectId(): T = ObjectId.parseToType(this).let { + if (it is T) it else throw IllegalArgumentException("invalid ${T::class} for ${it.objectType} in id $this") +} + +object NullObjectId : ObjectId(ObjectType.NULL_OBJECT, 0) +class BaseObjectId(instance: Long = 0) : ObjectId(ObjectType.BASE_OBJECT, instance) +class AccountObjectId(instance: Long = 0) : ObjectId(ObjectType.ACCOUNT_OBJECT, instance) +class AssetObjectId(instance: Long = 0) : ObjectId(ObjectType.ASSET_OBJECT, instance) +class MinerObjectId(instance: Long = 0) : ObjectId(ObjectType.MINER_OBJECT, instance) +class CustomObjectId(instance: Long = 0) : ObjectId(ObjectType.CUSTOM_OBJECT, instance) +class ProposalObjectId(instance: Long = 0) : ObjectId(ObjectType.PROPOSAL_OBJECT, instance) +class OperationHistoryObjectId(instance: Long = 0) : ObjectId(ObjectType.OPERATION_HISTORY_OBJECT, instance) +class WithdrawPermissionObjectId(instance: Long = 0) : ObjectId(ObjectType.WITHDRAW_PERMISSION_OBJECT, instance) +class VestingBalanceObjectId(instance: Long = 0) : ObjectId(ObjectType.VESTING_BALANCE_OBJECT, instance) +class GlobalPropertyObjectId(instance: Long = 0) : ObjectId(ObjectType.GLOBAL_PROPERTY_OBJECT, instance) +class DynamicGlobalPropertyObjectId(instance: Long = 0) : ObjectId(ObjectType.DYNAMIC_GLOBAL_PROPERTY_OBJECT, instance) +class ReservedObjectId(instance: Long = 0) : ObjectId(ObjectType.RESERVED_OBJECT, instance) +class AssetDataObjectId(instance: Long = 0) : ObjectId(ObjectType.ASSET_DYNAMIC_DATA, instance) +class AccountBalanceObjectId(instance: Long = 0) : ObjectId(ObjectType.ACCOUNT_BALANCE_OBJECT, instance) +class AccountStatsObjectId(instance: Long = 0) : ObjectId(ObjectType.ACCOUNT_STATISTICS_OBJECT, instance) +class TransactionObjectId(instance: Long = 0) : ObjectId(ObjectType.TRANSACTION_OBJECT, instance) +class BlockSummaryObjectId(instance: Long = 0) : ObjectId(ObjectType.BLOCK_SUMMARY_OBJECT, instance) +class AccountTransactionObjectId(instance: Long = 0) : ObjectId(ObjectType.ACCOUNT_TRANSACTION_HISTORY_OBJECT, instance) +class ChainPropertyObjectId(instance: Long = 0) : ObjectId(ObjectType.CHAIN_PROPERTY_OBJECT, instance) +class MinerScheduleObjectId(instance: Long = 0) : ObjectId(ObjectType.MINER_SCHEDULE_OBJECT, instance) +class BudgetRecordObjectId(instance: Long = 0) : ObjectId(ObjectType.BUDGET_RECORD_OBJECT, instance) +class PurchaseObjectId(instance: Long = 0) : ObjectId(ObjectType.PURCHASE_OBJECT, instance) +class ContentObjectId(instance: Long = 0) : ObjectId(ObjectType.CONTENT_OBJECT, instance) +class PublisherObjectId(instance: Long = 0) : ObjectId(ObjectType.PUBLISHER_OBJECT, instance) +class SubscriptionObjectId(instance: Long = 0) : ObjectId(ObjectType.SUBSCRIPTION_OBJECT, instance) +class SeedingStatsObjectId(instance: Long = 0) : ObjectId(ObjectType.SEEDING_STATISTICS_OBJECT, instance) +class TransactionDetailObjectId(instance: Long = 0) : ObjectId(ObjectType.TRANSACTION_DETAIL_OBJECT, instance) +class MessagingObjectId(instance: Long = 0) : ObjectId(ObjectType.MESSAGING_OBJECT, instance) diff --git a/library/src/main/java/ch/decent/sdk/model/ObjectType.kt b/library/src/main/java/ch/decent/sdk/model/ObjectType.kt index 7cd7fda4..f0ad7ac6 100644 --- a/library/src/main/java/ch/decent/sdk/model/ObjectType.kt +++ b/library/src/main/java/ch/decent/sdk/model/ObjectType.kt @@ -1,63 +1,78 @@ package ch.decent.sdk.model -import kotlin.math.max - /** * Enum type used to list all possible object types and obtain their space + type id */ -enum class ObjectType { - // dcore/libraries/chain/include/graphene/chain/protocol/types.hpp - // enum object_type, space = 1 - NULL_OBJECT, // ordinal = 0, type = 0, space = any - BASE_OBJECT, - ACCOUNT_OBJECT, - ASSET_OBJECT, - MINER_OBJECT, - CUSTOM_OBJECT, //5 - PROPOSAL_OBJECT, - OPERATION_HISTORY_OBJECT, - WITHDRAW_PERMISSION_OBJECT, - VESTING_BALANCE_OBJECT, - - // enum impl_object_type, space = 2 - GLOBAL_PROPERTY_OBJECT, // ordinal = 10, type 0 - DYNAMIC_GLOBAL_PROPERTY_OBJECT, - RESERVED_OBJECT, - ASSET_DYNAMIC_DATA, - ACCOUNT_BALANCE_OBJECT, - ACCOUNT_STATISTICS_OBJECT, //5 - TRANSACTION_OBJECT, - BLOCK_SUMMARY_OBJECT, - ACCOUNT_TRANSACTION_HISTORY_OBJECT, - CHAIN_PROPERTY_OBJECT, - MINER_SCHEDULE_OBJECT, //10 - BUDGET_RECORD_OBJECT, - PURCHASE_OBJECT, - CONTENT_OBJECT, - PUBLISHER_OBJECT, - SUBSCRIPTION_OBJECT, //15 - SEEDING_STATISTICS_OBJECT, - TRANSACTION_DETAIL_OBJECT, - MESSAGING_OBJECT; - - val space: Byte - get() = if (ordinal < 10) 1 else 2 +enum class ObjectType(val space: Int, val type: Int) { + NULL_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.NULL_OBJECT.ordinal), + BASE_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.BASE_OBJECT.ordinal), + ACCOUNT_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.ACCOUNT_OBJECT.ordinal), + ASSET_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.ASSET_OBJECT.ordinal), + MINER_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.MINER_OBJECT.ordinal), + CUSTOM_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.CUSTOM_OBJECT.ordinal), + PROPOSAL_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.PROPOSAL_OBJECT.ordinal), + OPERATION_HISTORY_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.OPERATION_HISTORY_OBJECT.ordinal), + WITHDRAW_PERMISSION_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.WITHDRAW_PERMISSION_OBJECT.ordinal), + VESTING_BALANCE_OBJECT(Space.PROTOCOL.ordinal, ProtocolId.VESTING_BALANCE_OBJECT.ordinal), + GLOBAL_PROPERTY_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.GLOBAL_PROPERTY_OBJECT.ordinal), + DYNAMIC_GLOBAL_PROPERTY_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.DYNAMIC_GLOBAL_PROPERTY_OBJECT.ordinal), + RESERVED_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.RESERVED_OBJECT.ordinal), + ASSET_DYNAMIC_DATA(Space.IMPLEMENTATION.ordinal, ImplementationId.ASSET_DYNAMIC_DATA.ordinal), + ACCOUNT_BALANCE_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.ACCOUNT_BALANCE_OBJECT.ordinal), + ACCOUNT_STATISTICS_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.ACCOUNT_STATISTICS_OBJECT.ordinal), + TRANSACTION_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.TRANSACTION_OBJECT.ordinal), + BLOCK_SUMMARY_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.BLOCK_SUMMARY_OBJECT.ordinal), + ACCOUNT_TRANSACTION_HISTORY_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.ACCOUNT_TRANSACTION_HISTORY_OBJECT.ordinal), + CHAIN_PROPERTY_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.CHAIN_PROPERTY_OBJECT.ordinal), + MINER_SCHEDULE_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.MINER_SCHEDULE_OBJECT.ordinal), + BUDGET_RECORD_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.BUDGET_RECORD_OBJECT.ordinal), + PURCHASE_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.PURCHASE_OBJECT.ordinal), + CONTENT_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.CONTENT_OBJECT.ordinal), + PUBLISHER_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.PUBLISHER_OBJECT.ordinal), + SUBSCRIPTION_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.SUBSCRIPTION_OBJECT.ordinal), + SEEDING_STATISTICS_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.SEEDING_STATISTICS_OBJECT.ordinal), + TRANSACTION_DETAIL_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.TRANSACTION_DETAIL_OBJECT.ordinal), + MESSAGING_OBJECT(Space.IMPLEMENTATION.ordinal, ImplementationId.MESSAGING_OBJECT.ordinal), + UNKNOWN_OBJECT(0, 0); - val type: Byte - get() = (ordinal - (space - 1) * 10).toByte() + internal enum class Space { + NULL, + PROTOCOL, + IMPLEMENTATION + } - /** - * This method is used to return the generic object type in the form space.type.0. - * - * Not to be confused with [ChainObject.objectId], which will return - * the full object id in the form space.type.id. - * - * @return: The generic object type - */ - val genericId: ChainObject - get() = ChainObject(this) + internal enum class ProtocolId { + NULL_OBJECT, // 0 + BASE_OBJECT, + ACCOUNT_OBJECT, + ASSET_OBJECT, + MINER_OBJECT, + CUSTOM_OBJECT, //5 + PROPOSAL_OBJECT, + OPERATION_HISTORY_OBJECT, + WITHDRAW_PERMISSION_OBJECT, + VESTING_BALANCE_OBJECT + } - companion object { - fun fromSpaceType(space: Int, type: Int) = ObjectType.values()[max(space - 1, 0) * 10 + type] + internal enum class ImplementationId { + GLOBAL_PROPERTY_OBJECT, //0 + DYNAMIC_GLOBAL_PROPERTY_OBJECT, + RESERVED_OBJECT, + ASSET_DYNAMIC_DATA, + ACCOUNT_BALANCE_OBJECT, + ACCOUNT_STATISTICS_OBJECT, //5 + TRANSACTION_OBJECT, + BLOCK_SUMMARY_OBJECT, + ACCOUNT_TRANSACTION_HISTORY_OBJECT, + CHAIN_PROPERTY_OBJECT, + MINER_SCHEDULE_OBJECT, //10 + BUDGET_RECORD_OBJECT, + PURCHASE_OBJECT, + CONTENT_OBJECT, + PUBLISHER_OBJECT, + SUBSCRIPTION_OBJECT, //15 + SEEDING_STATISTICS_OBJECT, + TRANSACTION_DETAIL_OBJECT, + MESSAGING_OBJECT } } diff --git a/library/src/main/java/ch/decent/sdk/model/OperationHistory.kt b/library/src/main/java/ch/decent/sdk/model/OperationHistory.kt index 8a7370ef..47295423 100644 --- a/library/src/main/java/ch/decent/sdk/model/OperationHistory.kt +++ b/library/src/main/java/ch/decent/sdk/model/OperationHistory.kt @@ -7,7 +7,7 @@ import com.google.gson.JsonArray import com.google.gson.annotations.SerializedName data class OperationHistory( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: OperationHistoryObjectId, @SerializedName("op") val operation: BaseOperation, @SerializedName("result") val result: JsonArray, @SerializedName("block_num") @UInt32 val blockNum: Long, diff --git a/library/src/main/java/ch/decent/sdk/model/Purchase.kt b/library/src/main/java/ch/decent/sdk/model/Purchase.kt index 51582d03..1f260a94 100644 --- a/library/src/main/java/ch/decent/sdk/model/Purchase.kt +++ b/library/src/main/java/ch/decent/sdk/model/Purchase.kt @@ -2,20 +2,21 @@ package ch.decent.sdk.model import ch.decent.sdk.model.types.UInt32 import ch.decent.sdk.model.types.UInt64 +import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.annotations.SerializedName import org.threeten.bp.LocalDateTime import java.math.BigInteger data class Purchase( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: PurchaseObjectId, @SerializedName("consumer") val author: String, @SerializedName("URI") val uri: String, @SerializedName("synopsis") val synopsisJson: String, @SerializedName("price") val price: AssetAmount, @SerializedName("paid_price_before_exchange") val priceBefore: AssetAmount, @SerializedName("paid_price_after_exchange") val priceAfter: AssetAmount, - @SerializedName("seeders_answered") val seedersAnswered: List, + @SerializedName("seeders_answered") val seedersAnswered: List, @SerializedName("size") @UInt64 val size: BigInteger, @SerializedName("rating") @UInt64 val rating: BigInteger, @SerializedName("comment") val comment: String, @@ -30,10 +31,6 @@ data class Purchase( @SerializedName("region_code_from") @UInt32 val regionFrom: Long ) { - fun synopsis(): Synopsis = - GsonBuilder() - .registerTypeAdapter(ChainObject::class.java, ChainObjectAdapter) - .create() - .fromJson(synopsisJson, Synopsis::class.java) + fun synopsis(): Synopsis = Gson().fromJson(synopsisJson, Synopsis::class.java) } diff --git a/library/src/main/java/ch/decent/sdk/model/Seeder.kt b/library/src/main/java/ch/decent/sdk/model/Seeder.kt index e2191c00..91d88ad4 100644 --- a/library/src/main/java/ch/decent/sdk/model/Seeder.kt +++ b/library/src/main/java/ch/decent/sdk/model/Seeder.kt @@ -6,15 +6,15 @@ import com.google.gson.annotations.SerializedName import org.threeten.bp.LocalDateTime import java.math.BigInteger -// todo untested data class Seeder( - @SerializedName("id") val id: ChainObject, + @SerializedName("id") val id: PublisherObjectId, + @SerializedName("seeder") val seeder: AccountObjectId, @SerializedName("free_space") @UInt64 val freeSpace: BigInteger, @SerializedName("price") val price: AssetAmount, @SerializedName("expiration") val expiration: LocalDateTime, @SerializedName("pubKey") val pubKey: PubKey, @SerializedName("ipfs_ID") val ipfsId: String, - @SerializedName("stats") val stats: ChainObject, + @SerializedName("stats") val stats: SeedingStatsObjectId, @SerializedName("rating") @UInt32 val rating: Long, @SerializedName("region_code") val regionCode: String ) diff --git a/library/src/main/java/ch/decent/sdk/model/SignedBlock.kt b/library/src/main/java/ch/decent/sdk/model/SignedBlock.kt index 2177ff7f..1055fc4a 100644 --- a/library/src/main/java/ch/decent/sdk/model/SignedBlock.kt +++ b/library/src/main/java/ch/decent/sdk/model/SignedBlock.kt @@ -6,7 +6,7 @@ import org.threeten.bp.LocalDateTime data class SignedBlock( @SerializedName("previous") val previous: String, @SerializedName("timestamp") val timestamp: LocalDateTime, - @SerializedName("miner") val miner: ChainObject, + @SerializedName("miner") val miner: MinerObjectId, @SerializedName("transaction_merkle_root") val transactionMerkleRoot: String, @SerializedName("miner_signature") val minerSignature: String, @SerializedName("transactions") val transactions: List, diff --git a/library/src/main/java/ch/decent/sdk/model/Subscription.kt b/library/src/main/java/ch/decent/sdk/model/Subscription.kt index f67fe3f2..6c4b7479 100644 --- a/library/src/main/java/ch/decent/sdk/model/Subscription.kt +++ b/library/src/main/java/ch/decent/sdk/model/Subscription.kt @@ -4,8 +4,9 @@ import com.google.gson.annotations.SerializedName import org.threeten.bp.LocalDateTime data class Subscription( - @SerializedName("from") val from: ChainObject, - @SerializedName("to") val to: ChainObject, + @SerializedName("id") val id: SubscriptionObjectId, + @SerializedName("from") val from: AccountObjectId, + @SerializedName("to") val to: AccountObjectId, @SerializedName("expiration") val expiration: LocalDateTime, @SerializedName("automatic_renewal") val renewal: Boolean ) diff --git a/library/src/main/java/ch/decent/sdk/model/TransactionDetail.kt b/library/src/main/java/ch/decent/sdk/model/TransactionDetail.kt index 28299a60..ce90d5a8 100644 --- a/library/src/main/java/ch/decent/sdk/model/TransactionDetail.kt +++ b/library/src/main/java/ch/decent/sdk/model/TransactionDetail.kt @@ -4,9 +4,9 @@ import com.google.gson.annotations.SerializedName import org.threeten.bp.LocalDateTime data class TransactionDetail( - @SerializedName("id") val id: ChainObject, - @SerializedName("m_from_account") val from: ChainObject, - @SerializedName("m_to_account") val to: ChainObject, + @SerializedName("id") val id: TransactionDetailObjectId, + @SerializedName("m_from_account") val from: AccountObjectId, + @SerializedName("m_to_account") val to: AccountObjectId, @SerializedName("m_operation_type") val type: Int, @SerializedName("m_transaction_amount") val amount: AssetAmount, @SerializedName("m_transaction_encrypted_memo") val memo: Memo?, diff --git a/library/src/main/java/ch/decent/sdk/model/TypeAdapters.kt b/library/src/main/java/ch/decent/sdk/model/TypeAdapters.kt index 2fd9c062..f84970fc 100644 --- a/library/src/main/java/ch/decent/sdk/model/TypeAdapters.kt +++ b/library/src/main/java/ch/decent/sdk/model/TypeAdapters.kt @@ -7,6 +7,7 @@ import ch.decent.sdk.crypto.dpk import ch.decent.sdk.model.operation.BaseOperation import ch.decent.sdk.model.operation.EmptyOperation import ch.decent.sdk.model.operation.OperationType +import ch.decent.sdk.model.operation.UnknownOperation import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonNull @@ -29,6 +30,7 @@ object DateTimeAdapter : TypeAdapter() { override fun read(reader: JsonReader): LocalDateTime = LocalDateTime.parse(reader.nextString()) } +/* object ChainObjectAdapter : TypeAdapter() { override fun read(reader: JsonReader): ChainObject = ChainObject.parse(reader.nextString()) @@ -36,6 +38,7 @@ object ChainObjectAdapter : TypeAdapter() { value?.let { out.value(it.objectId) } ?: out.nullValue() } } +*/ object AddressAdapter : TypeAdapter
() { override fun read(reader: JsonReader): Address? = Address.decodeCheckNull(reader.nextString()) @@ -61,6 +64,27 @@ object AuthMapAdapter : TypeAdapter() { } } +@Suppress("UNCHECKED_CAST") +object ObjectIdFactory : TypeAdapterFactory { + override fun create(gson: Gson, type: TypeToken): TypeAdapter? { + if (ObjectId::class.javaObjectType.isAssignableFrom(type.rawType)) { + return object : TypeAdapter() { + override fun write(out: JsonWriter, value: T) { + out.value(value.toString()) + } + + override fun read(reader: JsonReader): T { + val id = reader.nextString() + val oid = if (type.rawType == ObjectId::class.javaObjectType) ObjectId.parse(id) else ObjectId.parseToType(id) + return oid as T + } + + } + } + return null + } +} + @Suppress("UNCHECKED_CAST") object OperationTypeFactory : TypeAdapterFactory { override fun create(gson: Gson, type: TypeToken): TypeAdapter? { @@ -77,7 +101,11 @@ object OperationTypeFactory : TypeAdapterFactory { override fun read(reader: JsonReader): T? { val el = Streams.parse(reader) - val op = OperationType.values()[el.asJsonArray[0].asInt] + val idx = el.asJsonArray[0].asInt + val op = OperationType.values().getOrElse(idx) { OperationType.UNKNOWN_OPERATION } + + if (op == OperationType.UNKNOWN_OPERATION) return UnknownOperation(idx) as T? + val obj = el.asJsonArray[1].asJsonObject return op.clazz?.let { val delegate = gson.getDelegateAdapter(this@OperationTypeFactory, TypeToken.get(it)) @@ -171,7 +199,7 @@ object PubKeyAdapter : TypeAdapter() { object ExtraKeysAdapter : TypeAdapter() { override fun read(reader: JsonReader): Wallet.ExtraKeys { reader.beginArray() - val account = reader.nextString().toChainObject() + val account = reader.nextString().toObjectId() reader.beginArray() val keys = mutableListOf
() while (reader.peek() != JsonToken.END_ARRAY) { @@ -184,7 +212,7 @@ object ExtraKeysAdapter : TypeAdapter() { override fun write(out: JsonWriter, value: Wallet.ExtraKeys) { out.beginArray() - out.value(value.account.objectId) + out.value(value.account.toString()) out.beginArray() value.keys.forEach { out.value(it.encode()) } out.endArray() @@ -212,13 +240,13 @@ object MinerIdAdapter : TypeAdapter() { override fun write(out: JsonWriter, value: MinerId) { out.beginArray() out.value(value.name) - out.value(value.id.objectId) + out.value(value.id.toString()) out.endArray() } override fun read(reader: JsonReader): MinerId { reader.beginArray() - val minerId = MinerId(reader.nextString(), reader.nextString().toChainObject()) + val minerId = MinerId(reader.nextString(), reader.nextString().toObjectId()) reader.endArray() return minerId } @@ -244,7 +272,7 @@ object OperationTypeAdapter : TypeAdapter() { out.value(value.ordinal) } - override fun read(reader: JsonReader): OperationType = OperationType.values()[reader.nextInt()] + override fun read(reader: JsonReader): OperationType = OperationType.values().getOrElse(reader.nextInt()) { OperationType.UNKNOWN_OPERATION } } object VoteIdAdapter : TypeAdapter() { @@ -260,7 +288,7 @@ object CoAuthorsAdapter : TypeAdapter() { out.beginArray() value.authors.forEach { (id, bp) -> out.beginArray() - out.value(id.objectId) + out.value(id.toString()) out.value(bp) out.endArray() } @@ -268,11 +296,11 @@ object CoAuthorsAdapter : TypeAdapter() { } override fun read(reader: JsonReader): CoAuthors { - val map = mutableMapOf() + val map = mutableMapOf() reader.beginArray() while (reader.hasNext()) { reader.beginArray() - map[reader.nextString().toChainObject()] = reader.nextInt() + map[reader.nextString().toObjectId()] = reader.nextInt() reader.endArray() } reader.endArray() diff --git a/library/src/main/java/ch/decent/sdk/model/VestingBalance.kt b/library/src/main/java/ch/decent/sdk/model/VestingBalance.kt index 8880a8ae..75e51b4f 100644 --- a/library/src/main/java/ch/decent/sdk/model/VestingBalance.kt +++ b/library/src/main/java/ch/decent/sdk/model/VestingBalance.kt @@ -4,7 +4,8 @@ import com.google.gson.annotations.SerializedName // todo policy.. data class VestingBalance( - @SerializedName("owner") val owner: ChainObject, + @SerializedName("id") val id: VestingBalanceObjectId, + @SerializedName("owner") val owner: AccountObjectId, @SerializedName("balance") val balance: AssetAmount, @SerializedName("policy") val policy: Any ) diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AccountCreateOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AccountCreateOperation.kt index c61dbdc6..66d00c20 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AccountCreateOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AccountCreateOperation.kt @@ -2,11 +2,10 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.crypto.Address import ch.decent.sdk.model.Account +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AccountOptions import ch.decent.sdk.model.Authority -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName /** @@ -21,7 +20,7 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AccountCreateOperation @JvmOverloads constructor( - @SerializedName("registrar") val registrar: ChainObject, + @SerializedName("registrar") val registrar: AccountObjectId, @SerializedName("name") val name: String, @SerializedName("owner") val owner: Authority, @SerializedName("active") val active: Authority, @@ -30,12 +29,11 @@ class AccountCreateOperation @JvmOverloads constructor( ) : BaseOperation(OperationType.ACCOUNT_CREATE_OPERATION, fee) { init { - require(registrar.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } require(Account.isValidName(name)) { "not a valid name" } } @JvmOverloads - constructor(registrar: ChainObject, name: String, public: Address, fee: Fee = Fee()) : + constructor(registrar: AccountObjectId, name: String, public: Address, fee: Fee = Fee()) : this(registrar, name, Authority(public), Authority(public), AccountOptions(public), fee) override fun toString(): String { diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AccountUpdateOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AccountUpdateOperation.kt index c6afe16b..46dbffc6 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AccountUpdateOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AccountUpdateOperation.kt @@ -1,9 +1,9 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.model.Account +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AccountOptions import ch.decent.sdk.model.Authority -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.VoteId @@ -20,7 +20,7 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AccountUpdateOperation @JvmOverloads constructor( - @SerializedName("account") val accountId: ChainObject, + @SerializedName("account") val accountId: AccountObjectId, @SerializedName("owner") var owner: Authority? = null, @SerializedName("active") var active: Authority? = null, @SerializedName("new_options") var options: AccountOptions? = null, @@ -31,10 +31,6 @@ class AccountUpdateOperation @JvmOverloads constructor( constructor(account: Account, votes: Set, fee: Fee) : this(account.id, options = account.options.copy(votes = votes), fee = fee) - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } - } - override fun toString(): String { return "AccountUpdateOperation(accountId=$accountId, owner=$owner, active=$active, options=$options)" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AddOrUpdateContentOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AddOrUpdateContentOperation.kt index ed354c3f..8b663ed1 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AddOrUpdateContentOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AddOrUpdateContentOperation.kt @@ -1,13 +1,11 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.DCoreConstants.BASIS_POINTS_TOTAL +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.CoAuthors import ch.decent.sdk.model.CustodyData import ch.decent.sdk.model.Fee import ch.decent.sdk.model.KeyPart -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.RegionalPrice import ch.decent.sdk.model.types.UInt32 import ch.decent.sdk.model.types.UInt64 @@ -44,13 +42,13 @@ import java.util.regex.Pattern */ class AddOrUpdateContentOperation @JvmOverloads constructor( @SerializedName("size") @UInt64 val size: BigInteger = BigInteger.ONE, - @SerializedName("author") val author: ChainObject, + @SerializedName("author") val author: AccountObjectId, @SerializedName("co_authors") var coAuthors: CoAuthors = CoAuthors(emptyMap()), @SerializedName("URI") val uri: String, @SerializedName("quorum") @UInt32 val quorum: Int = 0, // seeders count won't overflow Int.max @SerializedName("price") var price: List, @SerializedName("hash") val hash: String = uri.toByteArray().ripemd160().hex(), - @SerializedName("seeders") val seeders: List = emptyList(), + @SerializedName("seeders") val seeders: List = emptyList(), @SerializedName("key_parts") val keyParts: List = emptyList(), @SerializedName("expiration") val expiration: LocalDateTime, @SerializedName("publishing_fee") val publishingFee: AssetAmount = AssetAmount(0), @@ -61,10 +59,8 @@ class AddOrUpdateContentOperation @JvmOverloads constructor( init { require(size > BigInteger.ZERO) { "invalid file size" } - require(author.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } require(Pattern.compile("^(https?|ipfs|magnet):.*").matcher(uri).matches()) { "unsupported uri scheme" } require(quorum >= 0) { "invalid seeders count" } - require(expiration.toEpochSecond(ZoneOffset.UTC) > LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)) { "invalid expiration time" } require(hash.unhex().size == TRX_ID_SIZE) { "invalid file hash size, should be 40 chars long, hex encoded" } } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetClaimFeesOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetClaimFeesOperation.kt index 5a772c0e..1d4ca760 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetClaimFeesOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetClaimFeesOperation.kt @@ -1,10 +1,8 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.DCoreConstants +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName /** @@ -17,17 +15,12 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetClaimFeesOperation @JvmOverloads constructor( - @SerializedName("issuer") val issuer: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, @SerializedName("uia_asset") val uia: AssetAmount, @SerializedName("dct_asset") val dct: AssetAmount, fee: Fee = Fee() ) : BaseOperation(OperationType.ASSET_CLAIM_FEES_OPERATION, fee) { - init { - require(issuer.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } - require(dct.assetId == DCoreConstants.DCT_ASSET_ID) { "not an DCT asset id" } - } - override fun toString(): String { return "AssetClaimFeesOperation(issuer=$issuer, uia=$uia, dct=$dct)" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetCreateOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetCreateOperation.kt index e643d72b..28cc31e9 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetCreateOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetCreateOperation.kt @@ -3,12 +3,11 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.DCoreConstants import ch.decent.sdk.DCoreConstants.PRECISION_ALLOWED import ch.decent.sdk.DCoreConstants.UIA_DESCRIPTION_MAX_CHARS +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Asset import ch.decent.sdk.model.AssetOptions -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee import ch.decent.sdk.model.MonitoredAssetOptions -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.types.UInt8 import com.google.gson.annotations.SerializedName @@ -25,7 +24,7 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetCreateOperation @JvmOverloads constructor( - @SerializedName("issuer") val issuer: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, @SerializedName("symbol") val symbol: String, @SerializedName("precision") @UInt8 val precision: Byte, @SerializedName("description") val description: String, @@ -35,7 +34,6 @@ class AssetCreateOperation @JvmOverloads constructor( ) : BaseOperation(OperationType.ASSET_CREATE_OPERATION, fee) { init { - require(issuer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } require(Asset.isValidSymbol(symbol)) { "invalid asset symbol: $symbol" } require(precision in PRECISION_ALLOWED) { "precision must be in range of 0-12" } require(description.length <= UIA_DESCRIPTION_MAX_CHARS) { "description cannot be longer then $UIA_DESCRIPTION_MAX_CHARS chars" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetFundPoolsOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetFundPoolsOperation.kt index f3305a80..83041b93 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetFundPoolsOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetFundPoolsOperation.kt @@ -1,10 +1,8 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.DCoreConstants +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName /** @@ -17,17 +15,12 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetFundPoolsOperation @JvmOverloads constructor( - @SerializedName("from_account") val from: ChainObject, + @SerializedName("from_account") val from: AccountObjectId, @SerializedName("uia_asset") val uia: AssetAmount, @SerializedName("dct_asset") val dct: AssetAmount, fee: Fee = Fee() ) : BaseOperation(OperationType.ASSET_FUND_POOLS_OPERATION, fee) { - init { - require(from.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } - require(dct.assetId == DCoreConstants.DCT_ASSET_ID) { "not an DCT asset id" } - } - override fun toString(): String { return "AssetFundPoolsOperation(from=$from, uia=$uia, dct=$dct)" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetIssueOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetIssueOperation.kt index da34f615..a4cc9c23 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetIssueOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetIssueOperation.kt @@ -1,10 +1,9 @@ package ch.decent.sdk.model.operation +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName /** @@ -18,18 +17,13 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetIssueOperation @JvmOverloads constructor( - @SerializedName("issuer") val issuer: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, @SerializedName("asset_to_issue") val assetToIssue: AssetAmount, - @SerializedName("issue_to_account") val issueToAccount: ChainObject, + @SerializedName("issue_to_account") val issueToAccount: AccountObjectId, @SerializedName("memo") val memo: Memo? = null, fee: Fee = Fee() ) : BaseOperation(OperationType.ASSET_ISSUE_OPERATION, fee) { - init { - require(issuer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(issueToAccount.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } - override fun toString(): String { return "AssetIssueOperation(issuer=$issuer, assetToIssue=$assetToIssue, issueToAccount=$issueToAccount, memo=$memo)" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetPublishFeedOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetPublishFeedOperation.kt index 3851e0f1..9a12ec74 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetPublishFeedOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetPublishFeedOperation.kt @@ -1,8 +1,8 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.PriceFeed import com.google.gson.annotations.SerializedName @@ -12,15 +12,11 @@ import com.google.gson.annotations.SerializedName * therefore throws Missing Active Authority 1.2.0 */ class AssetPublishFeedOperation @JvmOverloads constructor( - @SerializedName("publisher") val publisher: ChainObject, - @SerializedName("asset_id") val asset: ChainObject, + @SerializedName("publisher") val publisher: AccountObjectId, + @SerializedName("asset_id") val asset: AssetObjectId, @SerializedName("feed") val feed: PriceFeed, fee: Fee = Fee() ) : BaseOperation(OperationType.ASSET_PUBLISH_FEED_OPERATION, fee) { - init { - require(publisher.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(asset.objectType == ObjectType.ASSET_OBJECT) { "not a valid asset object id" } - } override fun toString(): String { return "AssetPublishFeedOperation(publisher=$publisher, asset=$asset, feed=$feed)" diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetReserveOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetReserveOperation.kt index aa10c0ae..977da11a 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetReserveOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetReserveOperation.kt @@ -1,9 +1,8 @@ package ch.decent.sdk.model.operation +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName /** @@ -15,15 +14,11 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetReserveOperation @JvmOverloads constructor( - @SerializedName("payer") val payer: ChainObject, + @SerializedName("payer") val payer: AccountObjectId, @SerializedName("amount_to_reserve") val amount: AssetAmount, fee: Fee = Fee() ) : BaseOperation(OperationType.ASSET_RESERVE_OPERATION, fee) { - init { - require(payer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } - override fun toString(): String { return "AssetReserveOperation(payer=$payer, amount=$amount)" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateAdvancedOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateAdvancedOperation.kt index c3754118..cb3f2713 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateAdvancedOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateAdvancedOperation.kt @@ -1,9 +1,9 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.DCoreConstants -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.types.UInt8 import com.google.gson.annotations.SerializedName @@ -18,16 +18,14 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetUpdateAdvancedOperation @JvmOverloads constructor( - @SerializedName("issuer") val issuer: ChainObject, - @SerializedName("asset_to_update") val assetToUpdate: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, + @SerializedName("asset_to_update") val assetToUpdate: AssetObjectId, @SerializedName("new_precision") @UInt8 var precision: Byte, @SerializedName("set_fixed_max_supply") var fixedMaxSupply: Boolean, fee: Fee = Fee() ) : BaseOperation(OperationType.UPDATE_USER_ISSUED_ASSET_ADVANCED, fee) { init { - require(issuer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(assetToUpdate.objectType == ObjectType.ASSET_OBJECT) { "not a valid asset object id" } require(precision in DCoreConstants.PRECISION_ALLOWED) { "precision must be in range of 0-12" } } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateMonitoredOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateMonitoredOperation.kt index 916a4981..853dde8d 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateMonitoredOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateMonitoredOperation.kt @@ -1,9 +1,9 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.DCoreConstants.UIA_DESCRIPTION_MAX_CHARS -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.types.UInt32 import ch.decent.sdk.model.types.UInt8 import com.google.gson.annotations.SerializedName @@ -14,8 +14,8 @@ import com.google.gson.annotations.SerializedName * therefore throws Missing Active Authority 1.2.0 */ class AssetUpdateMonitoredOperation @JvmOverloads constructor( - @SerializedName("issuer") val issuer: ChainObject, - @SerializedName("asset_to_update") val assetToUpdate: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, + @SerializedName("asset_to_update") val assetToUpdate: AssetObjectId, @SerializedName("new_description") val description: String, @SerializedName("new_feed_lifetime_sec") @UInt32 val newFeedLifetime: Long, @SerializedName("new_minimum_feeds") @UInt8 val newMinimumFeeds: Short, @@ -23,8 +23,6 @@ class AssetUpdateMonitoredOperation @JvmOverloads constructor( ) : BaseOperation(OperationType.UPDATE_MONITORED_ASSET_OPERATION, fee) { init { - require(issuer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(assetToUpdate.objectType == ObjectType.ASSET_OBJECT) { "not a valid asset object id" } require(description.length <= UIA_DESCRIPTION_MAX_CHARS) { "description cannot be longer then $UIA_DESCRIPTION_MAX_CHARS chars" } } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateOperation.kt index b7bb5e26..54e2cbf7 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/AssetUpdateOperation.kt @@ -1,11 +1,10 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.DCoreConstants import ch.decent.sdk.DCoreConstants.UIA_DESCRIPTION_MAX_CHARS -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.ExchangeRate import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.types.UInt64 import com.google.gson.annotations.SerializedName @@ -23,10 +22,10 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class AssetUpdateOperation @JvmOverloads constructor( - @SerializedName("issuer") val issuer: ChainObject, - @SerializedName("asset_to_update") val assetToUpdate: ChainObject, + @SerializedName("issuer") val issuer: AccountObjectId, + @SerializedName("asset_to_update") val assetToUpdate: AssetObjectId, @SerializedName("new_description") var newDescription: String, - @SerializedName("new_issuer") val newIssuer: ChainObject?, + @SerializedName("new_issuer") val newIssuer: AccountObjectId?, @SerializedName("max_supply") @UInt64 var maxSupply: Long, // Asset.options.maxSupply is @Int64 therefore we use Long here @SerializedName("core_exchange_rate") var coreExchangeRate: ExchangeRate, @SerializedName("is_exchangeable") var exchangeable: Boolean, @@ -34,10 +33,7 @@ class AssetUpdateOperation @JvmOverloads constructor( ) : BaseOperation(OperationType.UPDATE_USER_ISSUED_ASSET_OPERATION, fee) { init { - require(issuer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(assetToUpdate.objectType == ObjectType.ASSET_OBJECT) { "not a valid asset object id" } require(newDescription.length <= UIA_DESCRIPTION_MAX_CHARS) { "description cannot be longer then $UIA_DESCRIPTION_MAX_CHARS chars" } - require(newIssuer?.objectType?.equals(ObjectType.ACCOUNT_OBJECT) ?: true) { "not a valid account object id" } // require(maxSupply <= DCoreConstants.MAX_SHARE_SUPPLY) { "max supply max value overflow" } } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/CustomOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/CustomOperation.kt index 749fb872..8b2b660c 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/CustomOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/CustomOperation.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.utils.unhex import com.google.gson.annotations.SerializedName @@ -17,8 +17,8 @@ import com.google.gson.annotations.SerializedName */ open class CustomOperation @JvmOverloads constructor( type: CustomOperationType, - @SerializedName("payer") val payer: ChainObject, - @SerializedName("required_auths") val requiredAuths: List, + @SerializedName("payer") val payer: AccountObjectId, + @SerializedName("required_auths") val requiredAuths: List, @SerializedName("data") val data: String, fee: Fee = Fee() ) : BaseOperation(OperationType.CUSTOM_OPERATION, fee) { diff --git a/library/src/main/java/ch/decent/sdk/model/operation/LeaveRatingAndCommentOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/LeaveRatingAndCommentOperation.kt index 4c73527f..8815a199 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/LeaveRatingAndCommentOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/LeaveRatingAndCommentOperation.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.DCoreConstants -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.model.types.UInt64 import com.google.gson.annotations.SerializedName @@ -18,7 +18,7 @@ import com.google.gson.annotations.SerializedName */ class LeaveRatingAndCommentOperation @JvmOverloads constructor( @SerializedName("URI") val uri: String, - @SerializedName("consumer") val consumer: ChainObject, + @SerializedName("consumer") val consumer: AccountObjectId, @SerializedName("rating") @UInt64 val rating: Byte, // 1-5 stars @SerializedName("comment") val comment: String, fee: Fee = Fee() diff --git a/library/src/main/java/ch/decent/sdk/model/operation/OperationType.kt b/library/src/main/java/ch/decent/sdk/model/operation/OperationType.kt index d6e9311e..af37493d 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/OperationType.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/OperationType.kt @@ -50,5 +50,6 @@ enum class OperationType(val clazz: Class<*>? = null) { RETURN_ESCROW_BUYING_OPERATION, // VIRTUAL PAY_SEEDER_OPERATION, // VIRTUAL FINISH_BUYING_OPERATION, // VIRTUAL 45 - RENEWAL_OF_SUBSCRIPTION_OPERATION // VIRTUAL + RENEWAL_OF_SUBSCRIPTION_OPERATION, // VIRTUAL + UNKNOWN_OPERATION } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/PurchaseContentOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/PurchaseContentOperation.kt index 30a41a5f..191a6218 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/PurchaseContentOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/PurchaseContentOperation.kt @@ -1,11 +1,10 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Content import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.PubKey import ch.decent.sdk.model.Regions import ch.decent.sdk.model.types.UInt32 @@ -27,7 +26,7 @@ import java.util.regex.Pattern */ class PurchaseContentOperation @JvmOverloads constructor( @SerializedName("URI") val uri: String, - @SerializedName("consumer") val consumer: ChainObject, + @SerializedName("consumer") val consumer: AccountObjectId, @SerializedName("price") val price: AssetAmount, @SerializedName("pubKey") val publicElGamal: PubKey, @SerializedName("region_code_from") @UInt32 val regionCode: Long = Regions.ALL.id, @@ -43,7 +42,6 @@ class PurchaseContentOperation @JvmOverloads constructor( ) init { - require(consumer.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } require(Pattern.compile("^(https?|ipfs|magnet):.*").matcher(uri).matches()) { "unsupported uri scheme" } require(price.amount >= 0) { "amount must be >= 0" } } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/RemoveContentOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/RemoveContentOperation.kt index 5c4b5d6e..a94deaac 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/RemoveContentOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/RemoveContentOperation.kt @@ -1,8 +1,7 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName /** @@ -14,15 +13,11 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class RemoveContentOperation @JvmOverloads constructor( - @SerializedName("author") val author: ChainObject, + @SerializedName("author") val author: AccountObjectId, @SerializedName("URI") val uri: String, fee: Fee = Fee() ) : BaseOperation(OperationType.CONTENT_CANCELLATION_OPERATION, fee) { - init { - require(author.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } - override fun toString(): String { return "RemoveContentOperation(author=$author, uri='$uri')" } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt index d2702320..1985323a 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.utils.hex @@ -15,7 +15,7 @@ import ch.decent.sdk.utils.hex */ class SendMessageOperation @JvmOverloads constructor( messagePayloadJson: String, - payer: ChainObject, - requiredAuths: List = listOf(payer), + payer: AccountObjectId, + requiredAuths: List = listOf(payer), fee: Fee = Fee() ) : CustomOperation(CustomOperationType.MESSAGING, payer, requiredAuths, messagePayloadJson.toByteArray().hex(), fee) diff --git a/library/src/main/java/ch/decent/sdk/model/operation/TransferOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/TransferOperation.kt index b2d62266..a54a0703 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/TransferOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/TransferOperation.kt @@ -1,9 +1,10 @@ package ch.decent.sdk.model.operation +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo +import ch.decent.sdk.model.ObjectId import ch.decent.sdk.model.ObjectType import com.google.gson.annotations.SerializedName @@ -18,15 +19,14 @@ import com.google.gson.annotations.SerializedName * When set to other then DCT, the request might fail if the asset is not convertible to DCT or conversion pool is not large enough */ class TransferOperation @JvmOverloads constructor( - @SerializedName("from") val from: ChainObject, - @SerializedName("to") val to: ChainObject, + @SerializedName("from") val from: AccountObjectId, + @SerializedName("to") val to: ObjectId, @SerializedName("amount") val amount: AssetAmount, @SerializedName("memo") val memo: Memo? = null, fee: Fee = Fee() ) : BaseOperation(OperationType.TRANSFER2_OPERATION, fee) { init { - require(from.objectType == ObjectType.ACCOUNT_OBJECT) { "not an account object id" } require(to.objectType == ObjectType.ACCOUNT_OBJECT || to.objectType == ObjectType.CONTENT_OBJECT) { "not an account or content object id" } } diff --git a/library/src/main/java/ch/decent/sdk/model/operation/UnknownOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/UnknownOperation.kt new file mode 100644 index 00000000..fd17b9b3 --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/model/operation/UnknownOperation.kt @@ -0,0 +1,9 @@ +package ch.decent.sdk.model.operation + +import ch.decent.sdk.model.Fee + +class UnknownOperation(val id: Int) : BaseOperation(OperationType.UNKNOWN_OPERATION, Fee()) { + override fun toString(): String { + return "UnknownOperation(id=$id)" + } +} diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GenerateContentKeys.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GenerateContentKeys.kt index 8eb5fb02..91985b95 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GenerateContentKeys.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GenerateContentKeys.kt @@ -1,20 +1,14 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.ContentKeys -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.net.model.ApiGroup internal class GenerateContentKeys( - seeders: List + seeders: List ) : BaseRequest( ApiGroup.DATABASE, "generate_content_keys", ContentKeys::class.java, listOf(seeders) -) { - - init { - require(seeders.all { it.objectType == ObjectType.ACCOUNT_OBJECT }) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalanceForTransaction.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalanceForTransaction.kt index d3dcaf71..2680cc54 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalanceForTransaction.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalanceForTransaction.kt @@ -1,22 +1,16 @@ package ch.decent.sdk.net.model.request +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.BalanceChange -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.OperationHistoryObjectId import ch.decent.sdk.net.model.ApiGroup internal class GetAccountBalanceForTransaction( - accountId: ChainObject, - operationId: ChainObject + accountId: AccountObjectId, + operationId: OperationHistoryObjectId ) : BaseRequest( ApiGroup.HISTORY, "get_account_balance_for_transaction", BalanceChange::class.java, listOf(accountId, operationId) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(operationId.objectType == ObjectType.OPERATION_HISTORY_OBJECT) { "not a valid history object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalances.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalances.kt index 5f77d965..bde089f0 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalances.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountBalances.kt @@ -1,23 +1,17 @@ package ch.decent.sdk.net.model.request +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetAccountBalances( - accountId: ChainObject, - assets: List = emptyList() + accountId: AccountObjectId, + assets: List = emptyList() ) : BaseRequest>( ApiGroup.DATABASE, "get_account_balances", TypeToken.getParameterized(List::class.java, AssetAmount::class.java).type, - listOf(accountId.objectId, assets) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(assets.all { it.objectType == ObjectType.ASSET_OBJECT }) { "not a valid asset object id" } - } -} + listOf(accountId, assets) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountById.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountById.kt index eee9a858..97cbc21a 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountById.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountById.kt @@ -1,18 +1,12 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import com.google.gson.reflect.TypeToken internal class GetAccountById( - accountIds: List + accountIds: List ) : GetObjects>( accountIds, TypeToken.getParameterized(List::class.java, Account::class.java).type -) { - - init { - require(accountIds.all { it.objectType == ObjectType.ACCOUNT_OBJECT }) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountHistory.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountHistory.kt index 39f99dee..185983c9 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountHistory.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountHistory.kt @@ -1,28 +1,21 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.OperationHistory +import ch.decent.sdk.model.OperationHistoryObjectId import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken import kotlin.math.max internal class GetAccountHistory( - accountId: ChainObject, - stopId: ChainObject = ObjectType.OPERATION_HISTORY_OBJECT.genericId, + accountId: AccountObjectId, + stopId: OperationHistoryObjectId = OperationHistoryObjectId(), limit: Int = REQ_LIMIT_MAX, - startId: ChainObject = ObjectType.OPERATION_HISTORY_OBJECT.genericId + startId: OperationHistoryObjectId = OperationHistoryObjectId() ) : BaseRequest>( ApiGroup.HISTORY, "get_account_history", TypeToken.getParameterized(List::class.java, OperationHistory::class.java).type, - listOf(accountId.objectId, stopId.objectId, max(0, limit), startId.objectId) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(startId.objectType == ObjectType.OPERATION_HISTORY_OBJECT) { "not a valid history object id" } - require(stopId.objectType == ObjectType.OPERATION_HISTORY_OBJECT) { "not a valid history object id" } - } -} + listOf(accountId, stopId, max(0, limit), startId) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountReferences.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountReferences.kt index 1ae0e1df..c655730a 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountReferences.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAccountReferences.kt @@ -1,14 +1,14 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetAccountReferences( - accountId: ChainObject -) : BaseRequest>( + accountId: AccountObjectId +) : BaseRequest>( ApiGroup.DATABASE, "get_account_references", - TypeToken.getParameterized(List::class.java, ChainObject::class.java).type, + TypeToken.getParameterized(List::class.java, AccountObjectId::class.java).type, listOf(accountId) ) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAssets.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAssets.kt index 9911288e..ee3224d4 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAssets.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAssets.kt @@ -1,21 +1,15 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Asset -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetAssets( - assets: List + assets: List ) : BaseRequest>( ApiGroup.DATABASE, "get_assets", TypeToken.getParameterized(List::class.java, Asset::class.java).type, listOf(assets) -) { - - init { - require(assets.all { it.objectType == ObjectType.ASSET_OBJECT }) { "not a valid asset object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetAssetsData.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetAssetsData.kt index b9fd46f3..523583cb 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetAssetsData.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetAssetsData.kt @@ -1,17 +1,12 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.AssetData -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AssetDataObjectId import com.google.gson.reflect.TypeToken internal class GetAssetsData( - assetDataIds: List + assetDataIds: List ) : GetObjects>( assetDataIds, TypeToken.getParameterized(List::class.java, AssetData::class.java).type -) { - init { - require(assetDataIds.all { it.objectType == ObjectType.ASSET_DYNAMIC_DATA }) { "not a valid asset dynamic data object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByConsumer.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByConsumer.kt index 29ace69a..8e7a10c6 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByConsumer.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByConsumer.kt @@ -1,19 +1,14 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Purchase import ch.decent.sdk.net.model.ApiGroup internal class GetBuyingByConsumer( - consumer: ChainObject + consumer: AccountObjectId ) : BaseRequest( ApiGroup.DATABASE, "get_buying_by_consumer", Purchase::class.java, listOf(consumer) -) { - init { - require(consumer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid asset object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByUri.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByUri.kt index 38b52960..57e6ed65 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByUri.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetBuyingByUri.kt @@ -1,20 +1,15 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Purchase import ch.decent.sdk.net.model.ApiGroup internal class GetBuyingByUri( - consumer: ChainObject, + consumer: AccountObjectId, uri: String ) : BaseRequest( ApiGroup.DATABASE, "get_buying_by_consumer_URI", Purchase::class.java, listOf(consumer, uri) -) { - init { - require(consumer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid asset object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetContentById.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetContentById.kt index 96a2f95b..e30c56ff 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetContentById.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetContentById.kt @@ -1,18 +1,12 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Content -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.ContentObjectId import com.google.gson.reflect.TypeToken internal class GetContentById( - contentId: List + contentId: List ) : GetObjects>( contentId, TypeToken.getParameterized(List::class.java, Content::class.java).type -) { - - init { - require(contentId.all { it.objectType == ObjectType.CONTENT_OBJECT }) { "not a valid content object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetFeedsByMiner.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetFeedsByMiner.kt index 1a49c823..6d16dff5 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetFeedsByMiner.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetFeedsByMiner.kt @@ -1,22 +1,17 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.MinerObjectId import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken -// todo what is this ? internal class GetFeedsByMiner( - account: ChainObject, + account: AccountObjectId, count: Int = REQ_LIMIT_MAX ) : BaseRequest>( ApiGroup.DATABASE, "get_feeds_by_miner", TypeToken.getParameterized(List::class.java, Any::class.java).type, listOf(account, count) -) { - init { - require(account.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid asset object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetFullAccounts.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetFullAccounts.kt index 0d28f5c6..d29de8d5 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetFullAccounts.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetFullAccounts.kt @@ -1,10 +1,9 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.FullAccount -import ch.decent.sdk.model.ObjectType -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.isValidId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken @@ -17,8 +16,8 @@ internal class GetFullAccounts( TypeToken.getParameterized(Map::class.java, String::class.java, FullAccount::class.java).type, listOf(namesOrIds, subscribe) ) { + init { - require(namesOrIds.all { (ChainObject.isValid(it) && it.toChainObject().objectType == ObjectType.ACCOUNT_OBJECT) || Account.isValidName(it) }) - { "not a valid account object id or name" } + require(namesOrIds.all { it.isValidId() || Account.isValidName(it) }) { "not a valid account object id or name" } } } diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetHistoryBuyingsByConsumer.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetHistoryBuyingsByConsumer.kt index 234830d4..4577422d 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetHistoryBuyingsByConsumer.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetHistoryBuyingsByConsumer.kt @@ -1,20 +1,15 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Purchase import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetHistoryBuyingsByConsumer( - consumer: ChainObject + consumer: AccountObjectId ) : BaseRequest>( ApiGroup.DATABASE, "get_buying_history_objects_by_consumer", TypeToken.getParameterized(List::class.java, Purchase::class.java).type, listOf(consumer) -) { - init { - require(consumer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetKeyReferences.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetKeyReferences.kt index e3c7da00..932846b0 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetKeyReferences.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetKeyReferences.kt @@ -1,15 +1,15 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.crypto.Address -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetKeyReferences( address: List
-) : BaseRequest>>( +) : BaseRequest>>( ApiGroup.DATABASE, "get_key_references", - TypeToken.getParameterized(List::class.java, TypeToken.getParameterized(List::class.java, ChainObject::class.java).type).type, + TypeToken.getParameterized(List::class.java, TypeToken.getParameterized(List::class.java, AccountObjectId::class.java).type).type, listOf(address) ) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetMessageObjects.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetMessageObjects.kt index f532bc28..d9358bdb 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetMessageObjects.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetMessageObjects.kt @@ -1,23 +1,17 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.MessageResponse -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetMessageObjects( - sender: ChainObject?, - receiver: ChainObject?, + sender: AccountObjectId?, + receiver: AccountObjectId?, maxCount: Int ) : BaseRequest>( ApiGroup.MESSAGING, "get_message_objects", TypeToken.getParameterized(List::class.java, MessageResponse::class.java).type, listOf(sender, receiver, maxCount) -) { - init { - require(sender?.objectType?.equals(ObjectType.ACCOUNT_OBJECT) ?: true) { "not a valid account object id" } - require(receiver?.objectType?.equals(ObjectType.ACCOUNT_OBJECT) ?: true) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetMinerByAccount.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetMinerByAccount.kt index b08bb61e..5850a90d 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetMinerByAccount.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetMinerByAccount.kt @@ -1,19 +1,14 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Miner -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.net.model.ApiGroup internal class GetMinerByAccount( - account: ChainObject + account: AccountObjectId ) : BaseRequest( ApiGroup.DATABASE, "get_miner_by_account", Miner::class.java, listOf(account) -) { - init { - require(account.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetMiners.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetMiners.kt index a960ca07..9a1aca51 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetMiners.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetMiners.kt @@ -1,19 +1,13 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.Miner -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.MinerObjectId import com.google.gson.reflect.TypeToken internal class GetMiners( - contentIds: List + contentIds: List ) : GetObjects>( contentIds.map { it }, TypeToken.getParameterized(List::class.java, Miner::class.java).type -) { - - init { - require(contentIds.all { it.objectType == ObjectType.MINER_OBJECT }) { "not a valid miner object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetNamedAccountBalances.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetNamedAccountBalances.kt index 948b2ef5..785d4e4b 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetNamedAccountBalances.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetNamedAccountBalances.kt @@ -2,14 +2,13 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetNamedAccountBalances( account: String, - assets: List = emptyList() + assets: List = emptyList() ) : BaseRequest>( ApiGroup.DATABASE, "get_named_account_balances", @@ -19,6 +18,5 @@ internal class GetNamedAccountBalances( init { require(Account.isValidName(account)) { "not a valid name: $account" } - require(assets.all { it.objectType == ObjectType.ASSET_OBJECT }) { "not a valid asset object id" } } } diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetObjects.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetObjects.kt index 2c9919b0..e17ab7b0 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetObjects.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetObjects.kt @@ -1,11 +1,11 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.ObjectId import ch.decent.sdk.net.model.ApiGroup import java.lang.reflect.Type internal open class GetObjects( - objects: List, + objects: List, returnClass: Type ) : BaseRequest( ApiGroup.DATABASE, diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetOpenBuyingsByConsumer.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetOpenBuyingsByConsumer.kt index 14fa9cba..8d9dec82 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetOpenBuyingsByConsumer.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetOpenBuyingsByConsumer.kt @@ -1,20 +1,15 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Purchase import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetOpenBuyingsByConsumer( - consumer: ChainObject + consumer: AccountObjectId ) : BaseRequest>( ApiGroup.DATABASE, "get_open_buyings_by_consumer", TypeToken.getParameterized(List::class.java, Purchase::class.java).type, listOf(consumer) -) { - init { - require(consumer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid asset object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetProposedTransactions.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetProposedTransactions.kt index 53300d1c..41a047fa 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetProposedTransactions.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetProposedTransactions.kt @@ -1,20 +1,15 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken // todo wait for proposal operation internal class GetProposedTransactions( - account: ChainObject + account: AccountObjectId ) : BaseRequest>( ApiGroup.DATABASE, "get_proposed_transactions", TypeToken.getParameterized(List::class.java, Any::class.java).type, listOf(account) -) { - init { - require(account.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetRelativeAccountHistory.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetRelativeAccountHistory.kt index 33e320c4..1e106a69 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetRelativeAccountHistory.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetRelativeAccountHistory.kt @@ -1,7 +1,6 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.OperationHistory import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX @@ -9,7 +8,7 @@ import com.google.gson.reflect.TypeToken import kotlin.math.max internal class GetRelativeAccountHistory( - accountId: ChainObject, + accountId: AccountObjectId, stop: Int = 0, limit: Int = REQ_LIMIT_MAX, start: Int = 0 @@ -17,10 +16,5 @@ internal class GetRelativeAccountHistory( ApiGroup.HISTORY, "get_relative_account_history", TypeToken.getParameterized(List::class.java, OperationHistory::class.java).type, - listOf(accountId.objectId, stop, max(0, limit), start) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} + listOf(accountId, stop, max(0, limit), start) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetRequiredFees.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetRequiredFees.kt index 51a26c27..1bf8b065 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetRequiredFees.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetRequiredFees.kt @@ -2,22 +2,17 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.DCoreConstants import ch.decent.sdk.model.AssetAmount +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.operation.BaseOperation -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetRequiredFees( operations: List, - assetId: ChainObject = DCoreConstants.DCT.id + assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID ) : BaseRequest>( ApiGroup.DATABASE, "get_required_fees", TypeToken.getParameterized(List::class.java, AssetAmount::class.java).type, listOf(operations.map { listOf(it.type.ordinal, it) }, assetId) -) { - init { - require(assetId.objectType == ObjectType.ASSET_OBJECT) { "not a valid asset object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetSeeder.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetSeeder.kt index bd8e8566..486191f5 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetSeeder.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetSeeder.kt @@ -1,20 +1,14 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Seeder import ch.decent.sdk.net.model.ApiGroup internal class GetSeeder( - accountId: ChainObject + accountId: AccountObjectId ) : BaseRequest( ApiGroup.DATABASE, "get_seeder", Seeder::class.java, listOf(accountId) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetSubscription.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetSubscription.kt index fa5d6a5b..aecdbfc3 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetSubscription.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetSubscription.kt @@ -1,19 +1,14 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.Subscription +import ch.decent.sdk.model.SubscriptionObjectId import ch.decent.sdk.net.model.ApiGroup internal class GetSubscription( - subscriptionId: ChainObject + subscriptionId: SubscriptionObjectId ) : BaseRequest( ApiGroup.DATABASE, "get_subscription", Subscription::class.java, listOf(subscriptionId) -) { - init { - require(subscriptionId.objectType == ObjectType.SUBSCRIPTION_OBJECT) { "not a valid subscription object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetVestingBalances.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetVestingBalances.kt index e5d0251e..b1ff9b3a 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/GetVestingBalances.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetVestingBalances.kt @@ -1,21 +1,15 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.VestingBalance import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class GetVestingBalances( - accountId: ChainObject + accountId: AccountObjectId ) : BaseRequest>( ApiGroup.DATABASE, "get_vesting_balances", TypeToken.getParameterized(List::class.java, VestingBalance::class.java).type, - listOf(accountId.objectId) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} + listOf(accountId) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByAuthor.kt b/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByAuthor.kt index 43942339..89a13ecf 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByAuthor.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByAuthor.kt @@ -1,22 +1,16 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Subscription import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class ListActiveSubscriptionsByAuthor( - accountId: ChainObject, + accountId: AccountObjectId, count: Int ) : BaseRequest>( ApiGroup.DATABASE, "list_active_subscriptions_by_author", TypeToken.getParameterized(List::class.java, Subscription::class.java).type, listOf(accountId, count) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByConsumer.kt b/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByConsumer.kt index d8c3a00f..dff5e3ba 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByConsumer.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/ListActiveSubscriptionsByConsumer.kt @@ -1,22 +1,16 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Subscription import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class ListActiveSubscriptionsByConsumer( - accountId: ChainObject, + accountId: AccountObjectId, count: Int ) : BaseRequest>( ApiGroup.DATABASE, "list_active_subscriptions_by_consumer", TypeToken.getParameterized(List::class.java, Subscription::class.java).type, listOf(accountId, count) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/ListPublishingManagers.kt b/library/src/main/java/ch/decent/sdk/net/model/request/ListPublishingManagers.kt index b2d0a673..c9da4868 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/ListPublishingManagers.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/ListPublishingManagers.kt @@ -1,6 +1,7 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.PublisherObjectId import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken @@ -8,9 +9,9 @@ import com.google.gson.reflect.TypeToken internal class ListPublishingManagers( lowerBound: String, limit: Int = REQ_LIMIT_MAX -) : BaseRequest>( +) : BaseRequest>( ApiGroup.DATABASE, "list_publishing_managers", - TypeToken.getParameterized(List::class.java, ChainObject::class.java).type, + TypeToken.getParameterized(List::class.java, AccountObjectId::class.java).type, listOf(lowerBound, limit) ) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByAuthor.kt b/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByAuthor.kt index 0f879f13..f032b364 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByAuthor.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByAuthor.kt @@ -1,22 +1,16 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Subscription import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class ListSubscriptionsByAuthor( - accountId: ChainObject, + accountId: AccountObjectId, count: Int ) : BaseRequest>( ApiGroup.DATABASE, "list_subscriptions_by_author", TypeToken.getParameterized(List::class.java, Subscription::class.java).type, listOf(accountId, count) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByConsumer.kt b/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByConsumer.kt index 1c0b574a..61a8bc3a 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByConsumer.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/ListSubscriptionsByConsumer.kt @@ -1,22 +1,16 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Subscription import ch.decent.sdk.net.model.ApiGroup import com.google.gson.reflect.TypeToken internal class ListSubscriptionsByConsumer( - accountId: ChainObject, + accountId: AccountObjectId, count: Int ) : BaseRequest>( ApiGroup.DATABASE, "list_subscriptions_by_consumer", TypeToken.getParameterized(List::class.java, Subscription::class.java).type, listOf(accountId, count) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/LookupAccounts.kt b/library/src/main/java/ch/decent/sdk/net/model/request/LookupAccounts.kt index 34aba414..d7396da1 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/LookupAccounts.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/LookupAccounts.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K import com.google.gson.reflect.TypeToken @@ -8,9 +8,9 @@ import com.google.gson.reflect.TypeToken internal class LookupAccounts( lowerBound: String, limit: Int = REQ_LIMIT_MAX_1K -) : BaseRequest>( +) : BaseRequest>( ApiGroup.DATABASE, "lookup_accounts", - TypeToken.getParameterized(Map::class.java, String::class.java, ChainObject::class.java).type, + TypeToken.getParameterized(Map::class.java, String::class.java, AccountObjectId::class.java).type, listOf(lowerBound, limit) ) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/LookupMiners.kt b/library/src/main/java/ch/decent/sdk/net/model/request/LookupMiners.kt deleted file mode 100644 index 03f7c3f7..00000000 --- a/library/src/main/java/ch/decent/sdk/net/model/request/LookupMiners.kt +++ /dev/null @@ -1,16 +0,0 @@ -package ch.decent.sdk.net.model.request - -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.net.model.ApiGroup -import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K -import com.google.gson.reflect.TypeToken - -internal class LookupMiners( - lowerBound: String, - limit: Int = REQ_LIMIT_MAX_1K -) : BaseRequest>( - ApiGroup.DATABASE, - "lookup_miners", - TypeToken.getParameterized(Map::class.java, String::class.java, ChainObject::class.java).type, - listOf(lowerBound, limit) -) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/RestoreEncryptionKey.kt b/library/src/main/java/ch/decent/sdk/net/model/request/RestoreEncryptionKey.kt index 496d47da..57d8bb72 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/RestoreEncryptionKey.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/RestoreEncryptionKey.kt @@ -1,21 +1,15 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.model.PubKey +import ch.decent.sdk.model.PurchaseObjectId import ch.decent.sdk.net.model.ApiGroup internal class RestoreEncryptionKey( elGamalPrivate: PubKey, - purchaseId: ChainObject + purchaseId: PurchaseObjectId ) : BaseRequest( ApiGroup.DATABASE, "restore_encryption_key", String::class.java, listOf(elGamalPrivate, purchaseId) -) { - - init { - require(purchaseId.objectType == ObjectType.PURCHASE_OBJECT) { "not a valid purchase object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountBalanceHistory.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountBalanceHistory.kt index 5aaa2149..919a1647 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountBalanceHistory.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountBalanceHistory.kt @@ -1,16 +1,16 @@ package ch.decent.sdk.net.model.request +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.BalanceChange -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken internal class SearchAccountBalanceHistory( - accountId: ChainObject, - assets: List = emptyList(), - recipientAccount: ChainObject? = null, + accountId: AccountObjectId, + assets: List = emptyList(), + recipientAccount: AccountObjectId? = null, fromBlock: Long = 0, toBlock: Long = 0, startOffset: Long = 0, @@ -20,10 +20,4 @@ internal class SearchAccountBalanceHistory( "search_account_balance_history", TypeToken.getParameterized(List::class.java, BalanceChange::class.java).type, listOf(accountId, assets, recipientAccount, fromBlock, toBlock, startOffset, limit) -) { - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(assets.all { it.objectType == ObjectType.ASSET_OBJECT }) { "not a valid asset object id" } - require(recipientAccount?.objectType?.equals(ObjectType.ACCOUNT_OBJECT) ?: true) { "not a valid account object id" } - } -} +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountHistory.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountHistory.kt index 9a478881..3d9fb484 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountHistory.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccountHistory.kt @@ -1,27 +1,23 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.NullObjectId import ch.decent.sdk.model.SearchAccountHistoryOrder import ch.decent.sdk.model.TransactionDetail +import ch.decent.sdk.model.TransactionDetailObjectId import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken +@Deprecated(message = "use SearchAccountBalanceHistory") internal class SearchAccountHistory( - accountId: ChainObject, + accountId: AccountObjectId, order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, - startId: ChainObject = ObjectType.NULL_OBJECT.genericId, + startId: TransactionDetailObjectId? = null, limit: Int = REQ_LIMIT_MAX ) : BaseRequest>( ApiGroup.DATABASE, "search_account_history", TypeToken.getParameterized(List::class.java, TransactionDetail::class.java).type, - listOf(accountId.objectId, order.value, startId.objectId, limit) -) { - - init { - require(accountId.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(startId == ObjectType.NULL_OBJECT.genericId || startId.objectType == ObjectType.TRANSACTION_DETAIL_OBJECT) { "not a valid null or transaction detail object id" } - } -} + listOf(accountId, order.value, startId ?: NullObjectId, limit) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccounts.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccounts.kt index fbae6ffc..74ed6da3 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccounts.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchAccounts.kt @@ -1,8 +1,8 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.NullObjectId import ch.decent.sdk.model.SearchAccountsOrder import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K @@ -11,15 +11,11 @@ import com.google.gson.reflect.TypeToken internal class SearchAccounts( searchTerm: String, order: SearchAccountsOrder = SearchAccountsOrder.NAME_DESC, - id: ChainObject = ObjectType.NULL_OBJECT.genericId, + id: AccountObjectId? = null, limit: Int = REQ_LIMIT_MAX_1K ) : BaseRequest>( ApiGroup.DATABASE, "search_accounts", TypeToken.getParameterized(List::class.java, Account::class.java).type, - listOf(searchTerm, order, id, limit) -) { - init { - require(id.objectType == ObjectType.NULL_OBJECT || id.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - } -} + listOf(searchTerm, order.value, id ?: NullObjectId, limit) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchBuyings.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchBuyings.kt index 2c72e57b..c41fe4ca 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchBuyings.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchBuyings.kt @@ -1,28 +1,23 @@ package ch.decent.sdk.net.model.request -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.NullObjectId import ch.decent.sdk.model.Purchase +import ch.decent.sdk.model.PurchaseObjectId import ch.decent.sdk.model.SearchPurchasesOrder import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken internal class SearchBuyings( - consumer: ChainObject, + consumer: AccountObjectId, order: SearchPurchasesOrder = SearchPurchasesOrder.PURCHASED_DESC, - startId: ChainObject = ObjectType.NULL_OBJECT.genericId, + startId: PurchaseObjectId? = null, term: String = "", limit: Int = REQ_LIMIT_MAX ) : BaseRequest>( ApiGroup.DATABASE, "get_buying_objects_by_consumer", TypeToken.getParameterized(List::class.java, Purchase::class.java).type, - listOf(consumer.objectId, order.value, startId.objectId, term, limit) -) { - - init { - require(consumer.objectType == ObjectType.ACCOUNT_OBJECT) { "not a valid account object id" } - require(startId == ObjectType.NULL_OBJECT.genericId || startId.objectType == ObjectType.PURCHASE_OBJECT) { "not a valid null or purchase object id" } - } -} + listOf(consumer, order.value, startId ?: NullObjectId, term, limit) +) diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchContent.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchContent.kt index 1976be42..ec070740 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchContent.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchContent.kt @@ -1,9 +1,8 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.Content -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.ContentObjectId +import ch.decent.sdk.model.ContentSummary import ch.decent.sdk.model.SearchContentOrder import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX @@ -15,17 +14,16 @@ internal class SearchContent( user: String, regionCode: String, type: String, - startId: ChainObject = ObjectType.NULL_OBJECT.genericId, + startId: ContentObjectId? = null, limit: Int = REQ_LIMIT_MAX -) : BaseRequest>( +) : BaseRequest>( ApiGroup.DATABASE, "search_content", - TypeToken.getParameterized(List::class.java, Content::class.java).type, + TypeToken.getParameterized(List::class.java, ContentSummary::class.java).type, listOf(term, order.value, user, regionCode, type, startId, limit) ) { init { require(Account.isValidName(user) || user.isBlank()) { "not a valid account name" } - require(startId == ObjectType.NULL_OBJECT.genericId || startId.objectType == ObjectType.CONTENT_OBJECT) { "not a valid null or content object id" } } } diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchFeedback.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchFeedback.kt index 80b21a0d..d739e5ad 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchFeedback.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchFeedback.kt @@ -1,9 +1,9 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.NullObjectId import ch.decent.sdk.model.Purchase +import ch.decent.sdk.model.PurchaseObjectId import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX import com.google.gson.reflect.TypeToken @@ -11,17 +11,16 @@ import com.google.gson.reflect.TypeToken internal class SearchFeedback( user: String?, uri: String, - startId: ChainObject = ObjectType.NULL_OBJECT.genericId, + startId: PurchaseObjectId? = null, count: Int = REQ_LIMIT_MAX ) : BaseRequest>( ApiGroup.DATABASE, "search_feedback", TypeToken.getParameterized(List::class.java, Purchase::class.java).type, - listOf(user, uri, startId, count) + listOf(user, uri, startId ?: NullObjectId, count) ) { init { require(user?.let { Account.isValidName(it) } ?: true) { "not a valid account name" } - require(startId == ObjectType.NULL_OBJECT.genericId || startId.objectType == ObjectType.PURCHASE_OBJECT) { "not a valid null or purchase object id" } } } diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/SearchMinerVoting.kt b/library/src/main/java/ch/decent/sdk/net/model/request/SearchMinerVoting.kt index 69a5365b..ed18e3c1 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/SearchMinerVoting.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/SearchMinerVoting.kt @@ -1,9 +1,9 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.MinerObjectId import ch.decent.sdk.model.MinerVotingInfo -import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.NullObjectId import ch.decent.sdk.model.SearchMinerVotingOrder import ch.decent.sdk.net.model.ApiGroup import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K @@ -14,17 +14,16 @@ internal class SearchMinerVoting( searchTerm: String, onlyMyVotes: Boolean = false, order: SearchMinerVotingOrder = SearchMinerVotingOrder.NAME_DESC, - id: ChainObject? = null, + id: MinerObjectId? = null, limit: Int = REQ_LIMIT_MAX_1K ) : BaseRequest>( ApiGroup.DATABASE, "search_miner_voting", TypeToken.getParameterized(List::class.java, MinerVotingInfo::class.java).type, - listOf(accountName, searchTerm, onlyMyVotes, order, id, limit) + listOf(accountName, searchTerm, onlyMyVotes, order.value, id ?: NullObjectId, limit) ) { init { require(accountName?.let { Account.isValidName(it) } ?: true) { "not a valid account name" } - require(id?.objectType?.equals(ObjectType.MINER_OBJECT) ?: true) { "not a valid miner object id" } } } diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/VerifyAccountAuthority.kt b/library/src/main/java/ch/decent/sdk/net/model/request/VerifyAccountAuthority.kt index a9af1a47..86b92032 100644 --- a/library/src/main/java/ch/decent/sdk/net/model/request/VerifyAccountAuthority.kt +++ b/library/src/main/java/ch/decent/sdk/net/model/request/VerifyAccountAuthority.kt @@ -2,7 +2,10 @@ package ch.decent.sdk.net.model.request import ch.decent.sdk.crypto.Address import ch.decent.sdk.model.Account -import ch.decent.sdk.model.ChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.ObjectId +import ch.decent.sdk.model.ObjectType +import ch.decent.sdk.model.isValidId import ch.decent.sdk.net.model.ApiGroup internal class VerifyAccountAuthority( @@ -15,6 +18,6 @@ internal class VerifyAccountAuthority( listOf(nameOrId, keys) ) { init { - require(Account.isValidName(nameOrId) || ChainObject.isValid(nameOrId)) { "not a valid account name or id" } + require(Account.isValidName(nameOrId) || nameOrId.isValidId()) { "not a valid account name or id" } } } diff --git a/library/src/main/java/ch/decent/sdk/net/serialization/Serializer.kt b/library/src/main/java/ch/decent/sdk/net/serialization/Serializer.kt index eba65bd6..4d104bd2 100644 --- a/library/src/main/java/ch/decent/sdk/net/serialization/Serializer.kt +++ b/library/src/main/java/ch/decent/sdk/net/serialization/Serializer.kt @@ -25,13 +25,13 @@ import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.AssetOptions import ch.decent.sdk.model.AuthMap import ch.decent.sdk.model.Authority -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.CoAuthors import ch.decent.sdk.model.CustodyData import ch.decent.sdk.model.ExchangeRate import ch.decent.sdk.model.KeyPart import ch.decent.sdk.model.Memo import ch.decent.sdk.model.MonitoredAssetOptions +import ch.decent.sdk.model.ObjectId import ch.decent.sdk.model.PubKey import ch.decent.sdk.model.Publishing import ch.decent.sdk.model.RegionalPrice @@ -65,6 +65,7 @@ import java.io.DataOutputStream import java.io.IOException import java.math.BigInteger import kotlin.reflect.KClass +import kotlin.reflect.full.superclasses /** *

Encodes signed and unsigned values using a common variable-length @@ -210,8 +211,8 @@ internal fun BigInteger.bytes(numBytes: Int): ByteArray { typealias Adapter = (BufferedSink, obj: T) -> Unit object Serializer { - private val chainObjectAdapter: Adapter = { buffer, obj -> - buffer.write(Varint.writeUnsignedVarLong(obj.instance.toLong())) + private val objectIdAdapter: Adapter = { buffer, obj -> + buffer.write(Varint.writeUnsignedVarLong(obj.instance)) } private val byteArrayAdapter: Adapter = { buffer, obj -> @@ -502,14 +503,14 @@ object Serializer { buffer.write(if (obj.isEmpty()) byteArrayOf(0) else Varint.writeUnsignedVarLong(obj.size.toLong())) obj.forEach { append(buffer, it) } } else { - val adapter = adapters[obj::class] as Adapter? + val adapter = (adapters[obj::class] ?: adapters[obj::class.superclasses.first()]) as Adapter? requireNotNull(adapter) { "missing adapter for ${obj::class}" } adapter(buffer, obj) } } private val adapters: Map, Adapter<*>> = mapOf( - ChainObject::class to chainObjectAdapter, + ObjectId::class to objectIdAdapter, ByteArray::class to byteArrayAdapter, String::class to stringAdapter, Address::class to addressAdapter, diff --git a/library/src/test/java/ch/decent/sdk/CrytpoTest.kt b/library/src/test/java/ch/decent/sdk/CrytpoTest.kt index 3cd09c91..d3522432 100644 --- a/library/src/test/java/ch/decent/sdk/CrytpoTest.kt +++ b/library/src/test/java/ch/decent/sdk/CrytpoTest.kt @@ -8,17 +8,16 @@ import ch.decent.sdk.crypto.Wallet import ch.decent.sdk.crypto.dpk import ch.decent.sdk.crypto.ecKey import ch.decent.sdk.model.Account +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.CipherKeyPairAdapter import ch.decent.sdk.model.ExtraKeysAdapter import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.utils.ElGamal.publicElGamal import ch.decent.sdk.utils.decryptAes import ch.decent.sdk.utils.decryptAesWithChecksum -import ch.decent.sdk.utils.encryptAes import ch.decent.sdk.utils.generateNonce import ch.decent.sdk.utils.hash512 -import ch.decent.sdk.utils.hex import ch.decent.sdk.utils.secret import ch.decent.sdk.utils.unhex import okio.Buffer @@ -26,9 +25,7 @@ import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should equal` import org.junit.Test import java.math.BigInteger -import java.nio.charset.Charset import java.security.MessageDigest -import kotlin.test.Ignore class CrytpoTest : TimeOutTest() { @@ -100,13 +97,13 @@ class CrytpoTest : TimeOutTest() { val pass = "quick brown fox jumped over a lazy dog" val key = ECKeyPair.fromBase58(private) // encryptAes(MessageDigest.getInstance("SHA-512").digest(pass.toByteArray()), private.toByteArray()).hex().print() - val wallet = Wallet.create(Credentials("1.2.30".toChainObject(), key), pass) + val wallet = Wallet.create(Credentials("1.2.30".toObjectId(), key), pass) Wallet.decrypt(wallet, pass).keyPair.private `should equal` key.private } @Test fun `encrypt private key as wallet file with empty password`() { val key = ECKeyPair.fromBase58(private) - val wallet = Wallet.create(Credentials("1.2.30".toChainObject(), key)) + val wallet = Wallet.create(Credentials("1.2.30".toObjectId(), key)) Wallet.decrypt(wallet).keyPair.private `should equal` key.private } @@ -120,7 +117,7 @@ class CrytpoTest : TimeOutTest() { } @Test fun `import dcore wallet`() { - val account = "1.2.30".toChainObject() + val account = "1.2.30".toObjectId() val json = """ { "version": 1, @@ -191,7 +188,7 @@ class CrytpoTest : TimeOutTest() { } @Test fun `dcore wallet export`() { - val credentials = Credentials("1.2.30".toChainObject(), "5Jd7zdvxXYNdUfnEXt5XokrE3zwJSs734yQ36a1YaqioRTGGLtn".dpk().ecKey()) + val credentials = Credentials("1.2.30".toObjectId(), "5Jd7zdvxXYNdUfnEXt5XokrE3zwJSs734yQ36a1YaqioRTGGLtn".dpk().ecKey()) val json = """ { "id": "1.2.30", diff --git a/library/src/test/java/ch/decent/sdk/Helpers.kt b/library/src/test/java/ch/decent/sdk/Helpers.kt index c0843ca2..80a9e43d 100644 --- a/library/src/test/java/ch/decent/sdk/Helpers.kt +++ b/library/src/test/java/ch/decent/sdk/Helpers.kt @@ -1,7 +1,8 @@ package ch.decent.sdk import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.net.TrustAllCerts import io.reactivex.Single import io.reactivex.observers.TestObserver @@ -19,8 +20,8 @@ object Helpers { .addInterceptor(HttpLoggingInterceptor { logger.info(it) }.setLevel(HttpLoggingInterceptor.Level.BODY)) .build() - @JvmStatic val account = "1.2.27".toChainObject() - @JvmStatic val account2 = "1.2.28".toChainObject() + @JvmStatic val account = "1.2.27".toObjectId() + @JvmStatic val account2 = "1.2.28".toObjectId() @JvmStatic val accountName = "public-account-9" @JvmStatic val accountName2 = "public-account-10" @JvmStatic val private = "5Hxwqx6JJUBYWjQNt8DomTNJ6r6YK8wDJym4CMAH1zGctFyQtzt" diff --git a/library/src/test/java/ch/decent/sdk/Scratchpad.kt b/library/src/test/java/ch/decent/sdk/Scratchpad.kt index 0a79a299..37b18539 100644 --- a/library/src/test/java/ch/decent/sdk/Scratchpad.kt +++ b/library/src/test/java/ch/decent/sdk/Scratchpad.kt @@ -3,11 +3,13 @@ package ch.decent.sdk import ch.decent.sdk.crypto.Address import ch.decent.sdk.crypto.DumpedPrivateKey import ch.decent.sdk.crypto.ECKeyPair +import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo import ch.decent.sdk.model.TransactionConfirmation import ch.decent.sdk.model.operation.TransferOperation +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.utils.hash512 import ch.decent.sdk.utils.hex import io.reactivex.Observable @@ -203,7 +205,6 @@ class Scratchpad { ) // op.bytes.hash256().print() // key.signature(op.bytes.hash256()).print() - } @Test fun `retry when`() { @@ -281,5 +282,9 @@ class Scratchpad { // b.BE().readUint16(2).should.equal(refNum); } + @Test fun `reflection`() { + "1.2.3".toObjectId().print() + } + } diff --git a/library/src/test/java/ch/decent/sdk/api/AssetApiTest.kt b/library/src/test/java/ch/decent/sdk/api/AssetApiTest.kt index 263bac48..23f40490 100644 --- a/library/src/test/java/ch/decent/sdk/api/AssetApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/AssetApiTest.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.api import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.net.model.request.PriceToDct import ch.decent.sdk.testCheck import org.junit.Test @@ -9,11 +9,11 @@ import org.junit.Test class AssetApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get asset for id`() { - api.assetApi.get("1.3.0".toChainObject()).testCheck() + api.assetApi.get("1.3.0".toObjectId()).testCheck() } @Test fun `should get assets for ids`() { - api.assetApi.getAll(listOf("1.3.0".toChainObject(), "1.3.1".toChainObject())).testCheck() + api.assetApi.getAll(listOf("1.3.0".toObjectId(), "1.3.1".toObjectId())).testCheck() } @Test fun `should get real supply`() { @@ -21,11 +21,11 @@ class AssetApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should get asset data for id`() { - api.assetApi.getAssetData("2.3.0".toChainObject()).testCheck() + api.assetApi.getAssetData("2.3.0".toObjectId()).testCheck() } @Test fun `should get assets data for id`() { - api.assetApi.getAssetsData(listOf("2.3.0".toChainObject(), "2.3.35".toChainObject())).testCheck() + api.assetApi.getAssetsData(listOf("2.3.0".toObjectId(), "2.3.35".toObjectId())).testCheck() } @Test fun `should list assets for lower bound symbol`() { @@ -45,13 +45,13 @@ class AssetApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should convert asset to DCT`() { - api.core.makeRequest(PriceToDct(AssetAmount(3, "1.3.33".toChainObject()))).testCheck { + api.core.makeRequest(PriceToDct(AssetAmount(3, "1.3.33".toObjectId()))).testCheck { assertComplete() assertNoErrors() assertValue { it.amount == 3000000L } } - api.assetApi.convertToDCT("1.3.33".toChainObject(), 3).testCheck { + api.assetApi.convertToDCT("1.3.33".toObjectId(), 3).testCheck { assertComplete() assertNoErrors() assertValue { it.amount == 3000000L } @@ -59,7 +59,7 @@ class AssetApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should convert asset from DCT`() { - api.assetApi.convertFromDCT("1.3.33".toChainObject(), 3000000).testCheck { + api.assetApi.convertFromDCT("1.3.33".toObjectId(), 3000000).testCheck { assertComplete() assertNoErrors() assertValue { it.amount == 3L } diff --git a/library/src/test/java/ch/decent/sdk/api/BalanceApiTest.kt b/library/src/test/java/ch/decent/sdk/api/BalanceApiTest.kt index 889ccd46..18918987 100644 --- a/library/src/test/java/ch/decent/sdk/api/BalanceApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/BalanceApiTest.kt @@ -1,14 +1,14 @@ package ch.decent.sdk.api import ch.decent.sdk.Helpers -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import io.reactivex.schedulers.Schedulers import org.junit.Test class BalanceApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get balance for account id`() { - val test = api.balanceApi.get(Helpers.account, "1.3.35".toChainObject()) + val test = api.balanceApi.get(Helpers.account, "1.3.35".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -28,7 +28,7 @@ class BalanceApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should get balance for account name`() { - val test = api.balanceApi.get(Helpers.accountName, "1.3.35".toChainObject()) + val test = api.balanceApi.get(Helpers.accountName, "1.3.35".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -97,4 +97,4 @@ class BalanceApiTest(channel: Channel) : BaseApiTest(channel) { .assertNoErrors() } -} \ No newline at end of file +} diff --git a/library/src/test/java/ch/decent/sdk/api/ContentApiTest.kt b/library/src/test/java/ch/decent/sdk/api/ContentApiTest.kt index b910d5d8..a3b1d229 100644 --- a/library/src/test/java/ch/decent/sdk/api/ContentApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/ContentApiTest.kt @@ -1,8 +1,8 @@ package ch.decent.sdk.api import ch.decent.sdk.Helpers -import ch.decent.sdk.model.ChainObject -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.ContentObjectId +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.utils.privateElGamal import io.reactivex.schedulers.Schedulers import org.junit.Test @@ -13,7 +13,7 @@ import org.junit.runners.Parameterized class ContentApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should generate content keys`() { - val test = api.contentApi.generateKeys(listOf(ChainObject.parse("1.2.17"), ChainObject.parse("1.2.18"))) + val test = api.contentApi.generateKeys(listOf("1.2.17".toObjectId(), "1.2.18".toObjectId())) .subscribeOn(Schedulers.newThread()) .test() @@ -23,7 +23,7 @@ class ContentApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should get content by id`() { - val test = api.contentApi.get("2.13.3".toChainObject()) + val test = api.contentApi.get("2.13.3".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -33,7 +33,7 @@ class ContentApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should get contents by ids`() { - val test = api.contentApi.getAll(listOf("2.13.3".toChainObject(), "2.13.4".toChainObject())) + val test = api.contentApi.getAll(listOf("2.13.3".toObjectId(), "2.13.4".toObjectId())) .subscribeOn(Schedulers.newThread()) .test() @@ -63,7 +63,7 @@ class ContentApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should restore content encryption key`() { - val test = api.contentApi.restoreEncryptionKey(Helpers.credentials.keyPair.privateElGamal(), "2.12.3".toChainObject()) + val test = api.contentApi.restoreEncryptionKey(Helpers.credentials.keyPair.privateElGamal(), "2.12.3".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -82,4 +82,4 @@ class ContentApiTest(channel: Channel) : BaseApiTest(channel) { test.assertComplete() .assertNoErrors() } -} \ No newline at end of file +} diff --git a/library/src/test/java/ch/decent/sdk/api/HistoryApiTest.kt b/library/src/test/java/ch/decent/sdk/api/HistoryApiTest.kt index 35cc832a..bb5ecdb4 100644 --- a/library/src/test/java/ch/decent/sdk/api/HistoryApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/HistoryApiTest.kt @@ -1,14 +1,14 @@ package ch.decent.sdk.api import ch.decent.sdk.Helpers -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import io.reactivex.schedulers.Schedulers import org.junit.Test class HistoryApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get account balance for op`() { - val test = api.historyApi.getOperation(Helpers.account, "1.7.980424".toChainObject()) + val test = api.historyApi.getOperation(Helpers.account, "1.7.980424".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -18,7 +18,7 @@ class HistoryApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should list account history`() { - val test = api.historyApi.listOperations("1.2.27".toChainObject()) + val test = api.historyApi.listOperations("1.2.27".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() diff --git a/library/src/test/java/ch/decent/sdk/api/MiningApiTest.kt b/library/src/test/java/ch/decent/sdk/api/MiningApiTest.kt index 274bb392..7b1f9d20 100644 --- a/library/src/test/java/ch/decent/sdk/api/MiningApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/MiningApiTest.kt @@ -2,7 +2,7 @@ package ch.decent.sdk.api import ch.decent.sdk.Helpers import ch.decent.sdk.model.VoteId -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import io.reactivex.schedulers.Schedulers import org.junit.Test @@ -29,7 +29,7 @@ class MiningApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `get feeds by miner`() { - val test = api.miningApi.getFeedsByMiner("1.2.4".toChainObject()) + val test = api.miningApi.getFeedsByMiner("1.2.4".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -39,7 +39,7 @@ class MiningApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `get miner by account`() { - val test = api.miningApi.getMinerByAccount("1.2.4".toChainObject()) + val test = api.miningApi.getMinerByAccount("1.2.4".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -59,7 +59,7 @@ class MiningApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `get miners by ids`() { - val test = api.miningApi.getMiners(listOf("1.4.2".toChainObject(), "1.4.3".toChainObject())) + val test = api.miningApi.getMiners(listOf("1.4.2".toObjectId(), "1.4.3".toObjectId())) .subscribeOn(Schedulers.newThread()) .test() diff --git a/library/src/test/java/ch/decent/sdk/api/OperationsTest.kt b/library/src/test/java/ch/decent/sdk/api/OperationsTest.kt index 2159761e..d4a811c1 100644 --- a/library/src/test/java/ch/decent/sdk/api/OperationsTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/OperationsTest.kt @@ -15,7 +15,7 @@ import ch.decent.sdk.model.RegionalPrice import ch.decent.sdk.model.Synopsis import ch.decent.sdk.model.operation.AssetClaimFeesOperation import ch.decent.sdk.model.operation.AssetFundPoolsOperation -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.testCheck import org.junit.After import org.junit.Before @@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory import org.threeten.bp.LocalDateTime @FixMethodOrder(MethodSorters.NAME_ASCENDING) +@Ignore class OperationsTest { companion object { @@ -77,7 +78,7 @@ class OperationsTest { // @Ignore @Test fun `accounts-4 should make a vote on a new account`() { api.accountApi.createCredentials(accountName, Helpers.private2) - .flatMap { api.miningApi.vote(it, listOf("1.4.4".toChainObject())) } + .flatMap { api.miningApi.vote(it, listOf("1.4.4".toObjectId())) } .testCheck() } @@ -95,7 +96,7 @@ class OperationsTest { // @Ignore @Test fun `content- should make a transfer to content`() { - api.contentApi.transfer(Helpers.credentials, "2.13.3".toChainObject(), AssetAmount(1), "transfer to content") + api.contentApi.transfer(Helpers.credentials, "2.13.3".toObjectId(), AssetAmount(1), "transfer to content") .testCheck() } @@ -200,7 +201,7 @@ class OperationsTest { } @Test fun `asset- should fund an asset pool from non-issuer account`() { - val op = AssetFundPoolsOperation(Helpers.account2, AssetAmount(0, "1.3.36".toChainObject()), AssetAmount(1)) + val op = AssetFundPoolsOperation(Helpers.account2, AssetAmount(0, "1.3.36".toObjectId()), AssetAmount(1)) api.broadcastApi.broadcastWithCallback(Helpers.private2.ecKey(), op) .testCheck() } @@ -210,11 +211,11 @@ class OperationsTest { Helpers.credentials, Helpers.accountName2, AssetAmount(1), - fee = Fee("1.3.40".toChainObject()) + fee = Fee("1.3.40".toObjectId()) ).testCheck { assertComplete() assertNoErrors() - assertValue { it.transaction.operations.single().fee.assetId == "1.3.40".toChainObject() } + assertValue { it.transaction.operations.single().fee.assetId == "1.3.40".toObjectId() } } } @@ -228,7 +229,7 @@ class OperationsTest { } @Test fun `asset- should claim an asset pool from non-issuer account is not allowed`() { - val op = AssetClaimFeesOperation(Helpers.account2, AssetAmount(0, "1.3.36"), AssetAmount(1)) + val op = AssetClaimFeesOperation(Helpers.account2, AssetAmount(0, "1.3.36".toObjectId()), AssetAmount(1)) api.broadcastApi.broadcastWithCallback(Helpers.private2.ecKey(), op) .testCheck { assertError(DCoreException::class.java) diff --git a/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt b/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt index 612cc9f7..e035d9a2 100644 --- a/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.api import ch.decent.sdk.model.Regions -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import io.reactivex.schedulers.Schedulers import org.junit.Test import org.junit.runner.RunWith @@ -11,7 +11,7 @@ import org.junit.runners.Parameterized class SeederApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get seeder by id`() { - val test = api.seedersApi.get("1.2.17".toChainObject()) + val test = api.seedersApi.get("1.2.17".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() @@ -59,4 +59,4 @@ class SeederApiTest(channel: Channel) : BaseApiTest(channel) { test.assertComplete() .assertNoErrors() } -} \ No newline at end of file +} diff --git a/library/src/test/java/ch/decent/sdk/api/ValidationApiTest.kt b/library/src/test/java/ch/decent/sdk/api/ValidationApiTest.kt index dc3fd25d..a3e1f294 100644 --- a/library/src/test/java/ch/decent/sdk/api/ValidationApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/ValidationApiTest.kt @@ -5,7 +5,7 @@ import ch.decent.sdk.crypto.address import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.operation.OperationType import ch.decent.sdk.model.operation.TransferOperation -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import io.reactivex.schedulers.Schedulers import org.junit.Test @@ -68,7 +68,7 @@ class ValidationApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should get fee for transfer OP`() { - val test = api.validationApi.getFeeForType(OperationType.TRANSFER2_OPERATION, "1.3.35".toChainObject()) + val test = api.validationApi.getFeeForType(OperationType.TRANSFER2_OPERATION, "1.3.35".toObjectId()) .subscribeOn(Schedulers.newThread()) .test() diff --git a/library/src/test/java/ch/decent/sdk/api/java/ApiTest.java b/library/src/test/java/ch/decent/sdk/api/java/ApiTest.java index cd815dac..18e2d4fa 100644 --- a/library/src/test/java/ch/decent/sdk/api/java/ApiTest.java +++ b/library/src/test/java/ch/decent/sdk/api/java/ApiTest.java @@ -45,34 +45,34 @@ public void init() { @SuppressWarnings("deprecation") @Test public void accountApiTest() { - api.getAccountApi().get(ObjectType.ACCOUNT_OBJECT.getGenericId()); - api.getAccountApi().getAll(Collections.singletonList(ObjectType.ACCOUNT_OBJECT.getGenericId())); + api.getAccountApi().get(new AccountObjectId()); + api.getAccountApi().getAll(Collections.singletonList(new AccountObjectId())); api.getAccountApi().getByName("reference"); api.getAccountApi().getAllByNames(Collections.singletonList("a name")); api.getAccountApi().countAll(); api.getAccountApi().createCredentials("u961279ec8b7ae7bd62f304f7c1c3d345", "5Jd7zdvxXYNdUfnEXt5XokrE3zwJSs734yQ36a1YaqioRTGGLtn"); api.getAccountApi().findAll("term"); api.getAccountApi().findAll("term", SearchAccountsOrder.ID_ASC); - api.getAccountApi().findAll("term", SearchAccountsOrder.ID_ASC, ObjectType.NULL_OBJECT.getGenericId()); - api.getAccountApi().findAll("term", SearchAccountsOrder.ID_ASC, ObjectType.NULL_OBJECT.getGenericId(), 10); - api.getAccountApi().findAllReferencesByAccount(ObjectType.ACCOUNT_OBJECT.getGenericId()); + api.getAccountApi().findAll("term", SearchAccountsOrder.ID_ASC, null); + api.getAccountApi().findAll("term", SearchAccountsOrder.ID_ASC, null, 10); + api.getAccountApi().findAllReferencesByAccount(new AccountObjectId()); api.getAccountApi().findAllReferencesByKeys(Collections.singletonList(Address.decode("DCT6MA5TQQ6UbMyMaLPmPXE2Syh5G3ZVhv5SbFedqLPqdFChSeqTz"))); api.getAccountApi().getFullAccounts(Collections.singletonList("nameorid")); api.getAccountApi().getFullAccounts(Collections.singletonList("nameorid"), true); api.getAccountApi().listAllRelative("abc"); api.getAccountApi().listAllRelative("abc", 10); - api.getAccountApi().searchAccountHistory(ObjectType.ACCOUNT_OBJECT.getGenericId()); - api.getAccountApi().searchAccountHistory(ObjectType.ACCOUNT_OBJECT.getGenericId(), ObjectType.NULL_OBJECT.getGenericId()); - api.getAccountApi().searchAccountHistory(ObjectType.ACCOUNT_OBJECT.getGenericId(), ObjectType.NULL_OBJECT.getGenericId(), SearchAccountHistoryOrder.FROM_ASC); - api.getAccountApi().searchAccountHistory(ObjectType.ACCOUNT_OBJECT.getGenericId(), ObjectType.NULL_OBJECT.getGenericId(), SearchAccountHistoryOrder.FROM_ASC, 10); + api.getAccountApi().searchAccountHistory(new AccountObjectId()); + api.getAccountApi().searchAccountHistory(new AccountObjectId(), null); + api.getAccountApi().searchAccountHistory(new AccountObjectId(), null, SearchAccountHistoryOrder.FROM_ASC); + api.getAccountApi().searchAccountHistory(new AccountObjectId(), null, SearchAccountHistoryOrder.FROM_ASC, 10); } @Test public void AssetApiTest() { - api.getAssetApi().convertToDCT(ChainObject.parse("1.3.33"), 10); - api.getAssetApi().convertFromDCT(ChainObject.parse("1.3.33"), 10); - api.getAssetApi().get(ObjectType.ASSET_OBJECT.getGenericId()); - api.getAssetApi().getAll(Arrays.asList(ObjectType.ASSET_OBJECT.getGenericId(), ObjectType.ASSET_OBJECT.getGenericId())); + api.getAssetApi().convertToDCT(new AssetObjectId(33), 10); + api.getAssetApi().convertFromDCT(new AssetObjectId(33), 10); + api.getAssetApi().get(new AssetObjectId()); + api.getAssetApi().getAll(Arrays.asList(new AssetObjectId(), new AssetObjectId())); api.getAssetApi().getAllByName(Arrays.asList("dct", "dct")); api.getAssetApi().getByName("dct"); api.getAssetApi().getRealSupply(); @@ -82,16 +82,16 @@ public void AssetApiTest() { @Test public void BalanceApiTest() { - api.getBalanceApi().get(ObjectType.ACCOUNT_OBJECT.getGenericId(), ObjectType.ASSET_OBJECT.getGenericId()); - api.getBalanceApi().get("account.name", ObjectType.ASSET_OBJECT.getGenericId()); + api.getBalanceApi().get(new AccountObjectId(), new AssetObjectId()); + api.getBalanceApi().get("account.name", new AssetObjectId()); api.getBalanceApi().getAll("account.name"); - api.getBalanceApi().getAll("account.name", Arrays.asList(ObjectType.ASSET_OBJECT.getGenericId(), ObjectType.ASSET_OBJECT.getGenericId())); - api.getBalanceApi().getAll(ObjectType.ACCOUNT_OBJECT.getGenericId()); - api.getBalanceApi().getAll(ObjectType.ACCOUNT_OBJECT.getGenericId(), Arrays.asList(ObjectType.ASSET_OBJECT.getGenericId(), ObjectType.ASSET_OBJECT.getGenericId())); - api.getBalanceApi().getAllVesting(ObjectType.ACCOUNT_OBJECT.getGenericId()); - api.getBalanceApi().getWithAsset(ObjectType.ACCOUNT_OBJECT.getGenericId(), "DCT"); + api.getBalanceApi().getAll("account.name", Arrays.asList(new AssetObjectId(), new AssetObjectId())); + api.getBalanceApi().getAll(new AccountObjectId()); + api.getBalanceApi().getAll(new AccountObjectId(), Arrays.asList(new AssetObjectId(), new AssetObjectId())); + api.getBalanceApi().getAllVesting(new AccountObjectId()); + api.getBalanceApi().getWithAsset(new AccountObjectId(), "DCT"); api.getBalanceApi().getWithAsset("account.name", "DCT"); - api.getBalanceApi().getAllWithAsset(ObjectType.ACCOUNT_OBJECT.getGenericId(), Arrays.asList("DCT", "DCT")); + api.getBalanceApi().getAllWithAsset(new AccountObjectId(), Arrays.asList("DCT", "DCT")); api.getBalanceApi().getAllWithAsset("account.name", Arrays.asList("DCT", "DCT")); } @@ -102,7 +102,7 @@ public void BlockApiTest() { @Test public void BroadcastApiTest() { ECKeyPair keyPair = ECKeyPair.fromBase58(Helpers.getPrivate()); - TransferOperation operation = new TransferOperation(ObjectType.ACCOUNT_OBJECT.getGenericId(), ObjectType.ACCOUNT_OBJECT.getGenericId(), new AssetAmount(1)); + TransferOperation operation = new TransferOperation(new AccountObjectId(), new AccountObjectId(), new AssetAmount(1)); Transaction trx = new Transaction(Collections.singletonList(operation), LocalDateTime.now(), 0, 0, "fff4") .withSignature(keyPair); api.getBroadcastApi().broadcast(trx); @@ -128,7 +128,7 @@ public void BroadcastApiTest() { @Test public void ContentApiTest() { api.getContentApi().get("uri"); - api.getContentApi().get(ObjectType.CONTENT_OBJECT.getGenericId()); + api.getContentApi().get(new ContentObjectId()); } @Test @@ -137,17 +137,17 @@ public void GeneralApiTest() { @Test public void HistoryApiTest() { - ChainObject historyObj = ObjectType.OPERATION_HISTORY_OBJECT.getGenericId(); - api.getHistoryApi().listOperations(ObjectType.ACCOUNT_OBJECT.getGenericId()); - api.getHistoryApi().listOperations(ObjectType.ACCOUNT_OBJECT.getGenericId(), historyObj); - api.getHistoryApi().listOperations(ObjectType.ACCOUNT_OBJECT.getGenericId(), historyObj, historyObj); - api.getHistoryApi().listOperations(ObjectType.ACCOUNT_OBJECT.getGenericId(), historyObj, historyObj, 100); + OperationHistoryObjectId historyObj = new OperationHistoryObjectId(); + api.getHistoryApi().listOperations(new AccountObjectId()); + api.getHistoryApi().listOperations(new AccountObjectId(), historyObj); + api.getHistoryApi().listOperations(new AccountObjectId(), historyObj, historyObj); + api.getHistoryApi().listOperations(new AccountObjectId(), historyObj, historyObj, 100); } @Test public void MiningApiTest() { api.getMiningApi().getMiners(); - api.getMiningApi().getMiners(Arrays.asList(ObjectType.MINER_OBJECT.getGenericId(), ObjectType.MINER_OBJECT.getGenericId())); + api.getMiningApi().getMiners(Arrays.asList(new MinerObjectId(), new MinerObjectId())); api.getMiningApi().listMinersRelative(); api.getMiningApi().listMinersRelative("lookup"); api.getMiningApi().listMinersRelative("lookup", 1); @@ -156,16 +156,16 @@ public void MiningApiTest() { /* @Test public void OperationsHelperTest() { - Credentials credentials = new Credentials(ObjectType.ACCOUNT_OBJECT.getGenericId(), Helpers.getPrivate()); - AssetAmount fee = new AssetAmount(BigInteger.valueOf(50), ObjectType.ASSET_OBJECT.getGenericId()); - api.getOperationsHelper().createBuyContent(credentials, ObjectType.CONTENT_OBJECT.getGenericId()); + Credentials credentials = new Credentials(new AccountObjectId(, Helpers.getPrivate()); + AssetAmount fee = new AssetAmount(BigInteger.valueOf(50), new AssetObjectId()); + api.getOperationsHelper().createBuyContent(credentials, new ContentObjectId(); api.getOperationsHelper().createBuyContent(credentials, "uri"); api.getOperationsHelper().createTransfer(credentials, "reference", new AssetAmount(10)); api.getOperationsHelper().createTransfer(credentials, "reference", new AssetAmount(10), fee); api.getOperationsHelper().createTransfer(credentials, "reference", new AssetAmount(10), "memo"); api.getOperationsHelper().createTransfer(credentials, "reference", new AssetAmount(10), "public memo", false); api.getOperationsHelper().createTransfer(credentials, "reference", new AssetAmount(10), "public memo", false, fee); - api.getOperationsHelper().createVote(ObjectType.ACCOUNT_OBJECT.getGenericId(), Arrays.asList(ObjectType.MINER_OBJECT.getGenericId(), ObjectType.MINER_OBJECT.getGenericId())); + api.getOperationsHelper().createVote(new AccountObjectId(, Arrays.asList(new MinerObjectId(, new MinerObjectId()); api.getOperationsHelper().transfer(credentials, "reference", new AssetAmount(10)); api.getOperationsHelper().transfer(credentials, "reference", new AssetAmount(10), fee); api.getOperationsHelper().transfer(credentials, "reference", new AssetAmount(10), "memo"); @@ -176,12 +176,12 @@ public void OperationsHelperTest() { @Test public void PurchaseApiTest() { - api.getPurchaseApi().get(ObjectType.ACCOUNT_OBJECT.getGenericId(), "uri"); - api.getPurchaseApi().findAll(ObjectType.ACCOUNT_OBJECT.getGenericId()); - api.getPurchaseApi().findAll(ObjectType.ACCOUNT_OBJECT.getGenericId(), "term"); - api.getPurchaseApi().findAll(ObjectType.ACCOUNT_OBJECT.getGenericId(), "term", ObjectType.PURCHASE_OBJECT.getGenericId()); - api.getPurchaseApi().findAll(ObjectType.ACCOUNT_OBJECT.getGenericId(), "term", ObjectType.PURCHASE_OBJECT.getGenericId(), SearchPurchasesOrder.PURCHASED_DESC); - api.getPurchaseApi().findAll(ObjectType.ACCOUNT_OBJECT.getGenericId(), "term", ObjectType.PURCHASE_OBJECT.getGenericId(), SearchPurchasesOrder.PURCHASED_DESC, 100); + api.getPurchaseApi().get(new AccountObjectId(), "uri"); + api.getPurchaseApi().findAll(new AccountObjectId()); + api.getPurchaseApi().findAll(new AccountObjectId(), "term"); + api.getPurchaseApi().findAll(new AccountObjectId(), "term", new PurchaseObjectId()); + api.getPurchaseApi().findAll(new AccountObjectId(), "term", new PurchaseObjectId(), SearchPurchasesOrder.PURCHASED_DESC); + api.getPurchaseApi().findAll(new AccountObjectId(), "term", new PurchaseObjectId(), SearchPurchasesOrder.PURCHASED_DESC, 100); } @Test diff --git a/library/src/test/java/ch/decent/sdk/model/AssetTest.kt b/library/src/test/java/ch/decent/sdk/model/AssetTest.kt index 6cf55ae9..f7b57300 100644 --- a/library/src/test/java/ch/decent/sdk/model/AssetTest.kt +++ b/library/src/test/java/ch/decent/sdk/model/AssetTest.kt @@ -10,14 +10,14 @@ import kotlin.test.assertNull class AssetTest { - private val otherCoin = "1.3.1".toChainObject() + private val otherCoin = "1.3.1".toObjectId() - private fun testAsset(assetId: ChainObject, base: AssetAmount, quote: AssetAmount) = + private fun testAsset(assetId: AssetObjectId, base: AssetAmount, quote: AssetAmount) = Asset( assetId, "TEST", 0, - ObjectType.ACCOUNT_OBJECT.genericId, + AccountObjectId(), "", AssetOptions( exchangeRate = ExchangeRate( @@ -26,11 +26,11 @@ class AssetTest { ), exchangeable = true ), - ObjectType.ASSET_DYNAMIC_DATA.genericId + AssetDataObjectId() ) private fun testConversionToDct( - assetId: ChainObject, + assetId: AssetObjectId, amountToConvert: Long, base: AssetAmount, quote: AssetAmount, @@ -45,7 +45,7 @@ class AssetTest { } private fun testConversionFromDct( - assetId: ChainObject, + assetId: AssetObjectId, amountToConvert: Long, base: AssetAmount, quote: AssetAmount, diff --git a/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt b/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt index 09f9e712..6c0adeb4 100644 --- a/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt +++ b/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt @@ -9,7 +9,6 @@ import ch.decent.sdk.crypto.address import ch.decent.sdk.model.Account import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.AssetOptions -import ch.decent.sdk.model.ChainObject import ch.decent.sdk.model.ExchangeRate import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo @@ -35,7 +34,7 @@ import ch.decent.sdk.model.operation.PurchaseContentOperation import ch.decent.sdk.model.operation.RemoveContentOperation import ch.decent.sdk.model.operation.SendMessageOperation import ch.decent.sdk.model.operation.TransferOperation -import ch.decent.sdk.model.toChainObject +import ch.decent.sdk.model.toObjectId import ch.decent.sdk.net.serialization.Serializer import ch.decent.sdk.utils.hex import org.amshove.kluent.`should be equal to` @@ -51,8 +50,8 @@ class SerializerTest : TimeOutTest() { val address = Address.decode("DCT6bVmimtYSvWQtwdrkVVQGHkVsTJZVKtBiUqf4YmJnrJPnk89QP") val op = TransferOperation( - "1.2.30".toChainObject(), - "1.2.31".toChainObject(), + "1.2.30".toObjectId(), + "1.2.31".toObjectId(), AssetAmount(10000000), Memo("hello memo", priv, address, BigInteger("132456789")), Fee(amount = 5000) @@ -66,7 +65,7 @@ class SerializerTest : TimeOutTest() { val op = PurchaseContentOperation( "ipfs:QmabU7WNHZwcojgJrCRwKhsJvfinLT9xffnKMFsrcCGGFP", - "1.2.30".toChainObject(), + "1.2.30".toObjectId(), AssetAmount(10000000), PubKey("9108409595926410618584909688806123815350070889187120060090262698305971998526501009804554058758289676257609340949615914583138841456997698133991004991473670") ) @@ -79,7 +78,7 @@ class SerializerTest : TimeOutTest() { val op = PurchaseContentOperation( "http://alax.io/?scheme=allax%3A%2F%2Fcom.example.helloworld%3A3&version=7f48b24e-8ab9-4810-8b9a-936146ad6ad2", - "1.2.30".toChainObject(), + "1.2.30".toObjectId(), AssetAmount(100000000), PubKey("5182545488318095000498180568539728214545472470974958338942426759510121851708530625921436777555517288139787965253547588340803542762268721656138876002028437") ) @@ -165,7 +164,7 @@ class SerializerTest : TimeOutTest() { val expected = "140000000000000000000100000000000000220016687474703a2f2f68656c6c6f2e696f2f776f726c6432000000000101000000e80300000000000000222222222222222222222222222222222222222200007238ed5c0000000000000000004c7b227469746c65223a2247616d65205469746c65222c226465736372697074696f6e223a224465736372697074696f6e222c22636f6e74656e745f747970655f6964223a22312e352e35227d00" val op = AddOrUpdateContentOperation( - author = ChainObject.parse("1.2.34"), + author = "1.2.34".toObjectId(), uri = "http://hello.io/world2", price = listOf(RegionalPrice(AssetAmount(1000), Regions.NONE.id)), expiration = LocalDateTime.parse("2019-05-28T13:32:34"), @@ -180,7 +179,7 @@ class SerializerTest : TimeOutTest() { val expected = "200000000000000000002216687474703a2f2f68656c6c6f2e696f2f776f726c6432" val op = RemoveContentOperation( - ChainObject.parse("1.2.34"), + "1.2.34".toObjectId(), "http://hello.io/world2" ) @@ -231,7 +230,7 @@ class SerializerTest : TimeOutTest() { @Test fun `should serialize create asset operation`() { val expected = "0320a1070000000000001b0353444b010968656c6c6f20617069fad456864c011a000100000000000000000100000000000000e70701010100000100" - val ex = ExchangeRate(AssetAmount(1), AssetAmount(1, ChainObject.parse("1.3.999"))) + val ex = ExchangeRate(AssetAmount(1), AssetAmount(1, "1.3.999".toObjectId())) val op = AssetCreateOperation(Helpers.account, "SDK", 1, "hello api", AssetOptions(ex)) op.fee = AssetAmount(500000) @@ -250,7 +249,7 @@ class SerializerTest : TimeOutTest() { @Test fun `should serialize issue asset operation`() { val expected = "040a00000000000000001b0a00000000000000241b0000" - val op = AssetIssueOperation(Helpers.account, AssetAmount(10, ChainObject.parse("1.3.36")), Helpers.account) + val op = AssetIssueOperation(Helpers.account, AssetAmount(10, "1.3.36".toObjectId()), Helpers.account) op.fee = AssetAmount(10) Serializer.serialize(op).hex() `should be equal to` expected } @@ -258,7 +257,7 @@ class SerializerTest : TimeOutTest() { @Test fun `should serialize reserve asset operation`() { val expected = "220a00000000000000001b0a000000000000002400" - val op = AssetReserveOperation(Helpers.account, AssetAmount(10, ChainObject.parse("1.3.36"))) + val op = AssetReserveOperation(Helpers.account, AssetAmount(10, "1.3.36".toObjectId())) op.fee = AssetAmount(10) Serializer.serialize(op).hex() `should be equal to` expected } @@ -266,7 +265,7 @@ class SerializerTest : TimeOutTest() { @Test fun `should serialize fund asset pool operation`() { val expected = "210a00000000000000001b0a00000000000000240a000000000000000000" - val op = AssetFundPoolsOperation(Helpers.account, AssetAmount(10, ChainObject.parse("1.3.36")), AssetAmount(10)) + val op = AssetFundPoolsOperation(Helpers.account, AssetAmount(10, "1.3.36".toObjectId()), AssetAmount(10)) op.fee = AssetAmount(10) Serializer.serialize(op).hex() `should be equal to` expected } @@ -274,7 +273,7 @@ class SerializerTest : TimeOutTest() { @Test fun `should serialize claim asset pool operation`() { val expected = "230a00000000000000001b0a00000000000000240a000000000000000000" - val op = AssetClaimFeesOperation(Helpers.account, AssetAmount(10, ChainObject.parse("1.3.36")), AssetAmount(10)) + val op = AssetClaimFeesOperation(Helpers.account, AssetAmount(10, "1.3.36".toObjectId()), AssetAmount(10)) op.fee = AssetAmount(10) Serializer.serialize(op).hex() `should be equal to` expected } From 3aa9befec66f70c207729bcbadb5a8d358bbbf82 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Fri, 26 Jul 2019 11:58:52 +0200 Subject: [PATCH 02/19] impl blocking gen api --- buildSrc/src/main/java/Dependencies.kt | 5 + library/build.gradle.kts | 21 ++ .../main/java/ch/decent/sdk/DCoreSdk.kt | 15 ++ .../ch/decent/sdk/api/blocking/AccountApi.kt | 99 +++++++++ .../ch/decent/sdk/api/blocking/AssetApi.kt | 153 +++++++++++++ .../ch/decent/sdk/api/blocking/BalanceApi.kt | 34 +++ .../ch/decent/sdk/api/blocking/BlockApi.kt | 16 ++ .../decent/sdk/api/blocking/BroadcastApi.kt | 63 ++++++ .../ch/decent/sdk/api/blocking/ContentApi.kt | 149 +++++++++++++ .../ch/decent/sdk/api/blocking/DCoreApi.kt | 37 ++++ .../ch/decent/sdk/api/blocking/GeneralApi.kt | 19 ++ .../ch/decent/sdk/api/blocking/HistoryApi.kt | 43 ++++ .../decent/sdk/api/blocking/MessagingApi.kt | 59 +++++ .../ch/decent/sdk/api/blocking/MiningApi.kt | 55 +++++ .../java/ch/decent/sdk/api/blocking/NftApi.kt | 172 +++++++++++++++ .../ch/decent/sdk/api/blocking/PurchaseApi.kt | 54 +++++ .../ch/decent/sdk/api/blocking/SeederApi.kt | 22 ++ .../sdk/api/blocking/SubscriptionApi.kt | 24 ++ .../decent/sdk/api/blocking/TransactionApi.kt | 30 +++ .../decent/sdk/api/blocking/ValidationApi.kt | 37 ++++ library/src/main/java/ch/decent/sdk/Apis.kt | 119 ++++++++++ .../src/main/java/ch/decent/sdk/DCoreApi.kt | 4 +- .../sdk/{DCoreSdk.kt => DCoreClient.kt} | 10 +- .../main/java/ch/decent/sdk/api/AccountApi.kt | 8 +- .../main/java/ch/decent/sdk/api/AssetApi.kt | 4 +- .../java/ch/decent/sdk/api/BroadcastApi.kt | 3 + .../main/java/ch/decent/sdk/api/ContentApi.kt | 7 +- .../main/java/ch/decent/sdk/api/HistoryApi.kt | 7 +- .../java/ch/decent/sdk/api/MessagingApi.kt | 11 +- .../main/java/ch/decent/sdk/api/MiningApi.kt | 8 +- .../src/main/java/ch/decent/sdk/api/NftApi.kt | 2 +- .../java/ch/decent/sdk/api/PurchaseApi.kt | 5 +- .../main/java/ch/decent/sdk/api/SeederApi.kt | 7 +- .../java/ch/decent/sdk/api/TransactionApi.kt | 3 + .../main/java/ch/decent/sdk/crypto/Wallet.kt | 6 +- .../java/ch/decent/sdk/model/AssetOptions.kt | 2 +- .../java/ch/decent/sdk/model/ContentTypes.kt | 3 +- .../model/operation/SendMessageOperation.kt | 4 +- .../java/ch/decent/sdk/net/rpc/RpcService.kt | 4 +- .../main/java/ch/decent/sdk/poet/Blocking.kt | 208 ++++++++++++++++++ .../src/test/java/ch/decent/sdk/CrytpoTest.kt | 4 +- .../src/test/java/ch/decent/sdk/Scratchpad.kt | 6 +- .../src/test/java/ch/decent/sdk/api/Base.kt | 8 +- .../java/ch/decent/sdk/api/CallbackApiTest.kt | 6 +- .../java/ch/decent/sdk/api/SeederApiTest.kt | 10 +- .../test/java/ch/decent/sdk/java/ApiTest.java | 16 +- .../java/ch/decent/sdk/model/AssetTest.kt | 4 +- .../java/ch/decent/sdk/net/SerializerTest.kt | 10 +- .../ch/decent/sdk/net/ws/RxWebSocketTest.kt | 5 +- 49 files changed, 1524 insertions(+), 77 deletions(-) create mode 100644 library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt create mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt create mode 100644 library/src/main/java/ch/decent/sdk/Apis.kt rename library/src/main/java/ch/decent/sdk/{DCoreSdk.kt => DCoreClient.kt} (93%) create mode 100644 library/src/main/java/ch/decent/sdk/poet/Blocking.kt diff --git a/buildSrc/src/main/java/Dependencies.kt b/buildSrc/src/main/java/Dependencies.kt index 64db6a1f..a0faa876 100644 --- a/buildSrc/src/main/java/Dependencies.kt +++ b/buildSrc/src/main/java/Dependencies.kt @@ -29,6 +29,8 @@ object Versions { val dokka = "0.9.16" val detekt = "1.0.0-RC14" val dockerCompose = "0.9.4" + + val kpoet = "1.3.0" } object GradlePlugins { @@ -61,6 +63,9 @@ object Libs { val errorProne = "com.google.errorprone:error_prone_core:${Versions.errorProne}" val errorProneJavac = "com.google.errorprone:javac:${Versions.errorProneJavac}" + + val kpoet = "com.squareup:kotlinpoet:${Versions.kpoet}" + } object TestLibs { diff --git a/library/build.gradle.kts b/library/build.gradle.kts index 72e94334..360e677c 100644 --- a/library/build.gradle.kts +++ b/library/build.gradle.kts @@ -1,4 +1,5 @@ import org.jetbrains.dokka.gradle.DokkaTask +import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet plugins { kotlin("jvm") @@ -14,6 +15,9 @@ dependencies { implementation(Libs.kotlin) implementation(Libs.kotlinReflect) + implementation(Libs.kpoet) + implementation("com.github.cretz.kastree:kastree-ast-psi:0.4.0") + api(Libs.rxKotlin) api(Libs.rxJava) @@ -39,6 +43,23 @@ dependencies { errorprone(Libs.errorProne) errorproneJavac(Libs.errorProneJavac) } +sourceSets.main { + withConvention(KotlinSourceSet::class) { + kotlin.srcDirs("src/main/java", "src-gen/main/java") + } +} + +tasks.create("cleanGen") { + delete("src-gen") +} + +tasks.create("generate") { + classpath = sourceSets["main"].runtimeClasspath + main = "ch.decent.sdk.poet.BlockingKt" + dependsOn("cleanGen") +} + +tasks.get("compileKotlin").dependsOn("cleanGen") detekt { toolVersion = Versions.detekt diff --git a/library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt b/library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt new file mode 100644 index 00000000..fbe014ab --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt @@ -0,0 +1,15 @@ +package ch.decent.sdk + +import kotlin.String +import okhttp3.OkHttpClient +import org.slf4j.Logger + +object DCoreSdk { + fun createApiBlocking( + client: OkHttpClient, + websocketUrl: String? = null, + httpUrl: String? = null, + logger: Logger? = null + ) = ch.decent.sdk.api.blocking.DCoreApi(DCoreApi(DCoreClient(client, websocketUrl, httpUrl, + logger))) +} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt new file mode 100644 index 00000000..4f529f84 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt @@ -0,0 +1,99 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Address +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.crypto.ECKeyPair +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AccountOptions +import ch.decent.sdk.model.AssetAmount +import ch.decent.sdk.model.Authority +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.SearchAccountHistoryOrder +import ch.decent.sdk.model.SearchAccountsOrder +import ch.decent.sdk.model.TransactionDetailObjectId +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K +import kotlin.Boolean +import kotlin.Int +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List + +class AccountApi internal constructor( + private val api: ch.decent.sdk.api.AccountApi +) { + fun exist(nameOrId: String) = api.exist(nameOrId).blockingGet() + fun get(id: AccountObjectId) = api.get(id).blockingGet() + fun getByName(name: String) = api.getByName(name).blockingGet() + fun get(nameOrId: String) = api.get(nameOrId).blockingGet() + fun countAll() = api.countAll().blockingGet() + fun findAllReferencesByKeys(keys: List

) = api.findAllReferencesByKeys(keys).blockingGet() + fun findAllReferencesByAccount(accountId: AccountObjectId) = + api.findAllReferencesByAccount(accountId).blockingGet() + fun getAll(accountIds: List) = api.getAll(accountIds).blockingGet() + fun getFullAccounts(namesOrIds: List, subscribe: Boolean = false) = + api.getFullAccounts(namesOrIds, subscribe).blockingGet() + fun getAllByNames(names: List) = api.getAllByNames(names).blockingGet() + fun listAllRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX_1K) = + api.listAllRelative(lowerBound, limit).blockingGet() + fun findAll( + searchTerm: String, + order: SearchAccountsOrder = SearchAccountsOrder.NAME_DESC, + id: AccountObjectId? = null, + limit: Int = REQ_LIMIT_MAX_1K + ) = api.findAll(searchTerm, order, id, limit).blockingGet() + fun searchAccountHistory( + accountId: AccountObjectId, + from: TransactionDetailObjectId? = null, + order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, + limit: Int = REQ_LIMIT_MAX + ) = api.searchAccountHistory(accountId, from, order, limit).blockingGet() + fun createCredentials(account: String, privateKey: String) = api.createCredentials(account, + privateKey).blockingGet() + fun createMemo( + message: String, + recipient: String? = null, + keyPair: ECKeyPair? = null + ) = api.createMemo(message, recipient, keyPair).blockingGet() + fun createTransfer( + credentials: Credentials, + nameOrId: String, + amount: AssetAmount, + memo: String? = null, + encrypted: Boolean = true, + fee: Fee = Fee() + ) = api.createTransfer(credentials, nameOrId, amount, memo, encrypted, fee).blockingGet() + fun transfer( + credentials: Credentials, + nameOrId: String, + amount: AssetAmount, + memo: String? = null, + encrypted: Boolean = true, + fee: Fee = Fee() + ) = api.transfer(credentials, nameOrId, amount, memo, encrypted, fee).blockingGet() + fun createAccountOperation( + registrar: AccountObjectId, + name: String, + address: Address, + fee: Fee = Fee() + ) = api.createAccountOperation(registrar, name, address, fee).blockingGet() + fun create( + registrar: Credentials, + name: String, + address: Address, + fee: Fee = Fee() + ) = api.create(registrar, name, address, fee).blockingGet() + fun createUpdateOperation(nameOrId: String, fee: Fee = Fee()) = + api.createUpdateOperation(nameOrId, fee).blockingGet() + fun update( + credentials: Credentials, + options: AccountOptions? = null, + active: Authority? = null, + owner: Authority? = null, + fee: Fee = Fee() + ) = api.update(credentials, options, active, owner, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt new file mode 100644 index 00000000..a6dad61c --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt @@ -0,0 +1,153 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetDataObjectId +import ch.decent.sdk.model.AssetObjectId +import ch.decent.sdk.model.AssetOptions +import ch.decent.sdk.model.ExchangeRateValues +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.Memo +import ch.decent.sdk.model.MonitoredAssetOptions +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import java.math.RoundingMode +import kotlin.Boolean +import kotlin.Byte +import kotlin.Int +import kotlin.Long +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List + +class AssetApi internal constructor( + private val api: ch.decent.sdk.api.AssetApi +) { + fun get(assetId: AssetObjectId) = api.get(assetId).blockingGet() + fun getAll(assetIds: List) = api.getAll(assetIds).blockingGet() + fun getRealSupply() = api.getRealSupply().blockingGet() + fun getAssetsData(assetId: List) = api.getAssetsData(assetId).blockingGet() + fun getAssetData(assetId: AssetDataObjectId) = api.getAssetData(assetId).blockingGet() + fun listAllRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX) = + api.listAllRelative(lowerBound, limit).blockingGet() + fun listAll(includeMonitored: Boolean = false) = api.listAll(includeMonitored).blockingGet() + fun getByName(assetSymbol: String) = api.getByName(assetSymbol).blockingGet() + fun getAllByName(assetSymbols: List) = api.getAllByName(assetSymbols).blockingGet() + fun convertFromDCT( + assetId: AssetObjectId, + amount: Long, + roundingMode: RoundingMode = RoundingMode.CEILING + ) = api.convertFromDCT(assetId, amount, roundingMode).blockingGet() + fun convertToDCT( + assetId: AssetObjectId, + amount: Long, + roundingMode: RoundingMode = RoundingMode.CEILING + ) = api.convertToDCT(assetId, amount, roundingMode).blockingGet() + fun createAssetCreateOperation( + issuer: AccountObjectId, + symbol: String, + precision: Byte, + description: String, + options: AssetOptions, + monitoredOptions: MonitoredAssetOptions? = null, + fee: Fee = Fee() + ) = api.createAssetCreateOperation(issuer, symbol, precision, description, options, + monitoredOptions, fee).blockingGet() + fun create( + credentials: Credentials, + symbol: String, + precision: Byte, + description: String, + options: AssetOptions = AssetOptions(), + fee: Fee = Fee() + ) = api.create(credentials, symbol, precision, description, options, fee).blockingGet() + fun createMonitoredAsset( + credentials: Credentials, + symbol: String, + precision: Byte, + description: String, + options: MonitoredAssetOptions = MonitoredAssetOptions(), + fee: Fee = Fee() + ) = api.createMonitoredAsset(credentials, symbol, precision, description, options, + fee).blockingGet() + fun createAssetUpdateOperation( + assetIdOrSymbol: String, + newIssuer: AccountObjectId? = null, + fee: Fee = Fee() + ) = api.createAssetUpdateOperation(assetIdOrSymbol, newIssuer, fee).blockingGet() + fun update( + credentials: Credentials, + assetIdOrSymbol: String, + exchangeRate: ExchangeRateValues? = null, + description: String? = null, + exchangeable: Boolean? = null, + maxSupply: Long? = null, + newIssuer: AccountObjectId? = null, + fee: Fee = Fee() + ) = api.update(credentials, assetIdOrSymbol, exchangeRate, description, exchangeable, maxSupply, + newIssuer, fee).blockingGet() + fun createAssetUpdateAdvancedOperation(assetIdOrSymbol: String, fee: Fee = Fee()) = + api.createAssetUpdateAdvancedOperation(assetIdOrSymbol, fee).blockingGet() + fun updateAdvanced( + credentials: Credentials, + assetIdOrSymbol: String, + precision: Byte? = null, + fixedMaxSupply: Boolean? = null, + fee: Fee = Fee() + ) = api.updateAdvanced(credentials, assetIdOrSymbol, precision, fixedMaxSupply, fee).blockingGet() + fun createAssetIssueOperation( + assetIdOrSymbol: String, + amount: Long, + to: AccountObjectId? = null, + memo: Memo? = null, + fee: Fee = Fee() + ) = api.createAssetIssueOperation(assetIdOrSymbol, amount, to, memo, fee).blockingGet() + fun issue( + credentials: Credentials, + assetIdOrSymbol: String, + amount: Long, + to: AccountObjectId? = null, + memo: Memo? = null, + fee: Fee = Fee() + ) = api.issue(credentials, assetIdOrSymbol, amount, to, memo, fee).blockingGet() + fun createFundPoolsOperation( + assetIdOrSymbol: String, + uia: Long, + dct: Long, + fee: Fee = Fee() + ) = api.createFundPoolsOperation(assetIdOrSymbol, uia, dct, fee).blockingGet() + fun fund( + credentials: Credentials, + assetIdOrSymbol: String, + uia: Long, + dct: Long, + fee: Fee = Fee() + ) = api.fund(credentials, assetIdOrSymbol, uia, dct, fee).blockingGet() + fun createClaimFeesOperation( + assetIdOrSymbol: String, + uia: Long, + dct: Long, + fee: Fee = Fee() + ) = api.createClaimFeesOperation(assetIdOrSymbol, uia, dct, fee).blockingGet() + fun claim( + credentials: Credentials, + assetIdOrSymbol: String, + uia: Long, + dct: Long, + fee: Fee = Fee() + ) = api.claim(credentials, assetIdOrSymbol, uia, dct, fee).blockingGet() + fun createReserveOperation( + assetIdOrSymbol: String, + amount: Long, + fee: Fee = Fee() + ) = api.createReserveOperation(assetIdOrSymbol, amount, fee).blockingGet() + fun reserve( + credentials: Credentials, + assetIdOrSymbol: String, + amount: Long, + fee: Fee = Fee() + ) = api.reserve(credentials, assetIdOrSymbol, amount, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt new file mode 100644 index 00000000..238ade30 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt @@ -0,0 +1,34 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.DCoreConstants +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List +import kotlin.collections.emptyList + +class BalanceApi internal constructor( + private val api: ch.decent.sdk.api.BalanceApi +) { + fun get(accountId: AccountObjectId, asset: AssetObjectId) = api.get(accountId, + asset).blockingGet() + fun getAll(accountId: AccountObjectId, assets: List = emptyList()) = + api.getAll(accountId, assets).blockingGet() + fun get(name: String, asset: AssetObjectId) = api.get(name, asset).blockingGet() + fun getAll(name: String, assets: List = emptyList()) = api.getAll(name, + assets).blockingGet() + fun getWithAsset(accountId: AccountObjectId, assetSymbol: String = DCoreConstants.DCT_SYMBOL) = + api.getWithAsset(accountId, assetSymbol).blockingGet() + fun getAllWithAsset(accountId: AccountObjectId, assetSymbols: List) = + api.getAllWithAsset(accountId, assetSymbols).blockingGet() + fun getWithAsset(name: String, assetSymbol: String = DCoreConstants.DCT_SYMBOL) = + api.getWithAsset(name, assetSymbol).blockingGet() + fun getAllWithAsset(name: String, assetSymbols: List) = api.getAllWithAsset(name, + assetSymbols).blockingGet() + fun getAllVesting(accountId: AccountObjectId) = api.getAllVesting(accountId).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt new file mode 100644 index 00000000..1839a32c --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt @@ -0,0 +1,16 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import kotlin.Long +import kotlin.Suppress + +class BlockApi internal constructor( + private val api: ch.decent.sdk.api.BlockApi +) { + fun get(blockNum: Long) = api.get(blockNum).blockingGet() + fun getHeader(blockNum: Long) = api.getHeader(blockNum).blockingGet() + fun getHeadTime() = api.getHeadTime().blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt new file mode 100644 index 00000000..2b0f0595 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt @@ -0,0 +1,63 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.ECKeyPair +import ch.decent.sdk.model.Transaction +import ch.decent.sdk.model.operation.BaseOperation +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List +import org.threeten.bp.Duration + +class BroadcastApi internal constructor( + private val api: ch.decent.sdk.api.BroadcastApi +) { + fun broadcast(transaction: Transaction) = api.broadcast(transaction).blockingGet() + fun broadcast( + privateKey: ECKeyPair, + operations: List, + expiration: Duration = api.transactionExpiration + ) = api.broadcast(privateKey, operations, expiration).blockingGet() + fun broadcast( + privateKey: ECKeyPair, + operation: BaseOperation, + expiration: Duration = api.transactionExpiration + ) = api.broadcast(privateKey, operation, expiration).blockingGet() + fun broadcast( + privateKey: String, + operations: List, + expiration: Duration = api.transactionExpiration + ) = api.broadcast(privateKey, operations, expiration).blockingGet() + fun broadcast( + privateKey: String, + operation: BaseOperation, + expiration: Duration = api.transactionExpiration + ) = api.broadcast(privateKey, operation, expiration).blockingGet() + fun broadcastWithCallback(transaction: Transaction) = + api.broadcastWithCallback(transaction).blockingGet() + fun broadcastWithCallback( + privateKey: ECKeyPair, + operations: List, + expiration: Duration = api.transactionExpiration + ) = api.broadcastWithCallback(privateKey, operations, expiration).blockingGet() + fun broadcastWithCallback( + privateKey: ECKeyPair, + operation: BaseOperation, + expiration: Duration = api.transactionExpiration + ) = api.broadcastWithCallback(privateKey, operation, expiration).blockingGet() + fun broadcastWithCallback( + privateKey: String, + operations: List, + expiration: Duration = api.transactionExpiration + ) = api.broadcastWithCallback(privateKey, operations, expiration).blockingGet() + fun broadcastWithCallback( + privateKey: String, + operation: BaseOperation, + expiration: Duration = api.transactionExpiration + ) = api.broadcastWithCallback(privateKey, operation, expiration).blockingGet() + fun broadcastSynchronous(transaction: Transaction) = + api.broadcastSynchronous(transaction).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt new file mode 100644 index 00000000..28034a6b --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt @@ -0,0 +1,149 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetAmount +import ch.decent.sdk.model.CoAuthors +import ch.decent.sdk.model.ContentObjectId +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.PubKey +import ch.decent.sdk.model.PurchaseObjectId +import ch.decent.sdk.model.RegionalPrice +import ch.decent.sdk.model.Regions +import ch.decent.sdk.model.SearchContentOrder +import ch.decent.sdk.model.Synopsis +import ch.decent.sdk.model.contentType +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import org.threeten.bp.LocalDateTime + +class ContentApi internal constructor( + private val api: ch.decent.sdk.api.ContentApi +) { + fun generateKeys(seeders: List) = api.generateKeys(seeders).blockingGet() + fun get(contentId: ContentObjectId) = api.get(contentId).blockingGet() + fun getAll(contentId: List) = api.getAll(contentId).blockingGet() + fun get(uri: String) = api.get(uri).blockingGet() + fun listAllPublishersRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX) = + api.listAllPublishersRelative(lowerBound, limit).blockingGet() + + fun restoreEncryptionKey(elGamalPrivate: PubKey, purchaseId: PurchaseObjectId) = + api.restoreEncryptionKey(elGamalPrivate, purchaseId).blockingGet() + + fun findAll( + term: String, + order: SearchContentOrder = SearchContentOrder.CREATED_DESC, + user: String = "", + regionCode: String = Regions.ALL.code, + type: String = contentType(), + startId: ContentObjectId? = null, + limit: Int = REQ_LIMIT_MAX + ) = api.findAll(term, order, user, regionCode, type, startId, limit).blockingGet() + + fun createPurchaseOperation( + credentials: Credentials, + contentId: ContentObjectId, + fee: Fee = Fee() + ) = api.createPurchaseOperation(credentials, contentId, fee).blockingGet() + + fun createPurchaseOperation( + credentials: Credentials, + uri: String, + fee: Fee = Fee() + ) = api.createPurchaseOperation(credentials, uri, fee).blockingGet() + + fun purchase( + credentials: Credentials, + contentId: ContentObjectId, + fee: Fee = Fee() + ) = api.purchase(credentials, contentId, fee).blockingGet() + + fun purchase( + credentials: Credentials, + uri: String, + fee: Fee = Fee() + ) = api.purchase(credentials, uri, fee).blockingGet() + + fun createTransfer( + credentials: Credentials, + id: ContentObjectId, + amount: AssetAmount, + memo: String? = null, + fee: Fee = Fee() + ) = api.createTransfer(credentials, id, amount, memo, fee).blockingGet() + + fun transfer( + credentials: Credentials, + id: ContentObjectId, + amount: AssetAmount, + memo: String? = null, + fee: Fee = Fee() + ) = api.transfer(credentials, id, amount, memo, fee).blockingGet() + + fun createRemoveContentOperation(content: ContentObjectId, fee: Fee = Fee()) = + api.createRemoveContentOperation(content, fee).blockingGet() + + fun createRemoveContentOperation(content: String, fee: Fee = Fee()) = + api.createRemoveContentOperation(content, fee).blockingGet() + + fun remove( + credentials: Credentials, + content: ContentObjectId, + fee: Fee = Fee() + ) = api.remove(credentials, content, fee).blockingGet() + + fun remove( + credentials: Credentials, + content: String, + fee: Fee = Fee() + ) = api.remove(credentials, content, fee).blockingGet() + + fun createAddContentOperation( + author: AccountObjectId, + coAuthors: CoAuthors, + uri: String, + price: List, + expiration: LocalDateTime, + synopsis: Synopsis, + fee: Fee = Fee() + ) = api.createAddContentOperation(author, coAuthors, uri, price, expiration, synopsis, + fee).blockingGet() + + fun add( + credentials: Credentials, + coAuthors: CoAuthors, + uri: String, + price: List, + expiration: LocalDateTime, + synopsis: Synopsis, + fee: Fee = Fee() + ) = api.add(credentials, coAuthors, uri, price, expiration, synopsis, fee).blockingGet() + + fun createUpdateContentOperation(content: ContentObjectId, fee: Fee = Fee()) = + api.createUpdateContentOperation(content, fee).blockingGet() + + fun createUpdateContentOperation(content: String, fee: Fee = Fee()) = + api.createUpdateContentOperation(content, fee).blockingGet() + + fun update( + credentials: Credentials, + content: ContentObjectId, + synopsis: Synopsis? = null, + price: List? = null, + coAuthors: CoAuthors? = null, + fee: Fee = Fee() + ) = api.update(credentials, content, synopsis, price, coAuthors, fee).blockingGet() + + fun update( + credentials: Credentials, + content: String, + synopsis: Synopsis? = null, + price: List? = null, + coAuthors: CoAuthors? = null, + fee: Fee = Fee() + ) = api.update(credentials, content, synopsis, price, coAuthors, fee).blockingGet() +} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt new file mode 100644 index 00000000..dc16b7a7 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt @@ -0,0 +1,37 @@ +package ch.decent.sdk.api.blocking + +class DCoreApi( + api: ch.decent.sdk.DCoreApi +) { + val broadcastApi: BroadcastApi = BroadcastApi(api.broadcastApi) + + val blockApi: BlockApi = BlockApi(api.blockApi) + + val miningApi: MiningApi = MiningApi(api.miningApi) + + val purchaseApi: PurchaseApi = PurchaseApi(api.purchaseApi) + + val contentApi: ContentApi = ContentApi(api.contentApi) + + val transactionApi: TransactionApi = TransactionApi(api.transactionApi) + + val accountApi: AccountApi = AccountApi(api.accountApi) + + val seederApi: SeederApi = SeederApi(api.seederApi) + + val balanceApi: BalanceApi = BalanceApi(api.balanceApi) + + val nftApi: NftApi = NftApi(api.nftApi) + + val generalApi: GeneralApi = GeneralApi(api.generalApi) + + val historyApi: HistoryApi = HistoryApi(api.historyApi) + + val assetApi: AssetApi = AssetApi(api.assetApi) + + val subscriptionApi: SubscriptionApi = SubscriptionApi(api.subscriptionApi) + + val messagingApi: MessagingApi = MessagingApi(api.messagingApi) + + val validationApi: ValidationApi = ValidationApi(api.validationApi) +} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt new file mode 100644 index 00000000..a0b50e87 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt @@ -0,0 +1,19 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import kotlin.Suppress +import org.threeten.bp.LocalDateTime + +class GeneralApi internal constructor( + private val api: ch.decent.sdk.api.GeneralApi +) { + fun getChainProperties() = api.getChainProperties().blockingGet() + fun getGlobalProperties() = api.getGlobalProperties().blockingGet() + fun getConfig() = api.getConfig().blockingGet() + fun getChainId() = api.getChainId().blockingGet() + fun getDynamicGlobalProperties() = api.getDynamicGlobalProperties().blockingGet() + fun getTimeToMaintenance(time: LocalDateTime) = api.getTimeToMaintenance(time).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt new file mode 100644 index 00000000..04775697 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt @@ -0,0 +1,43 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.AssetObjectId +import ch.decent.sdk.model.OperationHistoryObjectId +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import kotlin.Int +import kotlin.Long +import kotlin.Suppress +import kotlin.collections.List +import kotlin.collections.emptyList + +class HistoryApi internal constructor( + private val api: ch.decent.sdk.api.HistoryApi +) { + fun getOperation(accountId: AccountObjectId, operationId: OperationHistoryObjectId) = + api.getOperation(accountId, operationId).blockingGet() + fun listOperations( + accountId: AccountObjectId, + startId: OperationHistoryObjectId? = null, + stopId: OperationHistoryObjectId? = null, + limit: Int = REQ_LIMIT_MAX + ) = api.listOperations(accountId, startId, stopId, limit).blockingGet() + fun listOperationsRelative( + accountId: AccountObjectId, + start: Int = 0, + limit: Int = REQ_LIMIT_MAX + ) = api.listOperationsRelative(accountId, start, limit).blockingGet() + fun findAllOperations( + accountId: AccountObjectId, + assets: List = emptyList(), + recipientAccount: AccountObjectId? = null, + fromBlock: Long = 0, + toBlock: Long = 0, + startOffset: Long = 0, + limit: Int = REQ_LIMIT_MAX + ) = api.findAllOperations(accountId, assets, recipientAccount, fromBlock, toBlock, startOffset, + limit).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt new file mode 100644 index 00000000..7719cc51 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt @@ -0,0 +1,59 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.MessageRequest +import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K +import kotlin.Int +import kotlin.Suppress +import kotlin.collections.List + +class MessagingApi internal constructor( + private val api: ch.decent.sdk.api.MessagingApi +) { + fun getAllOperations( + sender: AccountObjectId? = null, + receiver: AccountObjectId? = null, + maxCount: Int = REQ_LIMIT_MAX_1K + ) = api.getAllOperations(sender, receiver, maxCount).blockingGet() + fun getAll( + sender: AccountObjectId? = null, + receiver: AccountObjectId? = null, + maxCount: Int = REQ_LIMIT_MAX_1K + ) = api.getAll(sender, receiver, maxCount).blockingGet() + fun getAllDecrypted( + credentials: Credentials, + sender: AccountObjectId? = null, + receiver: AccountObjectId? = null, + maxCount: Int = REQ_LIMIT_MAX_1K + ) = api.getAllDecrypted(credentials, sender, receiver, maxCount).blockingGet() + fun getAllDecryptedForSender(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K) = + api.getAllDecryptedForSender(credentials, maxCount).blockingGet() + fun getAllDecryptedForReceiver(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K) = + api.getAllDecryptedForReceiver(credentials, maxCount).blockingGet() + fun createMessageOperation( + credentials: Credentials, + messages: List, + fee: Fee = Fee() + ) = api.createMessageOperation(credentials, messages, fee).blockingGet() + fun createMessageOperationUnencrypted( + credentials: Credentials, + messages: List, + fee: Fee = Fee() + ) = api.createMessageOperationUnencrypted(credentials, messages, fee).blockingGet() + fun send( + credentials: Credentials, + messages: List, + fee: Fee = Fee() + ) = api.send(credentials, messages, fee).blockingGet() + fun sendUnencrypted( + credentials: Credentials, + messages: List, + fee: Fee = Fee() + ) = api.sendUnencrypted(credentials, messages, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt new file mode 100644 index 00000000..41b1abf9 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt @@ -0,0 +1,55 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.MinerObjectId +import ch.decent.sdk.model.SearchMinerVotingOrder +import ch.decent.sdk.model.VoteId +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K +import kotlin.Boolean +import kotlin.Int +import kotlin.Long +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List + +class MiningApi internal constructor( + private val api: ch.decent.sdk.api.MiningApi +) { + fun getActualVotes() = api.getActualVotes().blockingGet() + fun getAssetPerBlock(blockNum: Long) = api.getAssetPerBlock(blockNum).blockingGet() + fun getFeedsByMiner(account: AccountObjectId, count: Int = REQ_LIMIT_MAX) = + api.getFeedsByMiner(account, count).blockingGet() + fun getMinerByAccount(account: AccountObjectId) = api.getMinerByAccount(account).blockingGet() + fun getMinerCount() = api.getMinerCount().blockingGet() + fun getMiners(minerIds: List) = api.getMiners(minerIds).blockingGet() + fun getMiners() = api.getMiners().blockingGet() + fun getNewAssetPerBlock() = api.getNewAssetPerBlock().blockingGet() + fun listMinersRelative(lowerBound: String = "", limit: Int = REQ_LIMIT_MAX_1K) = + api.listMinersRelative(lowerBound, limit).blockingGet() + fun findVotedMiners(voteIds: List) = api.findVotedMiners(voteIds).blockingGet() + fun findAllVotingInfo( + searchTerm: String, + order: SearchMinerVotingOrder = SearchMinerVotingOrder.NAME_DESC, + id: MinerObjectId? = null, + accountName: String? = null, + onlyMyVotes: Boolean = false, + limit: Int = REQ_LIMIT_MAX_1K + ) = api.findAllVotingInfo(searchTerm, order, id, accountName, onlyMyVotes, limit).blockingGet() + fun createVoteOperation( + accountId: AccountObjectId, + minerIds: List, + fee: Fee = Fee() + ) = api.createVoteOperation(accountId, minerIds, fee).blockingGet() + fun vote( + credentials: Credentials, + minerIds: List, + fee: Fee = Fee() + ) = api.vote(credentials, minerIds, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt new file mode 100644 index 00000000..df535da3 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt @@ -0,0 +1,172 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.Memo +import ch.decent.sdk.model.NftDataObjectId +import ch.decent.sdk.model.NftModel +import ch.decent.sdk.model.NftObjectId +import ch.decent.sdk.model.NftOptions +import ch.decent.sdk.net.serialization.Variant +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import java.lang.Class +import kotlin.Boolean +import kotlin.Int +import kotlin.Long +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List +import kotlin.collections.Map +import kotlin.collections.emptyList +import kotlin.reflect.KClass + +class NftApi internal constructor( + private val api: ch.decent.sdk.api.NftApi +) { + fun get(idOrSymbol: String) = api.get(idOrSymbol).blockingGet() + fun getAll(ids: List) = api.getAll(ids).blockingGet() + fun get(id: NftObjectId) = api.get(id).blockingGet() + fun getAllBySymbol(symbols: List) = api.getAllBySymbol(symbols).blockingGet() + fun getBySymbol(symbol: String) = api.getBySymbol(symbol).blockingGet() + fun getAllData(ids: List, clazz: KClass) = api.getAllData(ids, + clazz).blockingGet() + fun getAllData(ids: List, clazz: Class) = api.getAllData(ids, + clazz).blockingGet() + fun getAllData(ids: List) = api.getAllData(ids).blockingGet() + fun getAllDataRaw(ids: List) = api.getAllDataRaw(ids).blockingGet() + fun getData(id: NftDataObjectId, clazz: KClass) = api.getData(id, + clazz).blockingGet() + fun getData(id: NftDataObjectId, clazz: Class) = api.getData(id, + clazz).blockingGet() + fun getData(id: NftDataObjectId) = api.getData(id).blockingGet() + fun getDataRaw(id: NftDataObjectId) = api.getDataRaw(id).blockingGet() + fun countAll() = api.countAll().blockingGet() + fun countAllData() = api.countAllData().blockingGet() + fun getNftBalancesRaw(account: AccountObjectId, nftIds: List = emptyList()) = + api.getNftBalancesRaw(account, nftIds).blockingGet() + fun getNftBalances(account: AccountObjectId, nftIds: List = emptyList()) = + api.getNftBalances(account, nftIds).blockingGet() + fun getNftBalances( + account: AccountObjectId, + nftId: NftObjectId, + clazz: KClass + ) = api.getNftBalances(account, nftId, clazz).blockingGet() + fun getNftBalances( + account: AccountObjectId, + nftId: NftObjectId, + clazz: Class + ) = api.getNftBalances(account, nftId, clazz).blockingGet() + fun listAllRelative(lowerBound: String = "", limit: Int = REQ_LIMIT_MAX) = + api.listAllRelative(lowerBound, limit).blockingGet() + fun listDataByNft(nftId: NftObjectId, clazz: KClass) = api.listDataByNft(nftId, + clazz).blockingGet() + fun listDataByNft(nftId: NftObjectId, clazz: Class) = api.listDataByNft(nftId, + clazz).blockingGet() + fun listDataByNft(nftId: NftObjectId) = api.listDataByNft(nftId).blockingGet() + fun listDataByNftRaw(nftId: NftObjectId) = api.listDataByNftRaw(nftId).blockingGet() + fun searchNftHistory(nftDataId: NftDataObjectId) = api.searchNftHistory(nftDataId).blockingGet() + fun createNftCreateOperation( + symbol: String, + options: NftOptions, + clazz: KClass, + transferable: Boolean, + fee: Fee = Fee() + ) = api.createNftCreateOperation(symbol, options, clazz, transferable, fee).blockingGet() + fun createNftCreateOperation( + symbol: String, + options: NftOptions, + clazz: Class, + transferable: Boolean, + fee: Fee = Fee() + ) = api.createNftCreateOperation(symbol, options, clazz, transferable, fee).blockingGet() + fun create( + credentials: Credentials, + symbol: String, + maxSupply: Long, + fixedMaxSupply: Boolean, + description: String, + clazz: KClass, + transferable: Boolean, + fee: Fee = Fee() + ) = api.create(credentials, symbol, maxSupply, fixedMaxSupply, description, clazz, transferable, + fee).blockingGet() + fun create( + credentials: Credentials, + symbol: String, + maxSupply: Long, + fixedMaxSupply: Boolean, + description: String, + clazz: Class, + transferable: Boolean, + fee: Fee = Fee() + ) = api.create(credentials, symbol, maxSupply, fixedMaxSupply, description, clazz, transferable, + fee).blockingGet() + fun createUpdateOperation(idOrSymbol: String, fee: Fee = Fee()) = + api.createUpdateOperation(idOrSymbol, fee).blockingGet() + fun update( + credentials: Credentials, + idOrSymbol: String, + maxSupply: Long? = null, + fixedMaxSupply: Boolean? = null, + description: String? = null, + fee: Fee = Fee() + ) = api.update(credentials, idOrSymbol, maxSupply, fixedMaxSupply, description, fee).blockingGet() + fun createIssueOperation( + issuer: AccountObjectId, + idOrSymbol: String, + to: AccountObjectId, + data: T? = null, + memo: Memo? = null, + fee: Fee = Fee() + ) = api.createIssueOperation(issuer, idOrSymbol, to, data, memo, fee).blockingGet() + fun issue( + credentials: Credentials, + idOrSymbol: String, + to: AccountObjectId, + data: T? = null, + memo: Memo? = null, + fee: Fee = Fee() + ) = api.issue(credentials, idOrSymbol, to, data, memo, fee).blockingGet() + fun createTransferOperation( + from: AccountObjectId, + to: AccountObjectId, + id: NftDataObjectId, + memo: Memo? = null, + fee: Fee = Fee() + ) = api.createTransferOperation(from, to, id, memo, fee).blockingGet() + fun transfer( + credentials: Credentials, + to: AccountObjectId, + id: NftDataObjectId, + memo: Memo? = null, + fee: Fee = Fee() + ) = api.transfer(credentials, to, id, memo, fee).blockingGet() + fun createUpdateDataOperation( + modifier: AccountObjectId, + id: NftDataObjectId, + fee: Fee = Fee() + ) = api.createUpdateDataOperation(modifier, id, fee).blockingGet() + fun createUpdateDataOperation( + modifier: AccountObjectId, + id: NftDataObjectId, + newData: T, + fee: Fee = Fee() + ) = api.createUpdateDataOperation(modifier, id, newData, fee).blockingGet() + fun updateData( + credentials: Credentials, + id: NftDataObjectId, + values: Map, + fee: Fee = Fee() + ) = api.updateData(credentials, id, values, fee).blockingGet() + fun updateData( + credentials: Credentials, + id: NftDataObjectId, + newData: T, + fee: Fee = Fee() + ) = api.updateData(credentials, id, newData, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt new file mode 100644 index 00000000..697811b9 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt @@ -0,0 +1,54 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.crypto.Credentials +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.PurchaseObjectId +import ch.decent.sdk.model.SearchPurchasesOrder +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import kotlin.Byte +import kotlin.Int +import kotlin.String +import kotlin.Suppress + +class PurchaseApi internal constructor( + private val api: ch.decent.sdk.api.PurchaseApi +) { + fun getAllHistory(accountId: AccountObjectId) = api.getAllHistory(accountId).blockingGet() + fun getAllOpen() = api.getAllOpen().blockingGet() + fun getAllOpenByUri(uri: String) = api.getAllOpenByUri(uri).blockingGet() + fun getAllOpenByAccount(accountId: AccountObjectId) = + api.getAllOpenByAccount(accountId).blockingGet() + fun get(consumer: AccountObjectId, uri: String) = api.get(consumer, uri).blockingGet() + fun findAll( + consumer: AccountObjectId, + term: String = "", + from: PurchaseObjectId? = null, + order: SearchPurchasesOrder = SearchPurchasesOrder.PURCHASED_DESC, + limit: Int = REQ_LIMIT_MAX + ) = api.findAll(consumer, term, from, order, limit).blockingGet() + fun findAllForFeedback( + uri: String, + user: String? = null, + count: Int = REQ_LIMIT_MAX, + startId: PurchaseObjectId? = null + ) = api.findAllForFeedback(uri, user, count, startId).blockingGet() + fun createRateAndCommentOperation( + uri: String, + consumer: AccountObjectId, + rating: Byte, + comment: String, + fee: Fee = Fee() + ) = api.createRateAndCommentOperation(uri, consumer, rating, comment, fee).blockingGet() + fun rateAndComment( + credentials: Credentials, + uri: String, + rating: Byte, + comment: String, + fee: Fee = Fee() + ) = api.rateAndComment(credentials, uri, rating, comment, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt new file mode 100644 index 00000000..ab615b7f --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt @@ -0,0 +1,22 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.Regions +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import kotlin.Int +import kotlin.String +import kotlin.Suppress + +class SeederApi internal constructor( + private val api: ch.decent.sdk.api.SeederApi +) { + fun get(accountId: AccountObjectId) = api.get(accountId).blockingGet() + fun listByPrice(count: Int = REQ_LIMIT_MAX) = api.listByPrice(count).blockingGet() + fun listByUpload(count: Int = REQ_LIMIT_MAX) = api.listByUpload(count).blockingGet() + fun listByRegion(region: String = Regions.ALL.code) = api.listByRegion(region).blockingGet() + fun listByRating(count: Int = REQ_LIMIT_MAX) = api.listByRating(count).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt new file mode 100644 index 00000000..b32e2a12 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt @@ -0,0 +1,24 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.SubscriptionObjectId +import kotlin.Int +import kotlin.Suppress + +class SubscriptionApi internal constructor( + private val api: ch.decent.sdk.api.SubscriptionApi +) { + fun get(id: SubscriptionObjectId) = api.get(id).blockingGet() + fun getAllActiveByConsumer(consumer: AccountObjectId, count: Int) = + api.getAllActiveByConsumer(consumer, count).blockingGet() + fun getAllActiveByAuthor(author: AccountObjectId, count: Int) = api.getAllActiveByAuthor(author, + count).blockingGet() + fun getAllByConsumer(consumer: AccountObjectId, count: Int) = api.getAllByConsumer(consumer, + count).blockingGet() + fun getAllByAuthor(author: AccountObjectId, count: Int) = api.getAllByAuthor(author, + count).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt new file mode 100644 index 00000000..2f247e90 --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt @@ -0,0 +1,30 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.Transaction +import ch.decent.sdk.model.TransactionConfirmation +import ch.decent.sdk.model.operation.BaseOperation +import kotlin.Long +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List +import org.threeten.bp.Duration + +class TransactionApi internal constructor( + private val api: ch.decent.sdk.api.TransactionApi +) { + fun createTransaction(operations: List, expiration: Duration = + api.transactionExpiration) = api.createTransaction(operations, expiration).blockingGet() + fun createTransaction(operation: BaseOperation, expiration: Duration = api.transactionExpiration) + = api.createTransaction(operation, expiration).blockingGet() + fun getAllProposed(accountId: AccountObjectId) = api.getAllProposed(accountId).blockingGet() + fun getRecent(trxId: String) = api.getRecent(trxId).blockingGet() + fun get(trxId: String) = api.get(trxId).blockingGet() + fun get(blockNum: Long, trxInBlock: Long) = api.get(blockNum, trxInBlock).blockingGet() + fun get(confirmation: TransactionConfirmation) = api.get(confirmation).blockingGet() + fun getHexDump(transaction: Transaction) = api.getHexDump(transaction).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt new file mode 100644 index 00000000..1602e04c --- /dev/null +++ b/library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt @@ -0,0 +1,37 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList" +) + +package ch.decent.sdk.api.blocking + +import ch.decent.sdk.DCoreConstants +import ch.decent.sdk.crypto.Address +import ch.decent.sdk.model.AssetObjectId +import ch.decent.sdk.model.Transaction +import ch.decent.sdk.model.operation.BaseOperation +import ch.decent.sdk.model.operation.OperationType +import kotlin.String +import kotlin.Suppress +import kotlin.collections.List + +class ValidationApi internal constructor( + private val api: ch.decent.sdk.api.ValidationApi +) { + fun getRequiredSignatures(transaction: Transaction, keys: List
) = + api.getRequiredSignatures(transaction, keys).blockingGet() + fun getPotentialSignatures(transaction: Transaction) = + api.getPotentialSignatures(transaction).blockingGet() + fun verifyAuthority(transaction: Transaction) = api.verifyAuthority(transaction).blockingGet() + fun verifyAccountAuthority(nameOrId: String, keys: List
) = + api.verifyAccountAuthority(nameOrId, keys).blockingGet() + fun validateTransaction(transaction: Transaction) = + api.validateTransaction(transaction).blockingGet() + fun getFees(op: List, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID) = + api.getFees(op, assetId).blockingGet() + fun getFee(op: BaseOperation, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID) = + api.getFee(op, assetId).blockingGet() + fun getFeesForType(types: List, assetId: AssetObjectId = + DCoreConstants.DCT_ASSET_ID) = api.getFeesForType(types, assetId).blockingGet() + fun getFeeForType(type: OperationType, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID) = + api.getFeeForType(type, assetId).blockingGet()} diff --git a/library/src/main/java/ch/decent/sdk/Apis.kt b/library/src/main/java/ch/decent/sdk/Apis.kt new file mode 100644 index 00000000..6c255f1a --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/Apis.kt @@ -0,0 +1,119 @@ +package ch.decent.sdk + +import ch.decent.sdk.api.AccountApi +import ch.decent.sdk.exception.ObjectNotFoundException +import ch.decent.sdk.model.Account +import ch.decent.sdk.model.AccountObjectId +import ch.decent.sdk.model.toObjectId +import ch.decent.sdk.poet.print +import io.reactivex.disposables.Disposable +import okhttp3.OkHttpClient +import org.slf4j.Logger +import java.util.concurrent.Future + +object Apis { + + class AccountApiSync internal constructor(private val api: AccountApi) { + /** + * Get account by id. + * + * @param id account id + * + * @return an account if exist, [ObjectNotFoundException] if not found + */ + fun get(id: AccountObjectId): Account = api.get(id).blockingGet() + } + + class AccountApiFuture internal constructor(private val api: AccountApi) { + /** + * Get account by id. + * + * @param id account id + * + * @return an account if exist, [ObjectNotFoundException] if not found + */ + fun get(id: AccountObjectId): Future = api.get(id).toFuture() + } + + interface ApiCallback { + fun onSuccess(value: T) + fun onError(error: Throwable) + } + + class AccountApiAsync internal constructor(private val api: AccountApi) { + /** + * Get account by id. + * + * @param id account id + * + * @return an account if exist, [ObjectNotFoundException] if not found + */ + fun get(id: AccountObjectId, success: (Account) -> Unit, error: (Throwable) -> Unit): Disposable = + api.get(id).subscribe(success, error) + + fun get(id: AccountObjectId, success: (Account) -> Unit): Disposable = + api.get(id).subscribe(success, {}) + + fun get(id: AccountObjectId, callback: ApiCallback): Disposable = + api.get(id).subscribe({ v -> callback.onSuccess(v) }, { e -> callback.onError(e) }) + } + + class DCoreApiSync(api: DCoreApi) { + val accountApi = AccountApiSync(api.accountApi) + } + + class DCoreApiAsync(api: DCoreApi) { + val accountApi = AccountApiAsync(api.accountApi) + } + + class DCoreApiFuture(api: DCoreApi) { + val accountApi = AccountApiFuture(api.accountApi) + } +} + +val api = DCoreApi(DCoreClient(OkHttpClient.Builder().build(), "wss://testnet-api.dcore.io", "https://testnet-api.dcore.io/")) + +fun DCoreApi.createSync() = Apis.DCoreApiSync(this) +fun DCoreApi.createAsync() = Apis.DCoreApiAsync(this) +fun DCoreApi.createFuture() = Apis.DCoreApiFuture(this) + +object DCoreSdka { + + @JvmStatic @JvmOverloads + fun create(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): Apis.DCoreApiSync = + api.createSync() + + @JvmStatic @JvmOverloads + fun createAsync(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): Apis.DCoreApiAsync = + api.createAsync() + + @JvmStatic @JvmOverloads + fun createFuture(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): Apis.DCoreApiFuture = + api.createFuture() + + @JvmStatic @JvmOverloads + fun createRx(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): DCoreApi = + api +} + +fun main() { + val callback = api.createAsync() + callback.accountApi.get(AccountObjectId(27), object : Apis.ApiCallback { + override fun onSuccess(value: Account) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun onError(error: Throwable) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + }) + callback.accountApi.get("1.2.27".toObjectId()) { account -> account.print() } + + + val sync = api.createSync() + sync.accountApi.get("1.2.27".toObjectId()) + + val future = api.createFuture() + future.accountApi.get("1.2.27".toObjectId()) +} diff --git a/library/src/main/java/ch/decent/sdk/DCoreApi.kt b/library/src/main/java/ch/decent/sdk/DCoreApi.kt index 297bf762..5807af08 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreApi.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreApi.kt @@ -26,7 +26,7 @@ import org.threeten.bp.Duration import java.util.concurrent.TimeoutException import kotlin.reflect.KClass -class DCoreApi internal constructor(internal val core: DCoreSdk) { +class DCoreApi internal constructor(internal val core: DCoreClient) { /** * default transaction expiration in seconds used when broadcasting transactions, @@ -59,7 +59,7 @@ class DCoreApi internal constructor(internal val core: DCoreSdk) { val historyApi = HistoryApi(this) val miningApi = MiningApi(this) val purchaseApi = PurchaseApi(this) - val seedersApi = SeederApi(this) + val seederApi = SeederApi(this) val callbackApi = CallbackApi(this) val subscriptionApi = SubscriptionApi(this) val transactionApi = TransactionApi(this) diff --git a/library/src/main/java/ch/decent/sdk/DCoreSdk.kt b/library/src/main/java/ch/decent/sdk/DCoreClient.kt similarity index 93% rename from library/src/main/java/ch/decent/sdk/DCoreSdk.kt rename to library/src/main/java/ch/decent/sdk/DCoreClient.kt index a2a6c481..0d789723 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreSdk.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreClient.kt @@ -42,7 +42,7 @@ import org.slf4j.Logger import org.threeten.bp.Duration import org.threeten.bp.LocalDateTime -class DCoreSdk private constructor( +class DCoreClient internal constructor( private val client: OkHttpClient, webSocketUrl: String? = null, restUrl: String? = null, @@ -110,14 +110,14 @@ class DCoreSdk private constructor( @JvmStatic @JvmOverloads fun createForHttp(client: OkHttpClient, url: String, logger: Logger? = null): DCoreApi = - DCoreApi(DCoreSdk(client, restUrl = url, logger = logger)) + DCoreApi(DCoreClient(client, restUrl = url, logger = logger)) @JvmStatic @JvmOverloads fun createForWebSocket(client: OkHttpClient, url: String, logger: Logger? = null): DCoreApi = - DCoreApi(DCoreSdk(client, webSocketUrl = url, logger = logger)) + DCoreApi(DCoreClient(client, webSocketUrl = url, logger = logger)) @JvmStatic @JvmOverloads - fun create(client: OkHttpClient, webSocketUrl: String, httpUrl: String, logger: Logger? = null): DCoreApi = - DCoreApi(DCoreSdk(client, webSocketUrl, httpUrl, logger)) + fun create(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): DCoreApi = + DCoreApi(DCoreClient(client, webSocketUrl, httpUrl, logger)) } } diff --git a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt b/library/src/main/java/ch/decent/sdk/api/AccountApi.kt index 1bd610a6..408da135 100644 --- a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/AccountApi.kt @@ -38,6 +38,8 @@ import ch.decent.sdk.net.model.request.LookupAccountNames import ch.decent.sdk.net.model.request.LookupAccounts import ch.decent.sdk.net.model.request.SearchAccountHistory import ch.decent.sdk.net.model.request.SearchAccounts +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K import io.reactivex.Single class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { @@ -149,7 +151,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return map of account names to corresponding IDs */ @JvmOverloads - fun listAllRelative(lowerBound: String, limit: Int = 1000): Single> = + fun listAllRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX_1K): Single> = LookupAccounts(lowerBound, limit).toRequest() /** @@ -167,7 +169,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { searchTerm: String, order: SearchAccountsOrder = SearchAccountsOrder.NAME_DESC, id: AccountObjectId? = null, - limit: Int = 1000 + limit: Int = REQ_LIMIT_MAX_1K ): Single> = SearchAccounts(searchTerm, order, id, limit).toRequest() /** @@ -186,7 +188,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { accountId: AccountObjectId, from: TransactionDetailObjectId? = null, order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, - limit: Int = 100 + limit: Int = REQ_LIMIT_MAX ): Single> = SearchAccountHistory(accountId, order, from, limit).toRequest() /** diff --git a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt b/library/src/main/java/ch/decent/sdk/api/AssetApi.kt index 0e609a5c..899a90cc 100644 --- a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/AssetApi.kt @@ -91,7 +91,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return the assets found */ @JvmOverloads - fun listAllRelative(lowerBound: String, limit: Int = 100): Single> = ListAssets(lowerBound, limit).toRequest() + fun listAllRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX): Single> = ListAssets(lowerBound, limit).toRequest() @JvmOverloads fun listAll(includeMonitored: Boolean = false): Single> = @@ -180,7 +180,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { symbol: String, precision: Byte, description: String, - options: AssetOptions = AssetOptions(ExchangeRate.forCreateOp(1, 1)), + options: AssetOptions = AssetOptions(), fee: Fee = Fee() ): Single = createAssetCreateOperation(credentials.account, symbol, precision, description, options, fee = fee) diff --git a/library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt b/library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt index c10ec7b0..98325e8d 100644 --- a/library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt @@ -15,6 +15,9 @@ import org.threeten.bp.Duration class BroadcastApi internal constructor(api: DCoreApi) : BaseApi(api) { + internal val transactionExpiration: Duration + get() = api.transactionExpiration + /** * broadcast transaction to DCore * @param transaction transaction to broadcast diff --git a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt b/library/src/main/java/ch/decent/sdk/api/ContentApi.kt index 1d5679e0..36b274f2 100644 --- a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/ContentApi.kt @@ -34,6 +34,7 @@ import ch.decent.sdk.net.model.request.GetContentByUri import ch.decent.sdk.net.model.request.ListPublishingManagers import ch.decent.sdk.net.model.request.RestoreEncryptionKey import ch.decent.sdk.net.model.request.SearchContent +import ch.decent.sdk.utils.REQ_LIMIT_MAX import io.reactivex.Single import org.threeten.bp.LocalDateTime @@ -85,7 +86,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of publishing managers */ @JvmOverloads - fun listAllPublishersRelative(lowerBound: String, limit: Int = 100): Single> = ListPublishingManagers(lowerBound, limit).toRequest() + fun listAllPublishersRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX): Single> = ListPublishingManagers(lowerBound, limit).toRequest() /** * Restores encryption key from key parts stored in buying object. @@ -116,9 +117,9 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { order: SearchContentOrder = SearchContentOrder.CREATED_DESC, user: String = "", regionCode: String = Regions.ALL.code, - type: String = contentType(ApplicationType.DECENT_CORE, CategoryType.NONE), + type: String = contentType(), startId: ContentObjectId? = null, - limit: Int = 100 + limit: Int = REQ_LIMIT_MAX ): Single> = SearchContent(term, order, user, regionCode, type, startId, limit).toRequest() /** diff --git a/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt b/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt index ff4debf4..627eb727 100644 --- a/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt @@ -12,6 +12,7 @@ import ch.decent.sdk.net.model.request.GetAccountBalanceForTransaction import ch.decent.sdk.net.model.request.GetAccountHistory import ch.decent.sdk.net.model.request.GetRelativeAccountHistory import ch.decent.sdk.net.model.request.SearchAccountBalanceHistory +import ch.decent.sdk.utils.REQ_LIMIT_MAX import io.reactivex.Single class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { @@ -44,7 +45,7 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { accountId: AccountObjectId, startId: OperationHistoryObjectId? = null, stopId: OperationHistoryObjectId? = null, - limit: Int = 100 + limit: Int = REQ_LIMIT_MAX ): Single> = GetAccountHistory(accountId, stopId ?: OperationHistoryObjectId(), limit, startId ?: OperationHistoryObjectId()).toRequest() @@ -61,7 +62,7 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { fun listOperationsRelative( accountId: AccountObjectId, start: Int = 0, - limit: Int = 100 + limit: Int = REQ_LIMIT_MAX ): Single> = GetRelativeAccountHistory(accountId, 0, limit, start).toRequest() /** @@ -86,6 +87,6 @@ class HistoryApi internal constructor(api: DCoreApi) : BaseApi(api) { fromBlock: Long = 0, toBlock: Long = 0, startOffset: Long = 0, - limit: Int = 100 + limit: Int = REQ_LIMIT_MAX ): Single> = SearchAccountBalanceHistory(accountId, assets, recipientAccount, fromBlock, toBlock, startOffset, limit).toRequest() } diff --git a/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt b/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt index 52f371a6..d6f46a17 100644 --- a/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt @@ -16,6 +16,7 @@ import ch.decent.sdk.model.MessageResponse import ch.decent.sdk.model.TransactionConfirmation import ch.decent.sdk.model.operation.SendMessageOperation import ch.decent.sdk.net.model.request.GetMessageObjects +import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K import io.reactivex.Single import io.reactivex.functions.BiFunction @@ -31,7 +32,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of message operation responses */ @JvmOverloads - fun getAllOperations(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = 1000): Single> = + fun getAllOperations(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = GetMessageObjects(sender, receiver, maxCount).toRequest() /** @@ -44,7 +45,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAll(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = 1000): Single> = + fun getAll(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = GetMessageObjects(sender, receiver, maxCount).toRequest() .map { it.map { Message.create(it) }.flatten() } @@ -63,7 +64,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { credentials: Credentials, sender: AccountObjectId? = null, receiver: AccountObjectId? = null, - maxCount: Int = 1000 + maxCount: Int = REQ_LIMIT_MAX_1K ): Single> = require(sender == credentials.account || receiver == credentials.account) { "credentials account id must match either sender id or receiver id " }.let { @@ -81,7 +82,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAllDecryptedForSender(credentials: Credentials, maxCount: Int = 1000): Single> = + fun getAllDecryptedForSender(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = getAllDecrypted(credentials, sender = credentials.account, maxCount = maxCount) /** @@ -93,7 +94,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAllDecryptedForReceiver(credentials: Credentials, maxCount: Int = 1000): Single> = + fun getAllDecryptedForReceiver(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = getAllDecrypted(credentials, receiver = credentials.account, maxCount = maxCount) /** diff --git a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt b/library/src/main/java/ch/decent/sdk/api/MiningApi.kt index fca5a333..ded6e908 100644 --- a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/MiningApi.kt @@ -26,6 +26,8 @@ import ch.decent.sdk.net.model.request.GetNewAssetPerBlock import ch.decent.sdk.net.model.request.LookupMinerAccounts import ch.decent.sdk.net.model.request.LookupVoteIds import ch.decent.sdk.net.model.request.SearchMinerVoting +import ch.decent.sdk.utils.REQ_LIMIT_MAX +import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K import io.reactivex.Single import java.math.BigInteger @@ -58,7 +60,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { */ // todo model @JvmOverloads - fun getFeedsByMiner(account: AccountObjectId, count: Int = 100) = GetFeedsByMiner(account, count).toRequest() + fun getFeedsByMiner(account: AccountObjectId, count: Int = REQ_LIMIT_MAX) = GetFeedsByMiner(account, count).toRequest() /** * Get the miner owned by a given account. @@ -109,7 +111,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of found miner ids */ @JvmOverloads - fun listMinersRelative(lowerBound: String = "", limit: Int = 1000): Single> = LookupMinerAccounts(lowerBound, limit).toRequest() + fun listMinersRelative(lowerBound: String = "", limit: Int = REQ_LIMIT_MAX_1K): Single> = LookupMinerAccounts(lowerBound, limit).toRequest() /** * Given a set of votes, return the objects they are voting for. @@ -140,7 +142,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { id: MinerObjectId? = null, accountName: String? = null, onlyMyVotes: Boolean = false, - limit: Int = 1000 + limit: Int = REQ_LIMIT_MAX_1K ): Single> = SearchMinerVoting(accountName, searchTerm, onlyMyVotes, order, id, limit).toRequest() /** diff --git a/library/src/main/java/ch/decent/sdk/api/NftApi.kt b/library/src/main/java/ch/decent/sdk/api/NftApi.kt index e23a091f..20164c76 100644 --- a/library/src/main/java/ch/decent/sdk/api/NftApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/NftApi.kt @@ -472,7 +472,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { from: AccountObjectId, to: AccountObjectId, id: NftDataObjectId, - memo: Memo?, + memo: Memo? = null, fee: Fee = Fee() ): Single = Single.just(NftTransferOperation(from, to, id, memo, fee)) diff --git a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt b/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt index 0ad0731b..fed67bef 100644 --- a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt @@ -19,6 +19,7 @@ import ch.decent.sdk.net.model.request.GetOpenBuyingsByConsumer import ch.decent.sdk.net.model.request.GetOpenBuyingsByUri import ch.decent.sdk.net.model.request.SearchBuyings import ch.decent.sdk.net.model.request.SearchFeedback +import ch.decent.sdk.utils.REQ_LIMIT_MAX import io.reactivex.Single class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { @@ -87,7 +88,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { term: String = "", from: PurchaseObjectId? = null, order: SearchPurchasesOrder = SearchPurchasesOrder.PURCHASED_DESC, - limit: Int = 100 + limit: Int = REQ_LIMIT_MAX ): Single> = SearchBuyings(consumer, order, from, term, limit).toRequest() /** @@ -104,7 +105,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { fun findAllForFeedback( uri: String, user: String? = null, - count: Int = 100, + count: Int = REQ_LIMIT_MAX, startId: PurchaseObjectId? = null ): Single> = SearchFeedback(user, uri, startId, count).toRequest() diff --git a/library/src/main/java/ch/decent/sdk/api/SeederApi.kt b/library/src/main/java/ch/decent/sdk/api/SeederApi.kt index 5fdcdcaa..98d65fd7 100644 --- a/library/src/main/java/ch/decent/sdk/api/SeederApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/SeederApi.kt @@ -12,6 +12,7 @@ import ch.decent.sdk.net.model.request.ListSeedersByPrice import ch.decent.sdk.net.model.request.ListSeedersByRating import ch.decent.sdk.net.model.request.ListSeedersByRegion import ch.decent.sdk.net.model.request.ListSeedersByUpload +import ch.decent.sdk.utils.REQ_LIMIT_MAX import io.reactivex.Single class SeederApi internal constructor(api: DCoreApi) : BaseApi(api) { @@ -32,7 +33,7 @@ class SeederApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of seeders */ @JvmOverloads - fun listByPrice(count: Int = 100): Single> = ListSeedersByPrice(count).toRequest() + fun listByPrice(count: Int = REQ_LIMIT_MAX): Single> = ListSeedersByPrice(count).toRequest() /** * Get a list of seeders ordered by total upload, in decreasing order. @@ -42,7 +43,7 @@ class SeederApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of seeders */ @JvmOverloads - fun listByUpload(count: Int = 100): Single> = ListSeedersByUpload(count).toRequest() + fun listByUpload(count: Int = REQ_LIMIT_MAX): Single> = ListSeedersByUpload(count).toRequest() /** * Get a list of seeders ordered by price. @@ -62,6 +63,6 @@ class SeederApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a list of seeders */ @JvmOverloads - fun listByRating(count: Int = 100): Single> = ListSeedersByRating(count).toRequest() + fun listByRating(count: Int = REQ_LIMIT_MAX): Single> = ListSeedersByRating(count).toRequest() } diff --git a/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt b/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt index 2b74713e..60a94b0f 100644 --- a/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt @@ -18,6 +18,9 @@ import org.threeten.bp.Duration class TransactionApi internal constructor(api: DCoreApi) : BaseApi(api) { + internal val transactionExpiration: Duration + get() = api.transactionExpiration + /** * create unsigned transaction * diff --git a/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt b/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt index e64d30b0..f339aaa2 100644 --- a/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt +++ b/library/src/main/java/ch/decent/sdk/crypto/Wallet.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.crypto -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.model.Account import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.CipherKeyPairAdapter @@ -79,7 +79,7 @@ object Wallet { fun exportDCoreWallet(credentials: Credentials, account: Account, password: String, chainId: String): DCoreWallet { require(credentials.account == account.id) val pass = MessageDigest.getInstance("SHA-512").digest(password.toByteArray()) - val gson = DCoreSdk.gsonBuilder + val gson = DCoreClient.gsonBuilder .registerTypeAdapter(Wallet.ExtraKeys::class.java, ExtraKeysAdapter) .registerTypeAdapter(Wallet.CipherKeyPair::class.java, CipherKeyPairAdapter) .create() @@ -90,7 +90,7 @@ object Wallet { fun importDCoreWallet(walletJson: String, password: String): Credentials { val pass = MessageDigest.getInstance("SHA-512").digest(password.toByteArray()) - val gson = DCoreSdk.gsonBuilder + val gson = DCoreClient.gsonBuilder .registerTypeAdapter(Wallet.ExtraKeys::class.java, ExtraKeysAdapter) .registerTypeAdapter(Wallet.CipherKeyPair::class.java, CipherKeyPairAdapter) .create() diff --git a/library/src/main/java/ch/decent/sdk/model/AssetOptions.kt b/library/src/main/java/ch/decent/sdk/model/AssetOptions.kt index 1b2fa754..734338ad 100644 --- a/library/src/main/java/ch/decent/sdk/model/AssetOptions.kt +++ b/library/src/main/java/ch/decent/sdk/model/AssetOptions.kt @@ -5,7 +5,7 @@ import ch.decent.sdk.model.types.Int64 import com.google.gson.annotations.SerializedName data class AssetOptions( - @SerializedName("core_exchange_rate") val exchangeRate: ExchangeRate, + @SerializedName("core_exchange_rate") val exchangeRate: ExchangeRate = ExchangeRate.forCreateOp(1, 1), @SerializedName("max_supply") @Int64 val maxSupply: Long = DCoreConstants.MAX_SHARE_SUPPLY, @SerializedName("is_exchangeable") val exchangeable: Boolean = true, @SerializedName("extensions") val extensions: FixedMaxSupply? = FixedMaxSupply(false) diff --git a/library/src/main/java/ch/decent/sdk/model/ContentTypes.kt b/library/src/main/java/ch/decent/sdk/model/ContentTypes.kt index 69d2bbb9..822c4071 100644 --- a/library/src/main/java/ch/decent/sdk/model/ContentTypes.kt +++ b/library/src/main/java/ch/decent/sdk/model/ContentTypes.kt @@ -3,7 +3,8 @@ package ch.decent.sdk.model /** * create content type string */ -fun contentType(app: ApplicationType, category: CategoryType): String = "${app.ordinal}.${category.ordinal}.0" +fun contentType(app: ApplicationType = ApplicationType.DECENT_CORE, category: CategoryType = CategoryType.NONE): String = + "${app.ordinal}.${category.ordinal}.0" enum class ApplicationType { DECENT_CORE, diff --git a/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt index bc19ae10..77a38bc1 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.model.operation import ch.decent.sdk.DCoreApi -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee import ch.decent.sdk.model.MessagePayload @@ -18,7 +18,7 @@ class SendMessageOperation : CustomOperation { /** * Send message operation. * - * @param gson GSON object to serialize message payload, [DCoreApi.gson] or [DCoreSdk.gsonBuilder] can be used + * @param gson GSON object to serialize message payload, [DCoreApi.gson] or [DCoreClient.gsonBuilder] can be used * @param message message payload * @param payer account id to pay for the operation * @param fee [Fee] fee for the operation, by default the fee will be computed in DCT asset. diff --git a/library/src/main/java/ch/decent/sdk/net/rpc/RpcService.kt b/library/src/main/java/ch/decent/sdk/net/rpc/RpcService.kt index ee2cbdf8..0e0a7f13 100644 --- a/library/src/main/java/ch/decent/sdk/net/rpc/RpcService.kt +++ b/library/src/main/java/ch/decent/sdk/net/rpc/RpcService.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.net.rpc -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.exception.DCoreException import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.net.model.request.BaseRequest @@ -29,7 +29,7 @@ internal class RpcService(url: String, client: OkHttpClient, private val gson: G private val service = Retrofit.Builder() .baseUrl(url) .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) - .addConverterFactory(GsonConverterFactory.create(DCoreSdk.gsonBuilder.create())) + .addConverterFactory(GsonConverterFactory.create(DCoreClient.gsonBuilder.create())) .client(client) .build() .create(RpcEndpoint::class.java) diff --git a/library/src/main/java/ch/decent/sdk/poet/Blocking.kt b/library/src/main/java/ch/decent/sdk/poet/Blocking.kt new file mode 100644 index 00000000..a2116466 --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/poet/Blocking.kt @@ -0,0 +1,208 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList", + "SpreadOperator", + "ComplexMethod", + "ThrowsCount" +) + +package ch.decent.sdk.poet + +import ch.decent.sdk.DCoreApi +import ch.decent.sdk.DCoreClient +import com.squareup.kotlinpoet.AnnotationSpec +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.CodeBlock +import com.squareup.kotlinpoet.FileSpec +import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.KModifier +import com.squareup.kotlinpoet.MemberName +import com.squareup.kotlinpoet.ParameterSpec +import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy +import com.squareup.kotlinpoet.PropertySpec +import com.squareup.kotlinpoet.TypeName +import com.squareup.kotlinpoet.TypeSpec +import com.squareup.kotlinpoet.TypeVariableName +import com.squareup.kotlinpoet.asClassName +import com.squareup.kotlinpoet.asTypeName +import io.reactivex.Single +import kastree.ast.Node +import kastree.ast.psi.Parser +import okhttp3.OkHttpClient +import org.slf4j.Logger +import java.io.File +import kotlin.reflect.KClass +import kotlin.reflect.full.declaredMembers + +fun Any?.print() = println(this.toString()) + +fun main() { +// val path = System.out + val path = out + Blocking.apiFiles.forEach { + it.writeTo(path) + println() + } + Blocking.apiFile.writeTo(path) + Factory.file.writeTo(path) +} + +fun Node.Expr.name() = (this as Node.Expr.Name).name +fun Node.File.structured() = this.decls.single() as Node.Decl.Structured +fun Node.WithModifiers.hasKeyword(keyword: Node.Modifier.Keyword) = this.mods.contains(Node.Modifier.Lit(keyword)) +fun Node.Decl.Func.Param.isNullable() = this.type?.ref is Node.TypeRef.Nullable +fun Node.Decl.Func.paramNames() = this.params.joinToString { it.name } + +fun Node.Decl.Func.paramSpecs(imports: List) = this.params.map { p -> + fun Node.Expr.defaultValue() = when (this) { + is Node.Expr.Const -> CodeBlock.of(this.value) + is Node.Expr.StringTmpl -> CodeBlock.of("%S", "") + is Node.Expr.BinaryOp -> { + when { + this.lhs is Node.Expr.Name && this.lhs.name() == apiNameRef -> CodeBlock.of("$apiNameRef.${this.rhs.name()}") + this.lhs is Node.Expr.Name -> CodeBlock.of("%T.${this.rhs.name()}", ClassName.bestGuess(this.lhs.name().fullName(imports))) + this.lhs is Node.Expr.BinaryOp -> (this.lhs as Node.Expr.BinaryOp) + .let { CodeBlock.of("%T.${it.rhs.name()}.${this.rhs.name()}", ClassName.bestGuess(it.lhs.name().fullName(imports))) } + else -> throw IllegalStateException() + } + } + is Node.Expr.Name -> CodeBlock.of("%M", this.name.member(imports)) + is Node.Expr.Call -> { + when { + this.args.isEmpty() && this.expr.name().first().isLowerCase() -> CodeBlock.of("%M()", this.expr.name().member(imports)) + this.args.isEmpty() -> CodeBlock.of("%T()", ClassName.bestGuess(this.expr.name().fullName(imports))) + else -> throw IllegalStateException() + } + } + else -> throw IllegalStateException() + } + val builder = ParameterSpec.builder(p.name, p.type!!.typeName(imports).copy(nullable = p.isNullable())) + p.default?.let { builder.defaultValue(it.defaultValue()) } + return@map builder.build() +} + +fun Node.TypeRef.Simple.fullName(imports: List) = this.pieces.single().name.fullName(imports) + +fun String.member(imports: List) = MemberName(fullName(imports).substringBeforeLast("."), this) + +fun String.fullName(imports: List) = when (this) { + "Class" -> "java.lang.$this" + "List", "Map", "emptyList" -> "kotlin.collections.$this" + "Long", "Int", "Short", "Byte", "String", "Boolean" -> "kotlin.$this" + else -> imports.find { it.substringAfterLast(".") == this }?.substringAfter("import ") +} ?: this + +fun Node.Type.typeName(imports: List): TypeName { + fun recursive(r: Node.TypeRef?): TypeName { + val type = when { + r is Node.TypeRef.Simple && r.pieces.single().typeParams.isEmpty() -> ClassName.bestGuess(r.fullName(imports)) + r is Node.TypeRef.Simple -> ClassName.bestGuess(r.fullName(imports)).parameterizedBy(*r.pieces.single().typeParams.map { recursive(it?.ref) }.toTypedArray()) + r is Node.TypeRef.Nullable -> recursive(r.type) + else -> throw IllegalStateException("unknown node: $r") + } + return if (type is ClassName && type.simpleName == "T") TypeVariableName("T") + else type + } + + return recursive(this.ref) +} + +fun Node.TypeParam.typeName(imports: List): TypeVariableName = + TypeVariableName(name, ClassName.bestGuess((type!! as Node.TypeRef.Simple).fullName(imports))) + +val out = File("library/src-gen/main/java") +val srcApi = "library/src/main/java/ch/decent/sdk/api/" +val packageName = "ch.decent.sdk" +val apiNameRef = "api" +val clientRef = DCoreClient::class.asClassName() +val apiRef = DCoreApi::class.asClassName() + +val apiClasses = File(srcApi).listFiles()!!.map { Parser.parseFile(it.readText()) } + .filterNot { it.structured().hasKeyword(Node.Modifier.Keyword.ABSTRACT) } + .filterNot { it.structured().name == "CallbackApi" } + +object Factory { + + private fun nullable(name: String, klass: KClass<*>) = + ParameterSpec.builder(name, klass.asTypeName().copy(nullable = true)).defaultValue("null").build() + + fun builder(apiName: String, apiFile: FileSpec) = FunSpec.builder(apiName) + .addParameter("client", OkHttpClient::class) + .addParameter(nullable("websocketUrl", String::class)) + .addParameter(nullable("httpUrl", String::class)) + .addParameter(nullable("logger", Logger::class)) + .addStatement("return %T(%T(%T(client, websocketUrl, httpUrl, logger)))", ClassName(apiFile.packageName, apiFile.name), apiRef, clientRef) + .build() + + val file = FileSpec.builder("ch.decent.sdk", "DCoreSdk") + .addType(TypeSpec.objectBuilder("DCoreSdk") + .addFunction(builder("createApiBlocking", Blocking.apiFile)) + .build()) + .build() +} + +object Blocking { + + val pckg = "$packageName.api.blocking" + private val blockingGet = Single<*>::blockingGet.name + private val members = apiClasses.map { ClassName(pckg, it.structured().name) } + + val api = TypeSpec.classBuilder("DCoreApi") + .primaryConstructor(FunSpec.constructorBuilder() + .addParameter(apiNameRef, apiRef) + .build()) + .addProperties(members.map { + val name = it.simpleName.decapitalize() + PropertySpec.builder(name, it) + .initializer("%T($apiNameRef.$name)", it) + .build() + }) + .build() + val apiFile = FileSpec.builder(pckg, api.name!!).addType(api).build() + + val apis = apiClasses.map { + + val klass = ClassName(it.pkg!!.names.joinToString("."), it.structured().name) + + val apiProp = PropertySpec.builder(apiNameRef, klass, KModifier.PRIVATE) + .initializer(apiNameRef) + .build() + + val ctor = FunSpec.constructorBuilder() + .addModifiers(KModifier.INTERNAL) + .addParameter(apiProp.name, apiProp.type, KModifier.PRIVATE) + .build() + + val methods = it.structured().members + .filterIsInstance() + .filterNot { it.hasKeyword(Node.Modifier.Keyword.PRIVATE) } + .map { f -> + val i = it.imports.map { it.names.joinToString(".") } + val b = FunSpec.builder(f.name!!) + .addCode("return $apiNameRef.%L(${f.paramNames()}).%L()", f.name, blockingGet) + .addParameters(f.paramSpecs(i)) + + if (f.typeParams.isNotEmpty()) { + b.addTypeVariable(f.typeParams.single().typeName(i)) + } + b.build() + } + + TypeSpec.classBuilder(klass) + .addProperty(apiProp) + .primaryConstructor(ctor) + .addFunctions(methods) + .build() + } + val apiFiles = apis.map { + FileSpec.builder(pckg, it.name!!) + .addAnnotation( + AnnotationSpec.builder(Suppress::class) + .addMember("%S", "TooManyFunctions") + .addMember("%S", "LongParameterList") + .build() + ) + .addType(it) + .build() + } +} diff --git a/library/src/test/java/ch/decent/sdk/CrytpoTest.kt b/library/src/test/java/ch/decent/sdk/CrytpoTest.kt index d3522432..899d4b51 100644 --- a/library/src/test/java/ch/decent/sdk/CrytpoTest.kt +++ b/library/src/test/java/ch/decent/sdk/CrytpoTest.kt @@ -234,11 +234,11 @@ class CrytpoTest : TimeOutTest() { "top_n_control_flags": 0 } """ - val account = DCoreSdk.gsonBuilder.create().fromJson(json, Account::class.java) + val account = DCoreClient.gsonBuilder.create().fromJson(json, Account::class.java) val wallet = Wallet.exportDCoreWallet(credentials, account, "pw", "17401602b201b3c45a3ad98afc6fb458f91f519bd30d1058adf6f2bed66376bc") - val gson = DCoreSdk.gsonBuilder + val gson = DCoreClient.gsonBuilder .registerTypeAdapter(Wallet.ExtraKeys::class.java, ExtraKeysAdapter) .registerTypeAdapter(Wallet.CipherKeyPair::class.java, CipherKeyPairAdapter) .create() diff --git a/library/src/test/java/ch/decent/sdk/Scratchpad.kt b/library/src/test/java/ch/decent/sdk/Scratchpad.kt index d56906c4..2a8449f7 100644 --- a/library/src/test/java/ch/decent/sdk/Scratchpad.kt +++ b/library/src/test/java/ch/decent/sdk/Scratchpad.kt @@ -181,12 +181,12 @@ class Scratchpad { @Test fun `processed transaction result`() { val str = "{\"id\":\"3d91dae75b55e34cddf43ebc56aeec8488db8012\",\"block_num\":454977,\"trx_num\":0,\"trx\":{\"ref_block_num\":61760,\"ref_block_prefix\":1485276657,\"expiration\":\"2018-03-22T12:56:29\",\"operations\":[[0,{\"fee\":{\"amount\":500000,\"asset_id\":\"1.3.0\"},\"from\":\"1.2.30\",\"to\":\"1.2.31\",\"amount\":{\"amount\":150000000,\"asset_id\":\"1.3.0\"},\"memo\":{\"from\":\"DCT6MA5TQQ6UbMyMaLPmPXE2Syh5G3ZVhv5SbFedqLPqdFChSeqTz\",\"to\":\"DCT6bVmimtYSvWQtwdrkVVQGHkVsTJZVKtBiUqf4YmJnrJPnk89QP\",\"nonce\":\"1029839728655420928\",\"message\":\"4acb403a35d4b73ec88a1cd287d93ccebd07809941b182b54c54ddb718ff98be\"},\"extensions\":[]}]],\"extensions\":[],\"signatures\":[\"1f75e472a20d5a8cdddccb26957a20b87c7fb8e6788d3c7cccd0abf48bd94455517c609bb4186821480655eb57a7956785e3c611ed61d2d9ef07c173969ddfffc0\"],\"operation_results\":[[0,{}]]}}" - val trx = DCoreSdk.gsonBuilder.create().fromJson(str, TransactionConfirmation::class.java) + val trx = DCoreClient.gsonBuilder.create().fromJson(str, TransactionConfirmation::class.java) println(trx) } /* @Test fun `transfers to various receivers`() { - val api = DCoreSdk.createApiRx(client, url, logger = LoggerFactory.getLogger("DCoreApi")) + val api = DCoreClient.createApiRx(client, url, logger = LoggerFactory.getLogger("DCoreApi")) val dpk = DumpedPrivateKey.fromBase58(private) val key = ECKeyPair.fromPrivate(dpk.bytes, dpk.compressed) val credentials = Credentials(account, key) @@ -291,7 +291,7 @@ class Scratchpad { @Test fun `custom operation`() { val logger = LoggerFactory.getLogger("LOG") - val api = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) + val api = DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) val op = CustomOperation(4, Helpers.account, listOf(Helpers.account), "hello data".toByteArray().hex()) api.broadcastApi.broadcastWithCallback(Helpers.private, op) diff --git a/library/src/test/java/ch/decent/sdk/api/Base.kt b/library/src/test/java/ch/decent/sdk/api/Base.kt index 1e42e989..cfc3d48f 100644 --- a/library/src/test/java/ch/decent/sdk/api/Base.kt +++ b/library/src/test/java/ch/decent/sdk/api/Base.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.Helpers import ch.decent.sdk.TimeOutTest import org.junit.After @@ -33,8 +33,8 @@ abstract class BaseApiTest(private val channel: Channel) : TimeOutTest() { val logger = LoggerFactory.getLogger(channel.toString()) api = when (channel) { - Channel.RpcService -> DCoreSdk.createForHttp(Helpers.client(logger), Helpers.httpUrl, logger) - Channel.RxWebSocket -> DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) + Channel.RpcService -> DCoreClient.createForHttp(Helpers.client(logger), Helpers.httpUrl, logger) + Channel.RxWebSocket -> DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) } } @@ -54,7 +54,7 @@ abstract class BaseOperationsTest { @Before fun init() { val logger = LoggerFactory.getLogger("RxWebSocket") - api = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) + api = DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) api.transactionExpiration = Duration.ofSeconds(5) } diff --git a/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt b/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt index bfd02ff0..ddecb883 100644 --- a/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.api import ch.decent.sdk.DCoreApi -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.Helpers import io.reactivex.schedulers.Schedulers import org.junit.After @@ -17,14 +17,14 @@ class CallbackApiTest { @Before fun init() { val logger = LoggerFactory.getLogger("RxWebSocket") - api = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) + api = DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) } @After fun finish() { } @Test fun `should fail for HTTP`() { - api = DCoreSdk.createForHttp(Helpers.client(), Helpers.httpUrl) + api = DCoreClient.createForHttp(Helpers.client(), Helpers.httpUrl) val test = api.callbackApi.onBlockApplied() .subscribeOn(Schedulers.newThread()) diff --git a/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt b/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt index 5cb6d432..03ff13f8 100644 --- a/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/SeederApiTest.kt @@ -13,22 +13,22 @@ import org.junit.runners.Parameterized class SeederApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get seeder by id`() { - api.seedersApi.get("1.2.17".toObjectId()).testCheck() + api.seederApi.get("1.2.17".toObjectId()).testCheck() } @Test fun `should list seeders by price`() { - api.seedersApi.listByPrice().testCheck() + api.seederApi.listByPrice().testCheck() } @Test fun `should list seeders by upload`() { - api.seedersApi.listByUpload().testCheck() + api.seederApi.listByUpload().testCheck() } @Test fun `should list seeders by region`() { - api.seedersApi.listByRegion(Regions.NONE.code).testCheck() + api.seederApi.listByRegion(Regions.NONE.code).testCheck() } @Test fun `should list seeders by rating`() { - api.seedersApi.listByRating(10).testCheck() + api.seederApi.listByRating(10).testCheck() } } diff --git a/library/src/test/java/ch/decent/sdk/java/ApiTest.java b/library/src/test/java/ch/decent/sdk/java/ApiTest.java index 819a8360..acb91fe7 100644 --- a/library/src/test/java/ch/decent/sdk/java/ApiTest.java +++ b/library/src/test/java/ch/decent/sdk/java/ApiTest.java @@ -2,7 +2,7 @@ import ch.decent.sdk.DCoreApi; import ch.decent.sdk.DCoreConstants; -import ch.decent.sdk.DCoreSdk; +import ch.decent.sdk.DCoreClient; import ch.decent.sdk.Helpers; import ch.decent.sdk.crypto.Address; import ch.decent.sdk.crypto.ECKeyPair; @@ -13,7 +13,6 @@ import ch.decent.sdk.model.operation.TransferOperation; import ch.decent.sdk.utils.Utils; import com.google.gson.Gson; -import kotlin.Pair; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,7 +21,6 @@ import java.util.Arrays; import java.util.Collections; -import java.util.Map; /** * this test checks calling Kotlin from Java @@ -31,15 +29,15 @@ public class ApiTest { private Logger logger = LoggerFactory.getLogger("API"); - private DCoreApi api = DCoreSdk.create(Helpers.client(logger), Helpers.getWsUrl(), Helpers.getHttpUrl(), logger); + private DCoreApi api = DCoreClient.create(Helpers.client(logger), Helpers.getWsUrl(), Helpers.getHttpUrl(), logger); @Test public void init() { - DCoreApi apiHttp = DCoreSdk.createForHttp(Helpers.client(logger), Helpers.getHttpUrl()); - apiHttp = DCoreSdk.createForHttp(Helpers.client(logger), Helpers.getHttpUrl(), logger); - DCoreApi apiWs = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.getWsUrl()); - apiWs = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.getWsUrl(), logger); - Gson gson = DCoreSdk.getGsonBuilder().create(); + DCoreApi apiHttp = DCoreClient.createForHttp(Helpers.client(logger), Helpers.getHttpUrl()); + apiHttp = DCoreClient.createForHttp(Helpers.client(logger), Helpers.getHttpUrl(), logger); + DCoreApi apiWs = DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.getWsUrl()); + apiWs = DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.getWsUrl(), logger); + Gson gson = DCoreClient.getGsonBuilder().create(); apiHttp.setTransactionExpiration(Duration.ofSeconds(100L)); } diff --git a/library/src/test/java/ch/decent/sdk/model/AssetTest.kt b/library/src/test/java/ch/decent/sdk/model/AssetTest.kt index f7b57300..84e466b0 100644 --- a/library/src/test/java/ch/decent/sdk/model/AssetTest.kt +++ b/library/src/test/java/ch/decent/sdk/model/AssetTest.kt @@ -1,7 +1,7 @@ package ch.decent.sdk.model import ch.decent.sdk.DCoreConstants -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import org.junit.Assert import org.junit.Test import java.math.RoundingMode @@ -158,7 +158,7 @@ class AssetTest { @Test fun `json mapping for monitored assets options`() { - val gson = DCoreSdk.gsonBuilder.create() + val gson = DCoreClient.gsonBuilder.create() val source = """{"id":"1.3.1","symbol":"USD","precision":4,"issuer":"1.2.20","description":"US dollar","monitored_asset_opts":{"feeds":[["1.2.1948",["2019-01-26T14:08:25",{"core_exchange_rate":{"base":{"amount":539041491,"asset_id":"1.3.1"},"quote":{"amount":"100000000000000","asset_id":"1.3.0"}}}]],["1.2.2044",["2017-09-28T12:17:55",{"core_exchange_rate":{"base":{"amount":628945,"asset_id":"1.3.1"},"quote":{"amount":"10000000000","asset_id":"1.3.0"}}}]],["1.2.2064",["2017-09-11T13:00:05",{"core_exchange_rate":{"base":{"amount":69014,"asset_id":"1.3.1"},"quote":{"amount":100000,"asset_id":"1.3.0"}}}]],["1.2.3149",["2018-05-17T11:12:20",{"core_exchange_rate":{"base":{"amount":805024,"asset_id":"1.3.1"},"quote":{"amount":"10000000000","asset_id":"1.3.0"}}}]],["1.2.3466",["2017-08-29T23:00:10",{"core_exchange_rate":{"base":{"amount":122419,"asset_id":"1.3.1"},"quote":{"amount":1000000000,"asset_id":"1.3.0"}}}]],["1.2.4435",["2017-11-03T06:00:10",{"core_exchange_rate":{"base":{"amount":416409,"asset_id":"1.3.1"},"quote":{"amount":"10000000000","asset_id":"1.3.0"}}}]]],"current_feed":{"core_exchange_rate":{"base":{"amount":0,"asset_id":"1.3.0"},"quote":{"amount":0,"asset_id":"1.3.0"}}},"current_feed_publication_time":"2019-04-09T14:08:25","feed_lifetime_sec":86400,"minimum_feeds":1},"options":{"max_supply":0,"core_exchange_rate":{"base":{"amount":0,"asset_id":"1.3.0"},"quote":{"amount":0,"asset_id":"1.3.0"}},"is_exchangeable":true,"extensions":[]},"dynamic_asset_data_id":"2.3.1"}""" assertNotNull(gson.fromJson(source, Asset::class.java).monitoredAssetOpts) val sourceWithoutMonitoredOptions = """{"id":"1.3.0","symbol":"DCT","precision":8,"issuer":"1.2.1","description":"","options":{"max_supply":"7319777577456900","core_exchange_rate":{"base":{"amount":1,"asset_id":"1.3.0"},"quote":{"amount":1,"asset_id":"1.3.0"}},"is_exchangeable":true,"extensions":[]},"dynamic_asset_data_id":"2.3.0"}""" diff --git a/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt b/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt index bd94990b..70a631dd 100644 --- a/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt +++ b/library/src/test/java/ch/decent/sdk/net/SerializerTest.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.net -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.Helpers import ch.decent.sdk.TimeOutTest import ch.decent.sdk.crypto.Address @@ -150,7 +150,7 @@ class SerializerTest : TimeOutTest() { "top_n_control_flags": 0 } """ - val account = DCoreSdk.gsonBuilder.create().fromJson(json, Account::class.java) + val account = DCoreClient.gsonBuilder.create().fromJson(json, Account::class.java) val op = AccountUpdateOperation( account.id, @@ -199,7 +199,7 @@ class SerializerTest : TimeOutTest() { @Test fun `should serialize transfer op transaction`() { val expected = "3e322ef4e4170c88615b012720a10700000000000022230000000000020160e3160000000000000102c03f8e840c1699fd7808c2bb858e249c688c5be8acf0a0c1c484ab0cfb27f0a802e0ced80260630f641f61f6d6959f32b5c43b1a38be55666b98abfe8bafcc556b002ea2558d64350a204bc2a1ee670302ceddb897c2d351fa0496ff089c934e35e030f8ae4f3f9397a70000" - val gson = DCoreSdk.gsonBuilder.create() + val gson = DCoreClient.gsonBuilder.create() val rawOp = """{"from":"1.2.34","to":"1.2.35","amount":{"amount":1500000,"asset_id":"1.3.0"},"memo":{"from":"DCT6MA5TQQ6UbMyMaLPmPXE2Syh5G3ZVhv5SbFedqLPqdFChSeqTz","to":"DCT6bVmimtYSvWQtwdrkVVQGHkVsTJZVKtBiUqf4YmJnrJPnk89QP","message":"4bc2a1ee670302ceddb897c2d351fa0496ff089c934e35e030f8ae4f3f9397a7","nonce":735604672334802432},"fee":{"amount":500000,"asset_id":"1.3.0"}}""" val op = gson.fromJson(rawOp, TransferOperation::class.java) op.type = OperationType.TRANSFER2_OPERATION @@ -226,7 +226,7 @@ class SerializerTest : TimeOutTest() { val memo = Memo("hello messaging api", keyPair, public2, 4764221389359926272.toBigInteger()) val payloadReceiver = MessagePayloadReceiver("1.2.28".toObjectId(), memo.message, public2, memo.nonce) val payload = MessagePayload("1.2.27".toObjectId(), listOf(payloadReceiver), public) - val gson = DCoreSdk.gsonBuilder.create() + val gson = DCoreClient.gsonBuilder.create() val op = SendMessageOperation(gson, payload, "1.2.27".toObjectId(), Fee(amount = 500002)) Serializer.serialize(op).hex() `should be equal to` bytes @@ -357,7 +357,7 @@ class SerializerTest : TimeOutTest() { private fun BaseOperation.expected() { val logger = LoggerFactory.getLogger("serializer") - val api = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.dockerWs, logger) + val api = DCoreClient.createForWebSocket(Helpers.client(logger), Helpers.dockerWs, logger) api.transactionApi.createTransaction(this) .flatMap { api.transactionApi.getHexDump(it) } .blockingGet() diff --git a/library/src/test/java/ch/decent/sdk/net/ws/RxWebSocketTest.kt b/library/src/test/java/ch/decent/sdk/net/ws/RxWebSocketTest.kt index 6802ccf8..822d941d 100644 --- a/library/src/test/java/ch/decent/sdk/net/ws/RxWebSocketTest.kt +++ b/library/src/test/java/ch/decent/sdk/net/ws/RxWebSocketTest.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.net.ws -import ch.decent.sdk.DCoreSdk +import ch.decent.sdk.DCoreClient import ch.decent.sdk.Helpers import ch.decent.sdk.TimeOutTest import ch.decent.sdk.net.model.request.GetChainId @@ -8,7 +8,6 @@ import ch.decent.sdk.net.model.request.Login import ch.decent.sdk.net.ws.model.WebSocketClosedException import io.reactivex.Single import io.reactivex.schedulers.Schedulers -import io.reactivex.schedulers.TestScheduler import org.amshove.kluent.`should be equal to` import org.junit.After import org.junit.Before @@ -27,7 +26,7 @@ class RxWebSocketTest : TimeOutTest() { Helpers.client(logger), mock.getUrl(), logger = logger, - gson = DCoreSdk.gsonBuilder.create() + gson = DCoreClient.gsonBuilder.create() ) } From 3f63e9ff0e1aedf83bda363a0f8a3f56c5c0afb7 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Thu, 1 Aug 2019 17:58:24 +0200 Subject: [PATCH 03/19] added futures, callbacks, cleanup, separate module --- apiGen/build.gradle.kts | 16 ++ .../java/ch/decent/sdk/poet/ApiDescriptor.kt | 14 ++ .../main/java/ch/decent/sdk/poet/Builders.kt | 82 +++++++ .../main/java/ch/decent/sdk/poet/DocReader.kt | 59 +++++ .../main/java/ch/decent/sdk/poet/Factory.kt | 39 ++++ .../java/ch/decent/sdk/poet/KastreeExt.kt | 89 ++++++++ .../src/main/java/ch/decent/sdk/poet/Main.kt | 43 ++++ buildSrc/src/main/java/Dependencies.kt | 1 + library/build.gradle.kts | 19 +- .../main/java/ch/decent/sdk/DCoreSdk.kt | 15 -- .../ch/decent/sdk/api/blocking/AccountApi.kt | 99 --------- .../ch/decent/sdk/api/blocking/AssetApi.kt | 153 ------------- .../ch/decent/sdk/api/blocking/BalanceApi.kt | 34 --- .../ch/decent/sdk/api/blocking/BlockApi.kt | 16 -- .../decent/sdk/api/blocking/BroadcastApi.kt | 63 ------ .../ch/decent/sdk/api/blocking/ContentApi.kt | 149 ------------- .../ch/decent/sdk/api/blocking/DCoreApi.kt | 37 ---- .../ch/decent/sdk/api/blocking/GeneralApi.kt | 19 -- .../ch/decent/sdk/api/blocking/HistoryApi.kt | 43 ---- .../decent/sdk/api/blocking/MessagingApi.kt | 59 ----- .../ch/decent/sdk/api/blocking/MiningApi.kt | 55 ----- .../java/ch/decent/sdk/api/blocking/NftApi.kt | 172 --------------- .../ch/decent/sdk/api/blocking/PurchaseApi.kt | 54 ----- .../ch/decent/sdk/api/blocking/SeederApi.kt | 22 -- .../sdk/api/blocking/SubscriptionApi.kt | 24 -- .../decent/sdk/api/blocking/TransactionApi.kt | 30 --- .../decent/sdk/api/blocking/ValidationApi.kt | 37 ---- library/src/main/java/ch/decent/sdk/Apis.kt | 119 ---------- .../main/java/ch/decent/sdk/DCoreClient.kt | 1 + .../sdk/{DCoreApi.kt => api/BaseCoreApi.kt} | 46 +--- .../main/java/ch/decent/sdk/api/Callback.kt | 20 ++ .../ch/decent/sdk/api/{ => rx}/AccountApi.kt | 8 +- .../ch/decent/sdk/api/{ => rx}/AssetApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/BalanceApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/BaseApi.kt | 4 +- .../ch/decent/sdk/api/{ => rx}/BlockApi.kt | 6 +- .../decent/sdk/api/{ => rx}/BroadcastApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/CallbackApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/ContentApi.kt | 5 +- .../java/ch/decent/sdk/api/rx/DCoreApi.kt | 24 ++ .../ch/decent/sdk/api/{ => rx}/GeneralApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/HistoryApi.kt | 3 +- .../decent/sdk/api/{ => rx}/MessagingApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/MiningApi.kt | 5 +- .../java/ch/decent/sdk/api/{ => rx}/NftApi.kt | 14 +- .../ch/decent/sdk/api/{ => rx}/PurchaseApi.kt | 3 +- .../ch/decent/sdk/api/{ => rx}/SeederApi.kt | 3 +- .../sdk/api/{ => rx}/SubscriptionApi.kt | 3 +- .../decent/sdk/api/{ => rx}/TransactionApi.kt | 5 +- .../decent/sdk/api/{ => rx}/ValidationApi.kt | 3 +- .../model/operation/SendMessageOperation.kt | 2 +- .../main/java/ch/decent/sdk/poet/Blocking.kt | 208 ------------------ .../src/test/java/ch/decent/sdk/Scratchpad.kt | 5 + .../src/test/java/ch/decent/sdk/api/Base.kt | 2 +- .../java/ch/decent/sdk/api/CallbackApiTest.kt | 2 +- .../test/java/ch/decent/sdk/java/ApiTest.java | 2 +- settings.gradle.kts | 2 +- 57 files changed, 439 insertions(+), 1517 deletions(-) create mode 100644 apiGen/build.gradle.kts create mode 100644 apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt create mode 100644 apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt create mode 100644 apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt create mode 100644 apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt create mode 100644 apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt create mode 100644 apiGen/src/main/java/ch/decent/sdk/poet/Main.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt delete mode 100644 library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt delete mode 100644 library/src/main/java/ch/decent/sdk/Apis.kt rename library/src/main/java/ch/decent/sdk/{DCoreApi.kt => api/BaseCoreApi.kt} (58%) create mode 100644 library/src/main/java/ch/decent/sdk/api/Callback.kt rename library/src/main/java/ch/decent/sdk/api/{ => rx}/AccountApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/AssetApi.kt (99%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/BalanceApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/BaseApi.kt (90%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/BlockApi.kt (88%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/BroadcastApi.kt (99%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/CallbackApi.kt (96%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/ContentApi.kt (99%) create mode 100644 library/src/main/java/ch/decent/sdk/api/rx/DCoreApi.kt rename library/src/main/java/ch/decent/sdk/api/{ => rx}/GeneralApi.kt (97%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/HistoryApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/MessagingApi.kt (99%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/MiningApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/NftApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/PurchaseApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/SeederApi.kt (97%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/SubscriptionApi.kt (98%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/TransactionApi.kt (96%) rename library/src/main/java/ch/decent/sdk/api/{ => rx}/ValidationApi.kt (99%) delete mode 100644 library/src/main/java/ch/decent/sdk/poet/Blocking.kt diff --git a/apiGen/build.gradle.kts b/apiGen/build.gradle.kts new file mode 100644 index 00000000..da47462f --- /dev/null +++ b/apiGen/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { + kotlin("jvm") + id(GradlePlugins.errorProne) + application +} + +application { + mainClassName = "ch.decent.sdk.poet.MainKt" +} + +dependencies { + implementation(Libs.kotlin) + implementation(Libs.kotlinReflect) + implementation(Libs.kpoet) + implementation("com.github.cretz.kastree:kastree-ast-psi:0.4.0") +} diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt b/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt new file mode 100644 index 00000000..e9ad85ee --- /dev/null +++ b/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt @@ -0,0 +1,14 @@ +package ch.decent.sdk.poet + +import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.TypeName + +data class ApiDescriptor( + val packageSuffix: String, + val createMethodName: String, + val returnCodeBlock: String, + val returnType: (TypeName) -> TypeName = { it }, + val methodBuilder: (FunSpec.Builder) -> Any = { } +) { + val packageName = "$packageNameApi.$packageSuffix" +} diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt new file mode 100644 index 00000000..83047c29 --- /dev/null +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -0,0 +1,82 @@ +package ch.decent.sdk.poet + +import com.squareup.kotlinpoet.AnnotationSpec +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.FileSpec +import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.KModifier +import com.squareup.kotlinpoet.PropertySpec +import com.squareup.kotlinpoet.TypeSpec +import kastree.ast.Node + +object Builders { + + private fun apiClassSpec(api: ApiDescriptor) = TypeSpec.classBuilder(apiRef.simpleName) + .primaryConstructor(FunSpec.constructorBuilder() + .addParameter(apiNameRef, apiRef) + .build()) + .superclass(ClassName(packageNameApi, "BaseCoreApi")) + .addSuperclassConstructorParameter("$apiNameRef.core") + .addProperties(apiClasses.map { ClassName(api.packageName, it.structured().name) }.map { + val name = it.simpleName.decapitalize() + PropertySpec.builder(name, it) + .initializer("%T($apiNameRef.$name)", it) + .build() + }) + .build() + + fun apiFile(api: ApiDescriptor) = apiClassSpec(api).let { FileSpec.builder(api.packageName, it.name!!).addType(it).build() } + + private fun apiServiceClasses(api: ApiDescriptor): List = apiClasses +// .filter { it.structured().name == "NftApi" } + .map { + val klass = ClassName(it.pkg!!.names.joinToString("."), it.structured().name) + + val apiProp = PropertySpec.builder(apiNameRef, klass, KModifier.PRIVATE) + .initializer(apiNameRef) + .build() + + val ctor = FunSpec.constructorBuilder() + .addModifiers(KModifier.INTERNAL) + .addParameter(apiProp.name, apiProp.type, KModifier.PRIVATE) + .build() + + val apiDoc = DocReader.docs.getValue(klass.simpleName).toMutableList() + val methods = it.structured().members + .filterIsInstance() + .filterNot { it.hasKeyword(Node.Modifier.Keyword.PRIVATE) } + .map { f -> + val i = it.imports.map { it.names.joinToString(".") } + val returnType = f.type!!.returnType(i) + + val b = FunSpec.builder(f.name!!) + .addCode("return $apiNameRef.%L(${f.paramNames()}).%L", f.name, api.returnCodeBlock) + .addParameters(f.paramSpecs(i)) + .returns(api.returnType(returnType)) + + if (f.typeParams.isNotEmpty()) b.addTypeVariable(f.typeParams.single().typeName(i)) + DocReader.applyDocs(b, apiDoc, f, i) + api.methodBuilder(b) + + b.build() + } + + TypeSpec.classBuilder(klass) + .addProperty(apiProp) + .primaryConstructor(ctor) + .addFunctions(methods) + .build() + } + + fun apiServiceFiles(api: ApiDescriptor) = apiServiceClasses(api).map { + FileSpec.builder(api.packageName, it.name!!) + .addAnnotation( + AnnotationSpec.builder(Suppress::class) + .addMember("%S", "TooManyFunctions") + .addMember("%S", "LongParameterList") + .build() + ) + .addType(it) + .build() + } +} diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt b/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt new file mode 100644 index 00000000..336a26ee --- /dev/null +++ b/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt @@ -0,0 +1,59 @@ +package ch.decent.sdk.poet + +import com.squareup.kotlinpoet.FunSpec +import kastree.ast.Node +import java.io.File + +object DocReader { + private const val TOKEN_START = "/**" + private const val TOKEN_END = "*/" + private val REGEX_FUN = Regex("\\s*fun\\s(?:<.*?>\\s)?(\\w+)\\(.*") + val REGEX_DOC_LINK = Regex("\\[\\w+]") + + data class FunDoc(val name: String, val docs: String) + + private fun File.docs(): List { + val funDocs = mutableListOf() + useLines { + val iter = it.iterator() + var hasDoc = false + var acc = "" + while (iter.hasNext()) { + val line = iter.next().trim() + if (line.startsWith(TOKEN_END)) hasDoc = false + if (hasDoc) acc = acc + line.substringAfter("*").trim() + "\n" + if (line.matches(REGEX_FUN)) { + funDocs += FunDoc(REGEX_FUN.matchEntire(line)!!.groups[1]!!.value, acc) + acc = "" + } + if (line.startsWith(TOKEN_START)) hasDoc = true + } + } + return funDocs + } + + val docs: Map> + get() = File(srcApi).listFiles()!! + .associate { it.nameWithoutExtension to it.docs() } + + fun applyDocs(b: FunSpec.Builder, docs: MutableList, f: Node.Decl.Func, i: List) { + val doc = docs.find { it.name == f.name } + doc?.let { + val args = mutableListOf() + val withImports = it.docs.replace(REGEX_DOC_LINK) { + it.value.drop(1).dropLast(1).let { + if (it.first().isLowerCase()) { + args.add(it.member(i)) + "[%M]" + } else { + args.add(it.className(i)) + "[%T]" + } + } + } + b.addKdoc(withImports, *args.toTypedArray()) + docs.remove(it) + } + + } +} diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt new file mode 100644 index 00000000..28acf13b --- /dev/null +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt @@ -0,0 +1,39 @@ +package ch.decent.sdk.poet + +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.FileSpec +import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.ParameterSpec +import com.squareup.kotlinpoet.TypeSpec +import com.squareup.kotlinpoet.asClassName + +object Factory { + + private fun nullable(name: String, klass: ClassName) = + ParameterSpec.builder(name, klass.copy(nullable = true)).defaultValue("null").build() + + val params = listOf( + ParameterSpec.builder("client", ClassName.bestGuess("okhttp3.OkHttpClient")).build(), + nullable("websocketUrl", String::class.asClassName()), + nullable("httpUrl", String::class.asClassName()), + nullable("logger", ClassName.bestGuess("org.slf4j.Logger")) + ) + + fun builder(methodName: String, pckg: String) = FunSpec.builder(methodName) + .addParameters(params) + .addStatement("return %T(%T(%T(client, websocketUrl, httpUrl, logger)))", ClassName(pckg, apiRef.simpleName), apiRef, clientRef) + .build() + + val rx = FunSpec.builder("createApiRx") + .addParameters(params) + .addStatement("return %T(%T(client, websocketUrl, httpUrl, logger))", apiRef, clientRef) + .build() + + val file: FileSpec + get() = FileSpec.builder("ch.decent.sdk", "DCoreSdk") + .addType(TypeSpec.objectBuilder("DCoreSdk") + .addFunction(rx) + .apply { apis.forEach { addFunction(builder(it.createMethodName, it.packageName)) } } + .build()) + .build() +} diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt new file mode 100644 index 00000000..9efcad2f --- /dev/null +++ b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt @@ -0,0 +1,89 @@ +@file:Suppress( + "TooManyFunctions", + "LongParameterList", + "SpreadOperator", + "ComplexMethod", + "ThrowsCount" +) + +package ch.decent.sdk.poet + +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.CodeBlock +import com.squareup.kotlinpoet.MemberName +import com.squareup.kotlinpoet.ParameterSpec +import com.squareup.kotlinpoet.ParameterizedTypeName +import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy +import com.squareup.kotlinpoet.TypeName +import com.squareup.kotlinpoet.TypeVariableName +import kastree.ast.Node + +fun Node.Expr.name() = (this as Node.Expr.Name).name +fun Node.File.structured() = this.decls.single() as Node.Decl.Structured +fun Node.WithModifiers.hasKeyword(keyword: Node.Modifier.Keyword) = this.mods.contains(Node.Modifier.Lit(keyword)) +fun Node.Decl.Func.Param.isNullable() = this.type?.ref is Node.TypeRef.Nullable +fun Node.Decl.Func.paramNames() = this.params.joinToString { it.name } + +fun Node.Decl.Func.paramSpecs(imports: List) = this.params.map { p -> + fun Node.Expr.defaultValue() = when (this) { + is Node.Expr.Const -> CodeBlock.of(this.value) + is Node.Expr.StringTmpl -> CodeBlock.of("%S", "") + is Node.Expr.BinaryOp -> { + when { + this.lhs is Node.Expr.Name && this.lhs.name() == apiNameRef -> CodeBlock.of("$apiNameRef.${this.rhs.name()}") + this.lhs is Node.Expr.Name -> CodeBlock.of("%T.${this.rhs.name()}", this.lhs.name().className(imports)) + this.lhs is Node.Expr.BinaryOp -> (this.lhs as Node.Expr.BinaryOp) + .let { CodeBlock.of("%T.${it.rhs.name()}.${this.rhs.name()}", it.lhs.name().className(imports)) } + else -> throw IllegalStateException() + } + } + is Node.Expr.Name -> CodeBlock.of("%M", this.name.member(imports)) + is Node.Expr.Call -> { + when { + this.args.isEmpty() && this.expr.name().first().isLowerCase() -> CodeBlock.of("%M()", this.expr.name().member(imports)) + this.args.isEmpty() -> CodeBlock.of("%T()", this.expr.name().className(imports)) + else -> throw IllegalStateException() + } + } + else -> throw IllegalStateException() + } + + val builder = ParameterSpec.builder(p.name, p.type!!.typeName(imports).copy(nullable = p.isNullable())) + p.default?.let { builder.defaultValue(it.defaultValue()) } + return@map builder.build() +} + +fun Node.TypeRef.Simple.fullName(imports: List) = this.pieces.single().name.fullName(imports) +fun Node.TypeRef.Simple.className(imports: List) = ClassName.bestGuess(fullName(imports)) + +fun String.member(imports: List) = MemberName(fullName(imports).substringBeforeLast("."), this) + +fun String.fullName(imports: List) = when (this) { + "Class" -> "java.lang.$this" + "List", "Map", "emptyList" -> "kotlin.collections.$this" + "Long", "Int", "Short", "Byte", "String", "Boolean", "Unit", "Any" -> "kotlin.$this" + else -> imports.find { it.substringAfterLast(".") == this }?.substringAfter("import ") +} ?: this + +fun String.className(imports: List) = ClassName.bestGuess(fullName(imports)) + +fun Node.Type.typeName(imports: List): TypeName { + fun recursive(r: Node.TypeRef?): TypeName { + val type = when { + r is Node.TypeRef.Simple && r.pieces.single().typeParams.isEmpty() -> r.className(imports) + r is Node.TypeRef.Simple -> r.className(imports).parameterizedBy(*r.pieces.single().typeParams.map { recursive(it?.ref) }.toTypedArray()) + r is Node.TypeRef.Nullable -> recursive(r.type) + else -> throw IllegalStateException("unknown node: $r") + } + return if (type is ClassName && type.simpleName == "T") TypeVariableName("T") + else type + } + + return recursive(this.ref) +} + +fun Node.Type.returnType(imports: List): TypeName = + (typeName(imports) as ParameterizedTypeName).typeArguments.single() + +fun Node.TypeParam.typeName(imports: List): TypeVariableName = + TypeVariableName(name, ClassName.bestGuess((type!! as Node.TypeRef.Simple).fullName(imports))) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt new file mode 100644 index 00000000..6ae06e07 --- /dev/null +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt @@ -0,0 +1,43 @@ +package ch.decent.sdk.poet + +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy +import com.squareup.kotlinpoet.asClassName +import kastree.ast.Node +import kastree.ast.psi.Parser +import java.io.File +import java.util.concurrent.Future + +val out = File("../library/gen/main/java") +val srcApi = "../library/src/main/java/ch/decent/sdk/api/rx" +val packageName = "ch.decent.sdk" +val packageNameApi = "$packageName.api" +val apiNameRef = "api" +val clientRef = ClassName.bestGuess("$packageName.DCoreClient") +val apiRef = ClassName.bestGuess("$packageNameApi.rx.DCoreApi") + +val apiClasses = File(srcApi).listFiles()!!.map { Parser.parseFile(it.readText()) } + .filterNot { it.structured().hasKeyword(Node.Modifier.Keyword.ABSTRACT) } + .filterNot { it.structured().name == "CallbackApi" || it.structured().name == apiRef.simpleName } + +val apis = listOf( + ApiDescriptor("blocking", "createApiBlocking", "blockingGet()"), + ApiDescriptor("futures", "createApiFutures", "toFuture()", + { Future::class.asClassName().parameterizedBy(it) }), + ApiDescriptor("callback", "createApi", "subscribeWith(callback)", + { ClassName.bestGuess("$packageNameApi.Callback").parameterizedBy(it) }, + { it.addParameter("callback", it.build().returnType!!) }) +) + +fun main() { + File("").absolutePath.print() +// val path = System.out + val path = out + apis.forEach { + Builders.apiFile(it).writeTo(path) + Builders.apiServiceFiles(it).forEach { it.writeTo(path) } + } + Factory.file.writeTo(path) +} + +fun Any?.print() = println(this.toString()) diff --git a/buildSrc/src/main/java/Dependencies.kt b/buildSrc/src/main/java/Dependencies.kt index a0faa876..e5e883f9 100644 --- a/buildSrc/src/main/java/Dependencies.kt +++ b/buildSrc/src/main/java/Dependencies.kt @@ -1,5 +1,6 @@ object Modules { val sdk = "library" + val apiGen = "apiGen" } object Repos { diff --git a/library/build.gradle.kts b/library/build.gradle.kts index 360e677c..086f32a6 100644 --- a/library/build.gradle.kts +++ b/library/build.gradle.kts @@ -15,9 +15,6 @@ dependencies { implementation(Libs.kotlin) implementation(Libs.kotlinReflect) - implementation(Libs.kpoet) - implementation("com.github.cretz.kastree:kastree-ast-psi:0.4.0") - api(Libs.rxKotlin) api(Libs.rxJava) @@ -45,22 +42,16 @@ dependencies { } sourceSets.main { withConvention(KotlinSourceSet::class) { - kotlin.srcDirs("src/main/java", "src-gen/main/java") + kotlin.srcDirs("src/main/java", "gen/main/java") } } -tasks.create("cleanGen") { - delete("src-gen") -} - -tasks.create("generate") { - classpath = sourceSets["main"].runtimeClasspath - main = "ch.decent.sdk.poet.BlockingKt" - dependsOn("cleanGen") +tasks { + getByName("clean") { + delete.add("gen") + } } -tasks.get("compileKotlin").dependsOn("cleanGen") - detekt { toolVersion = Versions.detekt input = files("src/main/java") diff --git a/library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt b/library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt deleted file mode 100644 index fbe014ab..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/DCoreSdk.kt +++ /dev/null @@ -1,15 +0,0 @@ -package ch.decent.sdk - -import kotlin.String -import okhttp3.OkHttpClient -import org.slf4j.Logger - -object DCoreSdk { - fun createApiBlocking( - client: OkHttpClient, - websocketUrl: String? = null, - httpUrl: String? = null, - logger: Logger? = null - ) = ch.decent.sdk.api.blocking.DCoreApi(DCoreApi(DCoreClient(client, websocketUrl, httpUrl, - logger))) -} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt deleted file mode 100644 index 4f529f84..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/AccountApi.kt +++ /dev/null @@ -1,99 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Address -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.crypto.ECKeyPair -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.AccountOptions -import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.Authority -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.SearchAccountHistoryOrder -import ch.decent.sdk.model.SearchAccountsOrder -import ch.decent.sdk.model.TransactionDetailObjectId -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K -import kotlin.Boolean -import kotlin.Int -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List - -class AccountApi internal constructor( - private val api: ch.decent.sdk.api.AccountApi -) { - fun exist(nameOrId: String) = api.exist(nameOrId).blockingGet() - fun get(id: AccountObjectId) = api.get(id).blockingGet() - fun getByName(name: String) = api.getByName(name).blockingGet() - fun get(nameOrId: String) = api.get(nameOrId).blockingGet() - fun countAll() = api.countAll().blockingGet() - fun findAllReferencesByKeys(keys: List
) = api.findAllReferencesByKeys(keys).blockingGet() - fun findAllReferencesByAccount(accountId: AccountObjectId) = - api.findAllReferencesByAccount(accountId).blockingGet() - fun getAll(accountIds: List) = api.getAll(accountIds).blockingGet() - fun getFullAccounts(namesOrIds: List, subscribe: Boolean = false) = - api.getFullAccounts(namesOrIds, subscribe).blockingGet() - fun getAllByNames(names: List) = api.getAllByNames(names).blockingGet() - fun listAllRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX_1K) = - api.listAllRelative(lowerBound, limit).blockingGet() - fun findAll( - searchTerm: String, - order: SearchAccountsOrder = SearchAccountsOrder.NAME_DESC, - id: AccountObjectId? = null, - limit: Int = REQ_LIMIT_MAX_1K - ) = api.findAll(searchTerm, order, id, limit).blockingGet() - fun searchAccountHistory( - accountId: AccountObjectId, - from: TransactionDetailObjectId? = null, - order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, - limit: Int = REQ_LIMIT_MAX - ) = api.searchAccountHistory(accountId, from, order, limit).blockingGet() - fun createCredentials(account: String, privateKey: String) = api.createCredentials(account, - privateKey).blockingGet() - fun createMemo( - message: String, - recipient: String? = null, - keyPair: ECKeyPair? = null - ) = api.createMemo(message, recipient, keyPair).blockingGet() - fun createTransfer( - credentials: Credentials, - nameOrId: String, - amount: AssetAmount, - memo: String? = null, - encrypted: Boolean = true, - fee: Fee = Fee() - ) = api.createTransfer(credentials, nameOrId, amount, memo, encrypted, fee).blockingGet() - fun transfer( - credentials: Credentials, - nameOrId: String, - amount: AssetAmount, - memo: String? = null, - encrypted: Boolean = true, - fee: Fee = Fee() - ) = api.transfer(credentials, nameOrId, amount, memo, encrypted, fee).blockingGet() - fun createAccountOperation( - registrar: AccountObjectId, - name: String, - address: Address, - fee: Fee = Fee() - ) = api.createAccountOperation(registrar, name, address, fee).blockingGet() - fun create( - registrar: Credentials, - name: String, - address: Address, - fee: Fee = Fee() - ) = api.create(registrar, name, address, fee).blockingGet() - fun createUpdateOperation(nameOrId: String, fee: Fee = Fee()) = - api.createUpdateOperation(nameOrId, fee).blockingGet() - fun update( - credentials: Credentials, - options: AccountOptions? = null, - active: Authority? = null, - owner: Authority? = null, - fee: Fee = Fee() - ) = api.update(credentials, options, active, owner, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt deleted file mode 100644 index a6dad61c..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/AssetApi.kt +++ /dev/null @@ -1,153 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.AssetDataObjectId -import ch.decent.sdk.model.AssetObjectId -import ch.decent.sdk.model.AssetOptions -import ch.decent.sdk.model.ExchangeRateValues -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.MonitoredAssetOptions -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import java.math.RoundingMode -import kotlin.Boolean -import kotlin.Byte -import kotlin.Int -import kotlin.Long -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List - -class AssetApi internal constructor( - private val api: ch.decent.sdk.api.AssetApi -) { - fun get(assetId: AssetObjectId) = api.get(assetId).blockingGet() - fun getAll(assetIds: List) = api.getAll(assetIds).blockingGet() - fun getRealSupply() = api.getRealSupply().blockingGet() - fun getAssetsData(assetId: List) = api.getAssetsData(assetId).blockingGet() - fun getAssetData(assetId: AssetDataObjectId) = api.getAssetData(assetId).blockingGet() - fun listAllRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX) = - api.listAllRelative(lowerBound, limit).blockingGet() - fun listAll(includeMonitored: Boolean = false) = api.listAll(includeMonitored).blockingGet() - fun getByName(assetSymbol: String) = api.getByName(assetSymbol).blockingGet() - fun getAllByName(assetSymbols: List) = api.getAllByName(assetSymbols).blockingGet() - fun convertFromDCT( - assetId: AssetObjectId, - amount: Long, - roundingMode: RoundingMode = RoundingMode.CEILING - ) = api.convertFromDCT(assetId, amount, roundingMode).blockingGet() - fun convertToDCT( - assetId: AssetObjectId, - amount: Long, - roundingMode: RoundingMode = RoundingMode.CEILING - ) = api.convertToDCT(assetId, amount, roundingMode).blockingGet() - fun createAssetCreateOperation( - issuer: AccountObjectId, - symbol: String, - precision: Byte, - description: String, - options: AssetOptions, - monitoredOptions: MonitoredAssetOptions? = null, - fee: Fee = Fee() - ) = api.createAssetCreateOperation(issuer, symbol, precision, description, options, - monitoredOptions, fee).blockingGet() - fun create( - credentials: Credentials, - symbol: String, - precision: Byte, - description: String, - options: AssetOptions = AssetOptions(), - fee: Fee = Fee() - ) = api.create(credentials, symbol, precision, description, options, fee).blockingGet() - fun createMonitoredAsset( - credentials: Credentials, - symbol: String, - precision: Byte, - description: String, - options: MonitoredAssetOptions = MonitoredAssetOptions(), - fee: Fee = Fee() - ) = api.createMonitoredAsset(credentials, symbol, precision, description, options, - fee).blockingGet() - fun createAssetUpdateOperation( - assetIdOrSymbol: String, - newIssuer: AccountObjectId? = null, - fee: Fee = Fee() - ) = api.createAssetUpdateOperation(assetIdOrSymbol, newIssuer, fee).blockingGet() - fun update( - credentials: Credentials, - assetIdOrSymbol: String, - exchangeRate: ExchangeRateValues? = null, - description: String? = null, - exchangeable: Boolean? = null, - maxSupply: Long? = null, - newIssuer: AccountObjectId? = null, - fee: Fee = Fee() - ) = api.update(credentials, assetIdOrSymbol, exchangeRate, description, exchangeable, maxSupply, - newIssuer, fee).blockingGet() - fun createAssetUpdateAdvancedOperation(assetIdOrSymbol: String, fee: Fee = Fee()) = - api.createAssetUpdateAdvancedOperation(assetIdOrSymbol, fee).blockingGet() - fun updateAdvanced( - credentials: Credentials, - assetIdOrSymbol: String, - precision: Byte? = null, - fixedMaxSupply: Boolean? = null, - fee: Fee = Fee() - ) = api.updateAdvanced(credentials, assetIdOrSymbol, precision, fixedMaxSupply, fee).blockingGet() - fun createAssetIssueOperation( - assetIdOrSymbol: String, - amount: Long, - to: AccountObjectId? = null, - memo: Memo? = null, - fee: Fee = Fee() - ) = api.createAssetIssueOperation(assetIdOrSymbol, amount, to, memo, fee).blockingGet() - fun issue( - credentials: Credentials, - assetIdOrSymbol: String, - amount: Long, - to: AccountObjectId? = null, - memo: Memo? = null, - fee: Fee = Fee() - ) = api.issue(credentials, assetIdOrSymbol, amount, to, memo, fee).blockingGet() - fun createFundPoolsOperation( - assetIdOrSymbol: String, - uia: Long, - dct: Long, - fee: Fee = Fee() - ) = api.createFundPoolsOperation(assetIdOrSymbol, uia, dct, fee).blockingGet() - fun fund( - credentials: Credentials, - assetIdOrSymbol: String, - uia: Long, - dct: Long, - fee: Fee = Fee() - ) = api.fund(credentials, assetIdOrSymbol, uia, dct, fee).blockingGet() - fun createClaimFeesOperation( - assetIdOrSymbol: String, - uia: Long, - dct: Long, - fee: Fee = Fee() - ) = api.createClaimFeesOperation(assetIdOrSymbol, uia, dct, fee).blockingGet() - fun claim( - credentials: Credentials, - assetIdOrSymbol: String, - uia: Long, - dct: Long, - fee: Fee = Fee() - ) = api.claim(credentials, assetIdOrSymbol, uia, dct, fee).blockingGet() - fun createReserveOperation( - assetIdOrSymbol: String, - amount: Long, - fee: Fee = Fee() - ) = api.createReserveOperation(assetIdOrSymbol, amount, fee).blockingGet() - fun reserve( - credentials: Credentials, - assetIdOrSymbol: String, - amount: Long, - fee: Fee = Fee() - ) = api.reserve(credentials, assetIdOrSymbol, amount, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt deleted file mode 100644 index 238ade30..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BalanceApi.kt +++ /dev/null @@ -1,34 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.DCoreConstants -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.AssetObjectId -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List -import kotlin.collections.emptyList - -class BalanceApi internal constructor( - private val api: ch.decent.sdk.api.BalanceApi -) { - fun get(accountId: AccountObjectId, asset: AssetObjectId) = api.get(accountId, - asset).blockingGet() - fun getAll(accountId: AccountObjectId, assets: List = emptyList()) = - api.getAll(accountId, assets).blockingGet() - fun get(name: String, asset: AssetObjectId) = api.get(name, asset).blockingGet() - fun getAll(name: String, assets: List = emptyList()) = api.getAll(name, - assets).blockingGet() - fun getWithAsset(accountId: AccountObjectId, assetSymbol: String = DCoreConstants.DCT_SYMBOL) = - api.getWithAsset(accountId, assetSymbol).blockingGet() - fun getAllWithAsset(accountId: AccountObjectId, assetSymbols: List) = - api.getAllWithAsset(accountId, assetSymbols).blockingGet() - fun getWithAsset(name: String, assetSymbol: String = DCoreConstants.DCT_SYMBOL) = - api.getWithAsset(name, assetSymbol).blockingGet() - fun getAllWithAsset(name: String, assetSymbols: List) = api.getAllWithAsset(name, - assetSymbols).blockingGet() - fun getAllVesting(accountId: AccountObjectId) = api.getAllVesting(accountId).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt deleted file mode 100644 index 1839a32c..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BlockApi.kt +++ /dev/null @@ -1,16 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import kotlin.Long -import kotlin.Suppress - -class BlockApi internal constructor( - private val api: ch.decent.sdk.api.BlockApi -) { - fun get(blockNum: Long) = api.get(blockNum).blockingGet() - fun getHeader(blockNum: Long) = api.getHeader(blockNum).blockingGet() - fun getHeadTime() = api.getHeadTime().blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt deleted file mode 100644 index 2b0f0595..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/BroadcastApi.kt +++ /dev/null @@ -1,63 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.ECKeyPair -import ch.decent.sdk.model.Transaction -import ch.decent.sdk.model.operation.BaseOperation -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List -import org.threeten.bp.Duration - -class BroadcastApi internal constructor( - private val api: ch.decent.sdk.api.BroadcastApi -) { - fun broadcast(transaction: Transaction) = api.broadcast(transaction).blockingGet() - fun broadcast( - privateKey: ECKeyPair, - operations: List, - expiration: Duration = api.transactionExpiration - ) = api.broadcast(privateKey, operations, expiration).blockingGet() - fun broadcast( - privateKey: ECKeyPair, - operation: BaseOperation, - expiration: Duration = api.transactionExpiration - ) = api.broadcast(privateKey, operation, expiration).blockingGet() - fun broadcast( - privateKey: String, - operations: List, - expiration: Duration = api.transactionExpiration - ) = api.broadcast(privateKey, operations, expiration).blockingGet() - fun broadcast( - privateKey: String, - operation: BaseOperation, - expiration: Duration = api.transactionExpiration - ) = api.broadcast(privateKey, operation, expiration).blockingGet() - fun broadcastWithCallback(transaction: Transaction) = - api.broadcastWithCallback(transaction).blockingGet() - fun broadcastWithCallback( - privateKey: ECKeyPair, - operations: List, - expiration: Duration = api.transactionExpiration - ) = api.broadcastWithCallback(privateKey, operations, expiration).blockingGet() - fun broadcastWithCallback( - privateKey: ECKeyPair, - operation: BaseOperation, - expiration: Duration = api.transactionExpiration - ) = api.broadcastWithCallback(privateKey, operation, expiration).blockingGet() - fun broadcastWithCallback( - privateKey: String, - operations: List, - expiration: Duration = api.transactionExpiration - ) = api.broadcastWithCallback(privateKey, operations, expiration).blockingGet() - fun broadcastWithCallback( - privateKey: String, - operation: BaseOperation, - expiration: Duration = api.transactionExpiration - ) = api.broadcastWithCallback(privateKey, operation, expiration).blockingGet() - fun broadcastSynchronous(transaction: Transaction) = - api.broadcastSynchronous(transaction).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt deleted file mode 100644 index 28034a6b..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/ContentApi.kt +++ /dev/null @@ -1,149 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.CoAuthors -import ch.decent.sdk.model.ContentObjectId -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.PubKey -import ch.decent.sdk.model.PurchaseObjectId -import ch.decent.sdk.model.RegionalPrice -import ch.decent.sdk.model.Regions -import ch.decent.sdk.model.SearchContentOrder -import ch.decent.sdk.model.Synopsis -import ch.decent.sdk.model.contentType -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import org.threeten.bp.LocalDateTime - -class ContentApi internal constructor( - private val api: ch.decent.sdk.api.ContentApi -) { - fun generateKeys(seeders: List) = api.generateKeys(seeders).blockingGet() - fun get(contentId: ContentObjectId) = api.get(contentId).blockingGet() - fun getAll(contentId: List) = api.getAll(contentId).blockingGet() - fun get(uri: String) = api.get(uri).blockingGet() - fun listAllPublishersRelative(lowerBound: String, limit: Int = REQ_LIMIT_MAX) = - api.listAllPublishersRelative(lowerBound, limit).blockingGet() - - fun restoreEncryptionKey(elGamalPrivate: PubKey, purchaseId: PurchaseObjectId) = - api.restoreEncryptionKey(elGamalPrivate, purchaseId).blockingGet() - - fun findAll( - term: String, - order: SearchContentOrder = SearchContentOrder.CREATED_DESC, - user: String = "", - regionCode: String = Regions.ALL.code, - type: String = contentType(), - startId: ContentObjectId? = null, - limit: Int = REQ_LIMIT_MAX - ) = api.findAll(term, order, user, regionCode, type, startId, limit).blockingGet() - - fun createPurchaseOperation( - credentials: Credentials, - contentId: ContentObjectId, - fee: Fee = Fee() - ) = api.createPurchaseOperation(credentials, contentId, fee).blockingGet() - - fun createPurchaseOperation( - credentials: Credentials, - uri: String, - fee: Fee = Fee() - ) = api.createPurchaseOperation(credentials, uri, fee).blockingGet() - - fun purchase( - credentials: Credentials, - contentId: ContentObjectId, - fee: Fee = Fee() - ) = api.purchase(credentials, contentId, fee).blockingGet() - - fun purchase( - credentials: Credentials, - uri: String, - fee: Fee = Fee() - ) = api.purchase(credentials, uri, fee).blockingGet() - - fun createTransfer( - credentials: Credentials, - id: ContentObjectId, - amount: AssetAmount, - memo: String? = null, - fee: Fee = Fee() - ) = api.createTransfer(credentials, id, amount, memo, fee).blockingGet() - - fun transfer( - credentials: Credentials, - id: ContentObjectId, - amount: AssetAmount, - memo: String? = null, - fee: Fee = Fee() - ) = api.transfer(credentials, id, amount, memo, fee).blockingGet() - - fun createRemoveContentOperation(content: ContentObjectId, fee: Fee = Fee()) = - api.createRemoveContentOperation(content, fee).blockingGet() - - fun createRemoveContentOperation(content: String, fee: Fee = Fee()) = - api.createRemoveContentOperation(content, fee).blockingGet() - - fun remove( - credentials: Credentials, - content: ContentObjectId, - fee: Fee = Fee() - ) = api.remove(credentials, content, fee).blockingGet() - - fun remove( - credentials: Credentials, - content: String, - fee: Fee = Fee() - ) = api.remove(credentials, content, fee).blockingGet() - - fun createAddContentOperation( - author: AccountObjectId, - coAuthors: CoAuthors, - uri: String, - price: List, - expiration: LocalDateTime, - synopsis: Synopsis, - fee: Fee = Fee() - ) = api.createAddContentOperation(author, coAuthors, uri, price, expiration, synopsis, - fee).blockingGet() - - fun add( - credentials: Credentials, - coAuthors: CoAuthors, - uri: String, - price: List, - expiration: LocalDateTime, - synopsis: Synopsis, - fee: Fee = Fee() - ) = api.add(credentials, coAuthors, uri, price, expiration, synopsis, fee).blockingGet() - - fun createUpdateContentOperation(content: ContentObjectId, fee: Fee = Fee()) = - api.createUpdateContentOperation(content, fee).blockingGet() - - fun createUpdateContentOperation(content: String, fee: Fee = Fee()) = - api.createUpdateContentOperation(content, fee).blockingGet() - - fun update( - credentials: Credentials, - content: ContentObjectId, - synopsis: Synopsis? = null, - price: List? = null, - coAuthors: CoAuthors? = null, - fee: Fee = Fee() - ) = api.update(credentials, content, synopsis, price, coAuthors, fee).blockingGet() - - fun update( - credentials: Credentials, - content: String, - synopsis: Synopsis? = null, - price: List? = null, - coAuthors: CoAuthors? = null, - fee: Fee = Fee() - ) = api.update(credentials, content, synopsis, price, coAuthors, fee).blockingGet() -} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt deleted file mode 100644 index dc16b7a7..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/DCoreApi.kt +++ /dev/null @@ -1,37 +0,0 @@ -package ch.decent.sdk.api.blocking - -class DCoreApi( - api: ch.decent.sdk.DCoreApi -) { - val broadcastApi: BroadcastApi = BroadcastApi(api.broadcastApi) - - val blockApi: BlockApi = BlockApi(api.blockApi) - - val miningApi: MiningApi = MiningApi(api.miningApi) - - val purchaseApi: PurchaseApi = PurchaseApi(api.purchaseApi) - - val contentApi: ContentApi = ContentApi(api.contentApi) - - val transactionApi: TransactionApi = TransactionApi(api.transactionApi) - - val accountApi: AccountApi = AccountApi(api.accountApi) - - val seederApi: SeederApi = SeederApi(api.seederApi) - - val balanceApi: BalanceApi = BalanceApi(api.balanceApi) - - val nftApi: NftApi = NftApi(api.nftApi) - - val generalApi: GeneralApi = GeneralApi(api.generalApi) - - val historyApi: HistoryApi = HistoryApi(api.historyApi) - - val assetApi: AssetApi = AssetApi(api.assetApi) - - val subscriptionApi: SubscriptionApi = SubscriptionApi(api.subscriptionApi) - - val messagingApi: MessagingApi = MessagingApi(api.messagingApi) - - val validationApi: ValidationApi = ValidationApi(api.validationApi) -} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt deleted file mode 100644 index a0b50e87..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/GeneralApi.kt +++ /dev/null @@ -1,19 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import kotlin.Suppress -import org.threeten.bp.LocalDateTime - -class GeneralApi internal constructor( - private val api: ch.decent.sdk.api.GeneralApi -) { - fun getChainProperties() = api.getChainProperties().blockingGet() - fun getGlobalProperties() = api.getGlobalProperties().blockingGet() - fun getConfig() = api.getConfig().blockingGet() - fun getChainId() = api.getChainId().blockingGet() - fun getDynamicGlobalProperties() = api.getDynamicGlobalProperties().blockingGet() - fun getTimeToMaintenance(time: LocalDateTime) = api.getTimeToMaintenance(time).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt deleted file mode 100644 index 04775697..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/HistoryApi.kt +++ /dev/null @@ -1,43 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.AssetObjectId -import ch.decent.sdk.model.OperationHistoryObjectId -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import kotlin.Int -import kotlin.Long -import kotlin.Suppress -import kotlin.collections.List -import kotlin.collections.emptyList - -class HistoryApi internal constructor( - private val api: ch.decent.sdk.api.HistoryApi -) { - fun getOperation(accountId: AccountObjectId, operationId: OperationHistoryObjectId) = - api.getOperation(accountId, operationId).blockingGet() - fun listOperations( - accountId: AccountObjectId, - startId: OperationHistoryObjectId? = null, - stopId: OperationHistoryObjectId? = null, - limit: Int = REQ_LIMIT_MAX - ) = api.listOperations(accountId, startId, stopId, limit).blockingGet() - fun listOperationsRelative( - accountId: AccountObjectId, - start: Int = 0, - limit: Int = REQ_LIMIT_MAX - ) = api.listOperationsRelative(accountId, start, limit).blockingGet() - fun findAllOperations( - accountId: AccountObjectId, - assets: List = emptyList(), - recipientAccount: AccountObjectId? = null, - fromBlock: Long = 0, - toBlock: Long = 0, - startOffset: Long = 0, - limit: Int = REQ_LIMIT_MAX - ) = api.findAllOperations(accountId, assets, recipientAccount, fromBlock, toBlock, startOffset, - limit).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt deleted file mode 100644 index 7719cc51..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/MessagingApi.kt +++ /dev/null @@ -1,59 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.MessageRequest -import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K -import kotlin.Int -import kotlin.Suppress -import kotlin.collections.List - -class MessagingApi internal constructor( - private val api: ch.decent.sdk.api.MessagingApi -) { - fun getAllOperations( - sender: AccountObjectId? = null, - receiver: AccountObjectId? = null, - maxCount: Int = REQ_LIMIT_MAX_1K - ) = api.getAllOperations(sender, receiver, maxCount).blockingGet() - fun getAll( - sender: AccountObjectId? = null, - receiver: AccountObjectId? = null, - maxCount: Int = REQ_LIMIT_MAX_1K - ) = api.getAll(sender, receiver, maxCount).blockingGet() - fun getAllDecrypted( - credentials: Credentials, - sender: AccountObjectId? = null, - receiver: AccountObjectId? = null, - maxCount: Int = REQ_LIMIT_MAX_1K - ) = api.getAllDecrypted(credentials, sender, receiver, maxCount).blockingGet() - fun getAllDecryptedForSender(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K) = - api.getAllDecryptedForSender(credentials, maxCount).blockingGet() - fun getAllDecryptedForReceiver(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K) = - api.getAllDecryptedForReceiver(credentials, maxCount).blockingGet() - fun createMessageOperation( - credentials: Credentials, - messages: List, - fee: Fee = Fee() - ) = api.createMessageOperation(credentials, messages, fee).blockingGet() - fun createMessageOperationUnencrypted( - credentials: Credentials, - messages: List, - fee: Fee = Fee() - ) = api.createMessageOperationUnencrypted(credentials, messages, fee).blockingGet() - fun send( - credentials: Credentials, - messages: List, - fee: Fee = Fee() - ) = api.send(credentials, messages, fee).blockingGet() - fun sendUnencrypted( - credentials: Credentials, - messages: List, - fee: Fee = Fee() - ) = api.sendUnencrypted(credentials, messages, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt deleted file mode 100644 index 41b1abf9..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/MiningApi.kt +++ /dev/null @@ -1,55 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.MinerObjectId -import ch.decent.sdk.model.SearchMinerVotingOrder -import ch.decent.sdk.model.VoteId -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K -import kotlin.Boolean -import kotlin.Int -import kotlin.Long -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List - -class MiningApi internal constructor( - private val api: ch.decent.sdk.api.MiningApi -) { - fun getActualVotes() = api.getActualVotes().blockingGet() - fun getAssetPerBlock(blockNum: Long) = api.getAssetPerBlock(blockNum).blockingGet() - fun getFeedsByMiner(account: AccountObjectId, count: Int = REQ_LIMIT_MAX) = - api.getFeedsByMiner(account, count).blockingGet() - fun getMinerByAccount(account: AccountObjectId) = api.getMinerByAccount(account).blockingGet() - fun getMinerCount() = api.getMinerCount().blockingGet() - fun getMiners(minerIds: List) = api.getMiners(minerIds).blockingGet() - fun getMiners() = api.getMiners().blockingGet() - fun getNewAssetPerBlock() = api.getNewAssetPerBlock().blockingGet() - fun listMinersRelative(lowerBound: String = "", limit: Int = REQ_LIMIT_MAX_1K) = - api.listMinersRelative(lowerBound, limit).blockingGet() - fun findVotedMiners(voteIds: List) = api.findVotedMiners(voteIds).blockingGet() - fun findAllVotingInfo( - searchTerm: String, - order: SearchMinerVotingOrder = SearchMinerVotingOrder.NAME_DESC, - id: MinerObjectId? = null, - accountName: String? = null, - onlyMyVotes: Boolean = false, - limit: Int = REQ_LIMIT_MAX_1K - ) = api.findAllVotingInfo(searchTerm, order, id, accountName, onlyMyVotes, limit).blockingGet() - fun createVoteOperation( - accountId: AccountObjectId, - minerIds: List, - fee: Fee = Fee() - ) = api.createVoteOperation(accountId, minerIds, fee).blockingGet() - fun vote( - credentials: Credentials, - minerIds: List, - fee: Fee = Fee() - ) = api.vote(credentials, minerIds, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt deleted file mode 100644 index df535da3..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/NftApi.kt +++ /dev/null @@ -1,172 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.NftDataObjectId -import ch.decent.sdk.model.NftModel -import ch.decent.sdk.model.NftObjectId -import ch.decent.sdk.model.NftOptions -import ch.decent.sdk.net.serialization.Variant -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import java.lang.Class -import kotlin.Boolean -import kotlin.Int -import kotlin.Long -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List -import kotlin.collections.Map -import kotlin.collections.emptyList -import kotlin.reflect.KClass - -class NftApi internal constructor( - private val api: ch.decent.sdk.api.NftApi -) { - fun get(idOrSymbol: String) = api.get(idOrSymbol).blockingGet() - fun getAll(ids: List) = api.getAll(ids).blockingGet() - fun get(id: NftObjectId) = api.get(id).blockingGet() - fun getAllBySymbol(symbols: List) = api.getAllBySymbol(symbols).blockingGet() - fun getBySymbol(symbol: String) = api.getBySymbol(symbol).blockingGet() - fun getAllData(ids: List, clazz: KClass) = api.getAllData(ids, - clazz).blockingGet() - fun getAllData(ids: List, clazz: Class) = api.getAllData(ids, - clazz).blockingGet() - fun getAllData(ids: List) = api.getAllData(ids).blockingGet() - fun getAllDataRaw(ids: List) = api.getAllDataRaw(ids).blockingGet() - fun getData(id: NftDataObjectId, clazz: KClass) = api.getData(id, - clazz).blockingGet() - fun getData(id: NftDataObjectId, clazz: Class) = api.getData(id, - clazz).blockingGet() - fun getData(id: NftDataObjectId) = api.getData(id).blockingGet() - fun getDataRaw(id: NftDataObjectId) = api.getDataRaw(id).blockingGet() - fun countAll() = api.countAll().blockingGet() - fun countAllData() = api.countAllData().blockingGet() - fun getNftBalancesRaw(account: AccountObjectId, nftIds: List = emptyList()) = - api.getNftBalancesRaw(account, nftIds).blockingGet() - fun getNftBalances(account: AccountObjectId, nftIds: List = emptyList()) = - api.getNftBalances(account, nftIds).blockingGet() - fun getNftBalances( - account: AccountObjectId, - nftId: NftObjectId, - clazz: KClass - ) = api.getNftBalances(account, nftId, clazz).blockingGet() - fun getNftBalances( - account: AccountObjectId, - nftId: NftObjectId, - clazz: Class - ) = api.getNftBalances(account, nftId, clazz).blockingGet() - fun listAllRelative(lowerBound: String = "", limit: Int = REQ_LIMIT_MAX) = - api.listAllRelative(lowerBound, limit).blockingGet() - fun listDataByNft(nftId: NftObjectId, clazz: KClass) = api.listDataByNft(nftId, - clazz).blockingGet() - fun listDataByNft(nftId: NftObjectId, clazz: Class) = api.listDataByNft(nftId, - clazz).blockingGet() - fun listDataByNft(nftId: NftObjectId) = api.listDataByNft(nftId).blockingGet() - fun listDataByNftRaw(nftId: NftObjectId) = api.listDataByNftRaw(nftId).blockingGet() - fun searchNftHistory(nftDataId: NftDataObjectId) = api.searchNftHistory(nftDataId).blockingGet() - fun createNftCreateOperation( - symbol: String, - options: NftOptions, - clazz: KClass, - transferable: Boolean, - fee: Fee = Fee() - ) = api.createNftCreateOperation(symbol, options, clazz, transferable, fee).blockingGet() - fun createNftCreateOperation( - symbol: String, - options: NftOptions, - clazz: Class, - transferable: Boolean, - fee: Fee = Fee() - ) = api.createNftCreateOperation(symbol, options, clazz, transferable, fee).blockingGet() - fun create( - credentials: Credentials, - symbol: String, - maxSupply: Long, - fixedMaxSupply: Boolean, - description: String, - clazz: KClass, - transferable: Boolean, - fee: Fee = Fee() - ) = api.create(credentials, symbol, maxSupply, fixedMaxSupply, description, clazz, transferable, - fee).blockingGet() - fun create( - credentials: Credentials, - symbol: String, - maxSupply: Long, - fixedMaxSupply: Boolean, - description: String, - clazz: Class, - transferable: Boolean, - fee: Fee = Fee() - ) = api.create(credentials, symbol, maxSupply, fixedMaxSupply, description, clazz, transferable, - fee).blockingGet() - fun createUpdateOperation(idOrSymbol: String, fee: Fee = Fee()) = - api.createUpdateOperation(idOrSymbol, fee).blockingGet() - fun update( - credentials: Credentials, - idOrSymbol: String, - maxSupply: Long? = null, - fixedMaxSupply: Boolean? = null, - description: String? = null, - fee: Fee = Fee() - ) = api.update(credentials, idOrSymbol, maxSupply, fixedMaxSupply, description, fee).blockingGet() - fun createIssueOperation( - issuer: AccountObjectId, - idOrSymbol: String, - to: AccountObjectId, - data: T? = null, - memo: Memo? = null, - fee: Fee = Fee() - ) = api.createIssueOperation(issuer, idOrSymbol, to, data, memo, fee).blockingGet() - fun issue( - credentials: Credentials, - idOrSymbol: String, - to: AccountObjectId, - data: T? = null, - memo: Memo? = null, - fee: Fee = Fee() - ) = api.issue(credentials, idOrSymbol, to, data, memo, fee).blockingGet() - fun createTransferOperation( - from: AccountObjectId, - to: AccountObjectId, - id: NftDataObjectId, - memo: Memo? = null, - fee: Fee = Fee() - ) = api.createTransferOperation(from, to, id, memo, fee).blockingGet() - fun transfer( - credentials: Credentials, - to: AccountObjectId, - id: NftDataObjectId, - memo: Memo? = null, - fee: Fee = Fee() - ) = api.transfer(credentials, to, id, memo, fee).blockingGet() - fun createUpdateDataOperation( - modifier: AccountObjectId, - id: NftDataObjectId, - fee: Fee = Fee() - ) = api.createUpdateDataOperation(modifier, id, fee).blockingGet() - fun createUpdateDataOperation( - modifier: AccountObjectId, - id: NftDataObjectId, - newData: T, - fee: Fee = Fee() - ) = api.createUpdateDataOperation(modifier, id, newData, fee).blockingGet() - fun updateData( - credentials: Credentials, - id: NftDataObjectId, - values: Map, - fee: Fee = Fee() - ) = api.updateData(credentials, id, values, fee).blockingGet() - fun updateData( - credentials: Credentials, - id: NftDataObjectId, - newData: T, - fee: Fee = Fee() - ) = api.updateData(credentials, id, newData, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt deleted file mode 100644 index 697811b9..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/PurchaseApi.kt +++ /dev/null @@ -1,54 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.crypto.Credentials -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.PurchaseObjectId -import ch.decent.sdk.model.SearchPurchasesOrder -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import kotlin.Byte -import kotlin.Int -import kotlin.String -import kotlin.Suppress - -class PurchaseApi internal constructor( - private val api: ch.decent.sdk.api.PurchaseApi -) { - fun getAllHistory(accountId: AccountObjectId) = api.getAllHistory(accountId).blockingGet() - fun getAllOpen() = api.getAllOpen().blockingGet() - fun getAllOpenByUri(uri: String) = api.getAllOpenByUri(uri).blockingGet() - fun getAllOpenByAccount(accountId: AccountObjectId) = - api.getAllOpenByAccount(accountId).blockingGet() - fun get(consumer: AccountObjectId, uri: String) = api.get(consumer, uri).blockingGet() - fun findAll( - consumer: AccountObjectId, - term: String = "", - from: PurchaseObjectId? = null, - order: SearchPurchasesOrder = SearchPurchasesOrder.PURCHASED_DESC, - limit: Int = REQ_LIMIT_MAX - ) = api.findAll(consumer, term, from, order, limit).blockingGet() - fun findAllForFeedback( - uri: String, - user: String? = null, - count: Int = REQ_LIMIT_MAX, - startId: PurchaseObjectId? = null - ) = api.findAllForFeedback(uri, user, count, startId).blockingGet() - fun createRateAndCommentOperation( - uri: String, - consumer: AccountObjectId, - rating: Byte, - comment: String, - fee: Fee = Fee() - ) = api.createRateAndCommentOperation(uri, consumer, rating, comment, fee).blockingGet() - fun rateAndComment( - credentials: Credentials, - uri: String, - rating: Byte, - comment: String, - fee: Fee = Fee() - ) = api.rateAndComment(credentials, uri, rating, comment, fee).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt deleted file mode 100644 index ab615b7f..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/SeederApi.kt +++ /dev/null @@ -1,22 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.Regions -import ch.decent.sdk.utils.REQ_LIMIT_MAX -import kotlin.Int -import kotlin.String -import kotlin.Suppress - -class SeederApi internal constructor( - private val api: ch.decent.sdk.api.SeederApi -) { - fun get(accountId: AccountObjectId) = api.get(accountId).blockingGet() - fun listByPrice(count: Int = REQ_LIMIT_MAX) = api.listByPrice(count).blockingGet() - fun listByUpload(count: Int = REQ_LIMIT_MAX) = api.listByUpload(count).blockingGet() - fun listByRegion(region: String = Regions.ALL.code) = api.listByRegion(region).blockingGet() - fun listByRating(count: Int = REQ_LIMIT_MAX) = api.listByRating(count).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt deleted file mode 100644 index b32e2a12..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/SubscriptionApi.kt +++ /dev/null @@ -1,24 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.SubscriptionObjectId -import kotlin.Int -import kotlin.Suppress - -class SubscriptionApi internal constructor( - private val api: ch.decent.sdk.api.SubscriptionApi -) { - fun get(id: SubscriptionObjectId) = api.get(id).blockingGet() - fun getAllActiveByConsumer(consumer: AccountObjectId, count: Int) = - api.getAllActiveByConsumer(consumer, count).blockingGet() - fun getAllActiveByAuthor(author: AccountObjectId, count: Int) = api.getAllActiveByAuthor(author, - count).blockingGet() - fun getAllByConsumer(consumer: AccountObjectId, count: Int) = api.getAllByConsumer(consumer, - count).blockingGet() - fun getAllByAuthor(author: AccountObjectId, count: Int) = api.getAllByAuthor(author, - count).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt deleted file mode 100644 index 2f247e90..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/TransactionApi.kt +++ /dev/null @@ -1,30 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.Transaction -import ch.decent.sdk.model.TransactionConfirmation -import ch.decent.sdk.model.operation.BaseOperation -import kotlin.Long -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List -import org.threeten.bp.Duration - -class TransactionApi internal constructor( - private val api: ch.decent.sdk.api.TransactionApi -) { - fun createTransaction(operations: List, expiration: Duration = - api.transactionExpiration) = api.createTransaction(operations, expiration).blockingGet() - fun createTransaction(operation: BaseOperation, expiration: Duration = api.transactionExpiration) - = api.createTransaction(operation, expiration).blockingGet() - fun getAllProposed(accountId: AccountObjectId) = api.getAllProposed(accountId).blockingGet() - fun getRecent(trxId: String) = api.getRecent(trxId).blockingGet() - fun get(trxId: String) = api.get(trxId).blockingGet() - fun get(blockNum: Long, trxInBlock: Long) = api.get(blockNum, trxInBlock).blockingGet() - fun get(confirmation: TransactionConfirmation) = api.get(confirmation).blockingGet() - fun getHexDump(transaction: Transaction) = api.getHexDump(transaction).blockingGet()} diff --git a/library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt b/library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt deleted file mode 100644 index 1602e04c..00000000 --- a/library/src-gen/main/java/ch/decent/sdk/api/blocking/ValidationApi.kt +++ /dev/null @@ -1,37 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList" -) - -package ch.decent.sdk.api.blocking - -import ch.decent.sdk.DCoreConstants -import ch.decent.sdk.crypto.Address -import ch.decent.sdk.model.AssetObjectId -import ch.decent.sdk.model.Transaction -import ch.decent.sdk.model.operation.BaseOperation -import ch.decent.sdk.model.operation.OperationType -import kotlin.String -import kotlin.Suppress -import kotlin.collections.List - -class ValidationApi internal constructor( - private val api: ch.decent.sdk.api.ValidationApi -) { - fun getRequiredSignatures(transaction: Transaction, keys: List
) = - api.getRequiredSignatures(transaction, keys).blockingGet() - fun getPotentialSignatures(transaction: Transaction) = - api.getPotentialSignatures(transaction).blockingGet() - fun verifyAuthority(transaction: Transaction) = api.verifyAuthority(transaction).blockingGet() - fun verifyAccountAuthority(nameOrId: String, keys: List
) = - api.verifyAccountAuthority(nameOrId, keys).blockingGet() - fun validateTransaction(transaction: Transaction) = - api.validateTransaction(transaction).blockingGet() - fun getFees(op: List, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID) = - api.getFees(op, assetId).blockingGet() - fun getFee(op: BaseOperation, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID) = - api.getFee(op, assetId).blockingGet() - fun getFeesForType(types: List, assetId: AssetObjectId = - DCoreConstants.DCT_ASSET_ID) = api.getFeesForType(types, assetId).blockingGet() - fun getFeeForType(type: OperationType, assetId: AssetObjectId = DCoreConstants.DCT_ASSET_ID) = - api.getFeeForType(type, assetId).blockingGet()} diff --git a/library/src/main/java/ch/decent/sdk/Apis.kt b/library/src/main/java/ch/decent/sdk/Apis.kt deleted file mode 100644 index 6c255f1a..00000000 --- a/library/src/main/java/ch/decent/sdk/Apis.kt +++ /dev/null @@ -1,119 +0,0 @@ -package ch.decent.sdk - -import ch.decent.sdk.api.AccountApi -import ch.decent.sdk.exception.ObjectNotFoundException -import ch.decent.sdk.model.Account -import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.toObjectId -import ch.decent.sdk.poet.print -import io.reactivex.disposables.Disposable -import okhttp3.OkHttpClient -import org.slf4j.Logger -import java.util.concurrent.Future - -object Apis { - - class AccountApiSync internal constructor(private val api: AccountApi) { - /** - * Get account by id. - * - * @param id account id - * - * @return an account if exist, [ObjectNotFoundException] if not found - */ - fun get(id: AccountObjectId): Account = api.get(id).blockingGet() - } - - class AccountApiFuture internal constructor(private val api: AccountApi) { - /** - * Get account by id. - * - * @param id account id - * - * @return an account if exist, [ObjectNotFoundException] if not found - */ - fun get(id: AccountObjectId): Future = api.get(id).toFuture() - } - - interface ApiCallback { - fun onSuccess(value: T) - fun onError(error: Throwable) - } - - class AccountApiAsync internal constructor(private val api: AccountApi) { - /** - * Get account by id. - * - * @param id account id - * - * @return an account if exist, [ObjectNotFoundException] if not found - */ - fun get(id: AccountObjectId, success: (Account) -> Unit, error: (Throwable) -> Unit): Disposable = - api.get(id).subscribe(success, error) - - fun get(id: AccountObjectId, success: (Account) -> Unit): Disposable = - api.get(id).subscribe(success, {}) - - fun get(id: AccountObjectId, callback: ApiCallback): Disposable = - api.get(id).subscribe({ v -> callback.onSuccess(v) }, { e -> callback.onError(e) }) - } - - class DCoreApiSync(api: DCoreApi) { - val accountApi = AccountApiSync(api.accountApi) - } - - class DCoreApiAsync(api: DCoreApi) { - val accountApi = AccountApiAsync(api.accountApi) - } - - class DCoreApiFuture(api: DCoreApi) { - val accountApi = AccountApiFuture(api.accountApi) - } -} - -val api = DCoreApi(DCoreClient(OkHttpClient.Builder().build(), "wss://testnet-api.dcore.io", "https://testnet-api.dcore.io/")) - -fun DCoreApi.createSync() = Apis.DCoreApiSync(this) -fun DCoreApi.createAsync() = Apis.DCoreApiAsync(this) -fun DCoreApi.createFuture() = Apis.DCoreApiFuture(this) - -object DCoreSdka { - - @JvmStatic @JvmOverloads - fun create(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): Apis.DCoreApiSync = - api.createSync() - - @JvmStatic @JvmOverloads - fun createAsync(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): Apis.DCoreApiAsync = - api.createAsync() - - @JvmStatic @JvmOverloads - fun createFuture(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): Apis.DCoreApiFuture = - api.createFuture() - - @JvmStatic @JvmOverloads - fun createRx(client: OkHttpClient, webSocketUrl: String?, httpUrl: String?, logger: Logger? = null): DCoreApi = - api -} - -fun main() { - val callback = api.createAsync() - callback.accountApi.get(AccountObjectId(27), object : Apis.ApiCallback { - override fun onSuccess(value: Account) { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } - - override fun onError(error: Throwable) { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } - - }) - callback.accountApi.get("1.2.27".toObjectId()) { account -> account.print() } - - - val sync = api.createSync() - sync.accountApi.get("1.2.27".toObjectId()) - - val future = api.createFuture() - future.accountApi.get("1.2.27".toObjectId()) -} diff --git a/library/src/main/java/ch/decent/sdk/DCoreClient.kt b/library/src/main/java/ch/decent/sdk/DCoreClient.kt index 0d789723..da267f25 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreClient.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreClient.kt @@ -1,5 +1,6 @@ package ch.decent.sdk +import ch.decent.sdk.api.rx.DCoreApi import ch.decent.sdk.crypto.Address import ch.decent.sdk.model.AddressAdapter import ch.decent.sdk.model.AuthMap diff --git a/library/src/main/java/ch/decent/sdk/DCoreApi.kt b/library/src/main/java/ch/decent/sdk/api/BaseCoreApi.kt similarity index 58% rename from library/src/main/java/ch/decent/sdk/DCoreApi.kt rename to library/src/main/java/ch/decent/sdk/api/BaseCoreApi.kt index 5807af08..d08a4183 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/BaseCoreApi.kt @@ -1,23 +1,7 @@ -package ch.decent.sdk +package ch.decent.sdk.api -import ch.decent.sdk.DCoreConstants.EXPIRATION_DEF -import ch.decent.sdk.api.AccountApi -import ch.decent.sdk.api.AssetApi -import ch.decent.sdk.api.BalanceApi -import ch.decent.sdk.api.BlockApi -import ch.decent.sdk.api.BroadcastApi -import ch.decent.sdk.api.CallbackApi -import ch.decent.sdk.api.ContentApi -import ch.decent.sdk.api.GeneralApi -import ch.decent.sdk.api.HistoryApi -import ch.decent.sdk.api.MessagingApi -import ch.decent.sdk.api.MiningApi -import ch.decent.sdk.api.NftApi -import ch.decent.sdk.api.PurchaseApi -import ch.decent.sdk.api.SeederApi -import ch.decent.sdk.api.SubscriptionApi -import ch.decent.sdk.api.TransactionApi -import ch.decent.sdk.api.ValidationApi +import ch.decent.sdk.DCoreClient +import ch.decent.sdk.DCoreConstants import ch.decent.sdk.model.NftModel import ch.decent.sdk.model.NftObjectId import ch.decent.sdk.model.RawNft @@ -26,13 +10,12 @@ import org.threeten.bp.Duration import java.util.concurrent.TimeoutException import kotlin.reflect.KClass -class DCoreApi internal constructor(internal val core: DCoreClient) { - +abstract class BaseCoreApi(internal val core: DCoreClient) { /** * default transaction expiration in seconds used when broadcasting transactions, * after the expiry the transaction is removed from recent pool and will be dismissed if not included in DCore block */ - var transactionExpiration: Duration = Duration.ofSeconds(EXPIRATION_DEF) + var transactionExpiration: Duration = Duration.ofSeconds(DCoreConstants.EXPIRATION_DEF) /** * websocket request timeout, if no response is delivered within time window a [TimeoutException] is thrown @@ -48,24 +31,6 @@ class DCoreApi internal constructor(internal val core: DCoreClient) { internal val registeredNfts = mutableMapOf>() - val accountApi = AccountApi(this) - val assetApi = AssetApi(this) - val validationApi = ValidationApi(this) - val balanceApi = BalanceApi(this) - val blockApi = BlockApi(this) - val broadcastApi = BroadcastApi(this) - val contentApi = ContentApi(this) - val generalApi = GeneralApi(this) - val historyApi = HistoryApi(this) - val miningApi = MiningApi(this) - val purchaseApi = PurchaseApi(this) - val seederApi = SeederApi(this) - val callbackApi = CallbackApi(this) - val subscriptionApi = SubscriptionApi(this) - val transactionApi = TransactionApi(this) - val messagingApi = MessagingApi(this) - val nftApi = NftApi(this) - /** * Register NFT data model with object id, if no model is provided the [RawNft] will be used * @@ -114,5 +79,4 @@ class DCoreApi internal constructor(internal val core: DCoreClient) { fun unregisterNfts(ids: List) { ids.forEach { unregisterNft(it) } } - } diff --git a/library/src/main/java/ch/decent/sdk/api/Callback.kt b/library/src/main/java/ch/decent/sdk/api/Callback.kt new file mode 100644 index 00000000..368e5320 --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/api/Callback.kt @@ -0,0 +1,20 @@ +package ch.decent.sdk.api + +import io.reactivex.Single +import io.reactivex.observers.DisposableSingleObserver + +abstract class Callback : DisposableSingleObserver() { + override fun onError(e: Throwable) {} + + fun cancel() = dispose() +} + + +fun get(callback: Callback) = Single.just(Unit) + .subscribeWith(callback) + +fun foo() { + get(object : Callback() { + override fun onSuccess(t: Unit) {} + }) +} diff --git a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/AccountApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt index 408da135..911cadec 100644 --- a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Address import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.crypto.ECKeyPair @@ -13,6 +12,7 @@ import ch.decent.sdk.model.AccountOptions import ch.decent.sdk.model.AssetAmount import ch.decent.sdk.model.Authority import ch.decent.sdk.model.Fee +import ch.decent.sdk.model.FullAccount import ch.decent.sdk.model.Memo import ch.decent.sdk.model.ObjectId import ch.decent.sdk.model.SearchAccountHistoryOrder @@ -129,7 +129,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return map of names or ids to account, or empty map if not present */ @JvmOverloads - fun getFullAccounts(namesOrIds: List, subscribe: Boolean = false) = + fun getFullAccounts(namesOrIds: List, subscribe: Boolean = false): Single> = GetFullAccounts(namesOrIds, subscribe).toRequest() /** @@ -211,7 +211,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * @param keyPair sender's key pair, mandatory for encrypted message */ @JvmOverloads - fun createMemo(message: String, recipient: String? = null, keyPair: ECKeyPair? = null) = + fun createMemo(message: String, recipient: String? = null, keyPair: ECKeyPair? = null): Single = if (keyPair != null && recipient != null) { get(recipient).map { Memo(message, keyPair, it.primaryAddress) } } else { diff --git a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/AssetApi.kt similarity index 99% rename from library/src/main/java/ch/decent/sdk/api/AssetApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/AssetApi.kt index 899a90cc..465f9ee5 100644 --- a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/AssetApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.AccountObjectId diff --git a/library/src/main/java/ch/decent/sdk/api/BalanceApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/BalanceApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/BalanceApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/BalanceApi.kt index 62ae762f..9c46d6cc 100644 --- a/library/src/main/java/ch/decent/sdk/api/BalanceApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/BalanceApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.DCoreConstants import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AmountWithAsset diff --git a/library/src/main/java/ch/decent/sdk/api/BaseApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/BaseApi.kt similarity index 90% rename from library/src/main/java/ch/decent/sdk/api/BaseApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/BaseApi.kt index 5f90d78a..0e5e1158 100644 --- a/library/src/main/java/ch/decent/sdk/api/BaseApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/BaseApi.kt @@ -1,12 +1,10 @@ -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.model.TransactionConfirmation import ch.decent.sdk.model.operation.BaseOperation import ch.decent.sdk.net.model.request.BaseRequest import ch.decent.sdk.net.model.request.WithCallback -import com.google.gson.Gson import io.reactivex.Flowable import io.reactivex.Single diff --git a/library/src/main/java/ch/decent/sdk/api/BlockApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/BlockApi.kt similarity index 88% rename from library/src/main/java/ch/decent/sdk/api/BlockApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/BlockApi.kt index 9c73eca3..85b26f0b 100644 --- a/library/src/main/java/ch/decent/sdk/api/BlockApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/BlockApi.kt @@ -1,10 +1,10 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.BlockHeader +import ch.decent.sdk.model.SignedBlock import ch.decent.sdk.net.model.request.GetBlock import ch.decent.sdk.net.model.request.GetBlockHeader import ch.decent.sdk.net.model.request.HeadBlockTime @@ -20,7 +20,7 @@ class BlockApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return the referenced block, or [ObjectNotFoundException] if no matching block was found */ - fun get(blockNum: Long) = GetBlock(blockNum).toRequest() + fun get(blockNum: Long): Single = GetBlock(blockNum).toRequest() /** * Retrieve a block header. diff --git a/library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/BroadcastApi.kt similarity index 99% rename from library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/BroadcastApi.kt index 98325e8d..a72c8aa7 100644 --- a/library/src/main/java/ch/decent/sdk/api/BroadcastApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/BroadcastApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.ECKeyPair import ch.decent.sdk.model.Transaction import ch.decent.sdk.model.TransactionConfirmation diff --git a/library/src/main/java/ch/decent/sdk/api/CallbackApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/CallbackApi.kt similarity index 96% rename from library/src/main/java/ch/decent/sdk/api/CallbackApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/CallbackApi.kt index 436cd1be..25dc3f83 100644 --- a/library/src/main/java/ch/decent/sdk/api/CallbackApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/CallbackApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.net.model.request.CancelAllSubscriptions import ch.decent.sdk.net.model.request.SetBlockAppliedCallback import ch.decent.sdk.net.model.request.SetContentUpdateCallback diff --git a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/ContentApi.kt similarity index 99% rename from library/src/main/java/ch/decent/sdk/api/ContentApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/ContentApi.kt index 36b274f2..dffdcfa3 100644 --- a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/ContentApi.kt @@ -1,14 +1,11 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.AccountObjectId -import ch.decent.sdk.model.ApplicationType import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.CategoryType import ch.decent.sdk.model.CoAuthors import ch.decent.sdk.model.Content import ch.decent.sdk.model.ContentKeys diff --git a/library/src/main/java/ch/decent/sdk/api/rx/DCoreApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/DCoreApi.kt new file mode 100644 index 00000000..03bc3f80 --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/api/rx/DCoreApi.kt @@ -0,0 +1,24 @@ +package ch.decent.sdk.api.rx + +import ch.decent.sdk.DCoreClient +import ch.decent.sdk.api.BaseCoreApi + +class DCoreApi internal constructor(core: DCoreClient) : BaseCoreApi(core) { + val accountApi = AccountApi(this) + val assetApi = AssetApi(this) + val validationApi = ValidationApi(this) + val balanceApi = BalanceApi(this) + val blockApi = BlockApi(this) + val broadcastApi = BroadcastApi(this) + val contentApi = ContentApi(this) + val generalApi = GeneralApi(this) + val historyApi = HistoryApi(this) + val miningApi = MiningApi(this) + val purchaseApi = PurchaseApi(this) + val seederApi = SeederApi(this) + val callbackApi = CallbackApi(this) + val subscriptionApi = SubscriptionApi(this) + val transactionApi = TransactionApi(this) + val messagingApi = MessagingApi(this) + val nftApi = NftApi(this) +} diff --git a/library/src/main/java/ch/decent/sdk/api/GeneralApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/GeneralApi.kt similarity index 97% rename from library/src/main/java/ch/decent/sdk/api/GeneralApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/GeneralApi.kt index f32b1c65..f2676431 100644 --- a/library/src/main/java/ch/decent/sdk/api/GeneralApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/GeneralApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.model.ChainProperties import ch.decent.sdk.model.Config import ch.decent.sdk.model.DynamicGlobalProps diff --git a/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/HistoryApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/HistoryApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/HistoryApi.kt index 627eb727..8d661637 100644 --- a/library/src/main/java/ch/decent/sdk/api/HistoryApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/HistoryApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.BalanceChange diff --git a/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt similarity index 99% rename from library/src/main/java/ch/decent/sdk/api/MessagingApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt index d6f46a17..0e66af60 100644 --- a/library/src/main/java/ch/decent/sdk/api/MessagingApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.model.Account import ch.decent.sdk.model.AccountObjectId diff --git a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/MiningApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/MiningApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/MiningApi.kt index ded6e908..8fb4808c 100644 --- a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/MiningApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.AccountObjectId @@ -60,7 +59,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { */ // todo model @JvmOverloads - fun getFeedsByMiner(account: AccountObjectId, count: Int = REQ_LIMIT_MAX) = GetFeedsByMiner(account, count).toRequest() + fun getFeedsByMiner(account: AccountObjectId, count: Int = REQ_LIMIT_MAX): Single> = GetFeedsByMiner(account, count).toRequest() /** * Get the miner owned by a given account. diff --git a/library/src/main/java/ch/decent/sdk/api/NftApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/NftApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/NftApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/NftApi.kt index 20164c76..b3c620bb 100644 --- a/library/src/main/java/ch/decent/sdk/api/NftApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/NftApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.AccountObjectId @@ -115,7 +114,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return NFT data objects, or [ObjectNotFoundException] if none found */ - fun getAllData(ids: List): Single>> = getAllDataRaw(ids).make() + fun getAllData(ids: List): Single>> = getAllDataRaw(ids).make() /** * Get NFT data instances with raw model @@ -154,7 +153,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return NFT data object, or [ObjectNotFoundException] if none found */ - fun getData(id: NftDataObjectId): Single> = getAllData(listOf(id)).map { it.single() } + fun getData(id: NftDataObjectId): Single> = getAllData(listOf(id)).map { it.single() } /** * Get NFT data instance with raw model @@ -201,7 +200,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return NFT data instances */ @JvmOverloads - fun getNftBalances(account: AccountObjectId, nftIds: List = emptyList()): Single>> = + fun getNftBalances(account: AccountObjectId, nftIds: List = emptyList()): Single>> = getNftBalancesRaw(account, nftIds).make() /** @@ -268,7 +267,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return NFT data objects */ - fun listDataByNft(nftId: NftObjectId): Single>> = listDataByNftRaw(nftId).make() + fun listDataByNft(nftId: NftObjectId): Single>> = listDataByNftRaw(nftId).make() /** * Get NFT data instances with raw model @@ -579,12 +578,13 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { private fun Single>>.make(clazz: KClass) = map { it.map { nft -> NftData(nft, clazz) } } + @Suppress("UNCHECKED_CAST") private fun Single>>.make() = map { it.map { nft -> val clazz = api.registeredNfts[nft.nftId] if (clazz != null) NftData(nft, clazz) else nft - } + } as List> } } diff --git a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/PurchaseApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/PurchaseApi.kt index fed67bef..fd5535cf 100644 --- a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/PurchaseApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee diff --git a/library/src/main/java/ch/decent/sdk/api/SeederApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/SeederApi.kt similarity index 97% rename from library/src/main/java/ch/decent/sdk/api/SeederApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/SeederApi.kt index 98d65fd7..a0ef1ba5 100644 --- a/library/src/main/java/ch/decent/sdk/api/SeederApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/SeederApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Regions diff --git a/library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/SubscriptionApi.kt similarity index 98% rename from library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/SubscriptionApi.kt index 636cc938..2ad05240 100644 --- a/library/src/main/java/ch/decent/sdk/api/SubscriptionApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/SubscriptionApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.exception.ObjectNotFoundException import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Subscription diff --git a/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/TransactionApi.kt similarity index 96% rename from library/src/main/java/ch/decent/sdk/api/TransactionApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/TransactionApi.kt index 60a94b0f..c2b9ad7b 100644 --- a/library/src/main/java/ch/decent/sdk/api/TransactionApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/TransactionApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.ProcessedTransaction import ch.decent.sdk.model.Transaction @@ -49,7 +48,7 @@ class TransactionApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return a set of proposed transactions */ // todo model - fun getAllProposed(accountId: AccountObjectId) = GetProposedTransactions(accountId).toRequest() + fun getAllProposed(accountId: AccountObjectId): Single> = GetProposedTransactions(accountId).toRequest() /** * If the transaction has not expired, this method will return the transaction for the given ID or it will return [ch.decent.sdk.exception.ObjectNotFoundException]. diff --git a/library/src/main/java/ch/decent/sdk/api/ValidationApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/ValidationApi.kt similarity index 99% rename from library/src/main/java/ch/decent/sdk/api/ValidationApi.kt rename to library/src/main/java/ch/decent/sdk/api/rx/ValidationApi.kt index 4f792b82..d847c7a9 100644 --- a/library/src/main/java/ch/decent/sdk/api/ValidationApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/ValidationApi.kt @@ -1,8 +1,7 @@ @file:Suppress("TooManyFunctions", "LongParameterList") -package ch.decent.sdk.api +package ch.decent.sdk.api.rx -import ch.decent.sdk.DCoreApi import ch.decent.sdk.DCoreConstants import ch.decent.sdk.crypto.Address import ch.decent.sdk.exception.DCoreException diff --git a/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt b/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt index 77a38bc1..579b547c 100644 --- a/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt +++ b/library/src/main/java/ch/decent/sdk/model/operation/SendMessageOperation.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.model.operation -import ch.decent.sdk.DCoreApi +import ch.decent.sdk.api.rx.DCoreApi import ch.decent.sdk.DCoreClient import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.Fee diff --git a/library/src/main/java/ch/decent/sdk/poet/Blocking.kt b/library/src/main/java/ch/decent/sdk/poet/Blocking.kt deleted file mode 100644 index a2116466..00000000 --- a/library/src/main/java/ch/decent/sdk/poet/Blocking.kt +++ /dev/null @@ -1,208 +0,0 @@ -@file:Suppress( - "TooManyFunctions", - "LongParameterList", - "SpreadOperator", - "ComplexMethod", - "ThrowsCount" -) - -package ch.decent.sdk.poet - -import ch.decent.sdk.DCoreApi -import ch.decent.sdk.DCoreClient -import com.squareup.kotlinpoet.AnnotationSpec -import com.squareup.kotlinpoet.ClassName -import com.squareup.kotlinpoet.CodeBlock -import com.squareup.kotlinpoet.FileSpec -import com.squareup.kotlinpoet.FunSpec -import com.squareup.kotlinpoet.KModifier -import com.squareup.kotlinpoet.MemberName -import com.squareup.kotlinpoet.ParameterSpec -import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy -import com.squareup.kotlinpoet.PropertySpec -import com.squareup.kotlinpoet.TypeName -import com.squareup.kotlinpoet.TypeSpec -import com.squareup.kotlinpoet.TypeVariableName -import com.squareup.kotlinpoet.asClassName -import com.squareup.kotlinpoet.asTypeName -import io.reactivex.Single -import kastree.ast.Node -import kastree.ast.psi.Parser -import okhttp3.OkHttpClient -import org.slf4j.Logger -import java.io.File -import kotlin.reflect.KClass -import kotlin.reflect.full.declaredMembers - -fun Any?.print() = println(this.toString()) - -fun main() { -// val path = System.out - val path = out - Blocking.apiFiles.forEach { - it.writeTo(path) - println() - } - Blocking.apiFile.writeTo(path) - Factory.file.writeTo(path) -} - -fun Node.Expr.name() = (this as Node.Expr.Name).name -fun Node.File.structured() = this.decls.single() as Node.Decl.Structured -fun Node.WithModifiers.hasKeyword(keyword: Node.Modifier.Keyword) = this.mods.contains(Node.Modifier.Lit(keyword)) -fun Node.Decl.Func.Param.isNullable() = this.type?.ref is Node.TypeRef.Nullable -fun Node.Decl.Func.paramNames() = this.params.joinToString { it.name } - -fun Node.Decl.Func.paramSpecs(imports: List) = this.params.map { p -> - fun Node.Expr.defaultValue() = when (this) { - is Node.Expr.Const -> CodeBlock.of(this.value) - is Node.Expr.StringTmpl -> CodeBlock.of("%S", "") - is Node.Expr.BinaryOp -> { - when { - this.lhs is Node.Expr.Name && this.lhs.name() == apiNameRef -> CodeBlock.of("$apiNameRef.${this.rhs.name()}") - this.lhs is Node.Expr.Name -> CodeBlock.of("%T.${this.rhs.name()}", ClassName.bestGuess(this.lhs.name().fullName(imports))) - this.lhs is Node.Expr.BinaryOp -> (this.lhs as Node.Expr.BinaryOp) - .let { CodeBlock.of("%T.${it.rhs.name()}.${this.rhs.name()}", ClassName.bestGuess(it.lhs.name().fullName(imports))) } - else -> throw IllegalStateException() - } - } - is Node.Expr.Name -> CodeBlock.of("%M", this.name.member(imports)) - is Node.Expr.Call -> { - when { - this.args.isEmpty() && this.expr.name().first().isLowerCase() -> CodeBlock.of("%M()", this.expr.name().member(imports)) - this.args.isEmpty() -> CodeBlock.of("%T()", ClassName.bestGuess(this.expr.name().fullName(imports))) - else -> throw IllegalStateException() - } - } - else -> throw IllegalStateException() - } - val builder = ParameterSpec.builder(p.name, p.type!!.typeName(imports).copy(nullable = p.isNullable())) - p.default?.let { builder.defaultValue(it.defaultValue()) } - return@map builder.build() -} - -fun Node.TypeRef.Simple.fullName(imports: List) = this.pieces.single().name.fullName(imports) - -fun String.member(imports: List) = MemberName(fullName(imports).substringBeforeLast("."), this) - -fun String.fullName(imports: List) = when (this) { - "Class" -> "java.lang.$this" - "List", "Map", "emptyList" -> "kotlin.collections.$this" - "Long", "Int", "Short", "Byte", "String", "Boolean" -> "kotlin.$this" - else -> imports.find { it.substringAfterLast(".") == this }?.substringAfter("import ") -} ?: this - -fun Node.Type.typeName(imports: List): TypeName { - fun recursive(r: Node.TypeRef?): TypeName { - val type = when { - r is Node.TypeRef.Simple && r.pieces.single().typeParams.isEmpty() -> ClassName.bestGuess(r.fullName(imports)) - r is Node.TypeRef.Simple -> ClassName.bestGuess(r.fullName(imports)).parameterizedBy(*r.pieces.single().typeParams.map { recursive(it?.ref) }.toTypedArray()) - r is Node.TypeRef.Nullable -> recursive(r.type) - else -> throw IllegalStateException("unknown node: $r") - } - return if (type is ClassName && type.simpleName == "T") TypeVariableName("T") - else type - } - - return recursive(this.ref) -} - -fun Node.TypeParam.typeName(imports: List): TypeVariableName = - TypeVariableName(name, ClassName.bestGuess((type!! as Node.TypeRef.Simple).fullName(imports))) - -val out = File("library/src-gen/main/java") -val srcApi = "library/src/main/java/ch/decent/sdk/api/" -val packageName = "ch.decent.sdk" -val apiNameRef = "api" -val clientRef = DCoreClient::class.asClassName() -val apiRef = DCoreApi::class.asClassName() - -val apiClasses = File(srcApi).listFiles()!!.map { Parser.parseFile(it.readText()) } - .filterNot { it.structured().hasKeyword(Node.Modifier.Keyword.ABSTRACT) } - .filterNot { it.structured().name == "CallbackApi" } - -object Factory { - - private fun nullable(name: String, klass: KClass<*>) = - ParameterSpec.builder(name, klass.asTypeName().copy(nullable = true)).defaultValue("null").build() - - fun builder(apiName: String, apiFile: FileSpec) = FunSpec.builder(apiName) - .addParameter("client", OkHttpClient::class) - .addParameter(nullable("websocketUrl", String::class)) - .addParameter(nullable("httpUrl", String::class)) - .addParameter(nullable("logger", Logger::class)) - .addStatement("return %T(%T(%T(client, websocketUrl, httpUrl, logger)))", ClassName(apiFile.packageName, apiFile.name), apiRef, clientRef) - .build() - - val file = FileSpec.builder("ch.decent.sdk", "DCoreSdk") - .addType(TypeSpec.objectBuilder("DCoreSdk") - .addFunction(builder("createApiBlocking", Blocking.apiFile)) - .build()) - .build() -} - -object Blocking { - - val pckg = "$packageName.api.blocking" - private val blockingGet = Single<*>::blockingGet.name - private val members = apiClasses.map { ClassName(pckg, it.structured().name) } - - val api = TypeSpec.classBuilder("DCoreApi") - .primaryConstructor(FunSpec.constructorBuilder() - .addParameter(apiNameRef, apiRef) - .build()) - .addProperties(members.map { - val name = it.simpleName.decapitalize() - PropertySpec.builder(name, it) - .initializer("%T($apiNameRef.$name)", it) - .build() - }) - .build() - val apiFile = FileSpec.builder(pckg, api.name!!).addType(api).build() - - val apis = apiClasses.map { - - val klass = ClassName(it.pkg!!.names.joinToString("."), it.structured().name) - - val apiProp = PropertySpec.builder(apiNameRef, klass, KModifier.PRIVATE) - .initializer(apiNameRef) - .build() - - val ctor = FunSpec.constructorBuilder() - .addModifiers(KModifier.INTERNAL) - .addParameter(apiProp.name, apiProp.type, KModifier.PRIVATE) - .build() - - val methods = it.structured().members - .filterIsInstance() - .filterNot { it.hasKeyword(Node.Modifier.Keyword.PRIVATE) } - .map { f -> - val i = it.imports.map { it.names.joinToString(".") } - val b = FunSpec.builder(f.name!!) - .addCode("return $apiNameRef.%L(${f.paramNames()}).%L()", f.name, blockingGet) - .addParameters(f.paramSpecs(i)) - - if (f.typeParams.isNotEmpty()) { - b.addTypeVariable(f.typeParams.single().typeName(i)) - } - b.build() - } - - TypeSpec.classBuilder(klass) - .addProperty(apiProp) - .primaryConstructor(ctor) - .addFunctions(methods) - .build() - } - val apiFiles = apis.map { - FileSpec.builder(pckg, it.name!!) - .addAnnotation( - AnnotationSpec.builder(Suppress::class) - .addMember("%S", "TooManyFunctions") - .addMember("%S", "LongParameterList") - .build() - ) - .addType(it) - .build() - } -} diff --git a/library/src/test/java/ch/decent/sdk/Scratchpad.kt b/library/src/test/java/ch/decent/sdk/Scratchpad.kt index 2a8449f7..842e9e8e 100644 --- a/library/src/test/java/ch/decent/sdk/Scratchpad.kt +++ b/library/src/test/java/ch/decent/sdk/Scratchpad.kt @@ -17,6 +17,7 @@ import ch.decent.sdk.utils.unhex import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject +import okhttp3.OkHttpClient import okio.Buffer import okio.ByteString.Companion.decodeHex import org.amshove.kluent.`should be equal to` @@ -302,4 +303,8 @@ class Scratchpad { "hello hex".unhex() } + @Test fun `check generated`() { + DCoreSdk.createApiBlocking(OkHttpClient()) + } + } diff --git a/library/src/test/java/ch/decent/sdk/api/Base.kt b/library/src/test/java/ch/decent/sdk/api/Base.kt index cfc3d48f..8e67983a 100644 --- a/library/src/test/java/ch/decent/sdk/api/Base.kt +++ b/library/src/test/java/ch/decent/sdk/api/Base.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.api -import ch.decent.sdk.DCoreApi +import ch.decent.sdk.api.rx.DCoreApi import ch.decent.sdk.DCoreClient import ch.decent.sdk.Helpers import ch.decent.sdk.TimeOutTest diff --git a/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt b/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt index ddecb883..06769b9e 100644 --- a/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt +++ b/library/src/test/java/ch/decent/sdk/api/CallbackApiTest.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.api -import ch.decent.sdk.DCoreApi +import ch.decent.sdk.api.rx.DCoreApi import ch.decent.sdk.DCoreClient import ch.decent.sdk.Helpers import io.reactivex.schedulers.Schedulers diff --git a/library/src/test/java/ch/decent/sdk/java/ApiTest.java b/library/src/test/java/ch/decent/sdk/java/ApiTest.java index acb91fe7..fe38f45b 100644 --- a/library/src/test/java/ch/decent/sdk/java/ApiTest.java +++ b/library/src/test/java/ch/decent/sdk/java/ApiTest.java @@ -1,6 +1,6 @@ package ch.decent.sdk.java; -import ch.decent.sdk.DCoreApi; +import ch.decent.sdk.api.rx.DCoreApi; import ch.decent.sdk.DCoreConstants; import ch.decent.sdk.DCoreClient; import ch.decent.sdk.Helpers; diff --git a/settings.gradle.kts b/settings.gradle.kts index 44219479..084be434 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1 +1 @@ -include(Modules.sdk) +include(Modules.sdk, Modules.apiGen) From 00463bc1c303f902635241b4b0b302c8018cab29 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Thu, 1 Aug 2019 18:13:53 +0200 Subject: [PATCH 04/19] cancelable --- .../main/java/ch/decent/sdk/poet/ApiDescriptor.kt | 3 +-- .../src/main/java/ch/decent/sdk/poet/Builders.kt | 4 +--- apiGen/src/main/java/ch/decent/sdk/poet/Main.kt | 12 +++++++----- .../src/main/java/ch/decent/sdk/api/Callback.kt | 15 ++++----------- 4 files changed, 13 insertions(+), 21 deletions(-) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt b/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt index e9ad85ee..b29b247c 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt @@ -7,8 +7,7 @@ data class ApiDescriptor( val packageSuffix: String, val createMethodName: String, val returnCodeBlock: String, - val returnType: (TypeName) -> TypeName = { it }, - val methodBuilder: (FunSpec.Builder) -> Any = { } + val methodBuilder: FunSpec.Builder.(TypeName) -> Any = { returns(it) } ) { val packageName = "$packageNameApi.$packageSuffix" } diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt index 83047c29..9de08749 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -47,16 +47,14 @@ object Builders { .filterNot { it.hasKeyword(Node.Modifier.Keyword.PRIVATE) } .map { f -> val i = it.imports.map { it.names.joinToString(".") } - val returnType = f.type!!.returnType(i) val b = FunSpec.builder(f.name!!) .addCode("return $apiNameRef.%L(${f.paramNames()}).%L", f.name, api.returnCodeBlock) .addParameters(f.paramSpecs(i)) - .returns(api.returnType(returnType)) if (f.typeParams.isNotEmpty()) b.addTypeVariable(f.typeParams.single().typeName(i)) DocReader.applyDocs(b, apiDoc, f, i) - api.methodBuilder(b) + api.methodBuilder(b, f.type!!.returnType(i)) b.build() } diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt index 6ae06e07..b7b3a718 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt @@ -22,11 +22,13 @@ val apiClasses = File(srcApi).listFiles()!!.map { Parser.parseFile(it.readText() val apis = listOf( ApiDescriptor("blocking", "createApiBlocking", "blockingGet()"), - ApiDescriptor("futures", "createApiFutures", "toFuture()", - { Future::class.asClassName().parameterizedBy(it) }), - ApiDescriptor("callback", "createApi", "subscribeWith(callback)", - { ClassName.bestGuess("$packageNameApi.Callback").parameterizedBy(it) }, - { it.addParameter("callback", it.build().returnType!!) }) + ApiDescriptor("futures", "createApiFutures", "toFuture()") + { returns(Future::class.asClassName().parameterizedBy(it)) }, + ApiDescriptor("callback", "createApi", "subscribeWith(callback)") + { + returns(ClassName.bestGuess("$packageNameApi.Cancelable")) + addParameter("callback", ClassName.bestGuess("$packageNameApi.Callback").parameterizedBy(it)) + } ) fun main() { diff --git a/library/src/main/java/ch/decent/sdk/api/Callback.kt b/library/src/main/java/ch/decent/sdk/api/Callback.kt index 368e5320..d79011ca 100644 --- a/library/src/main/java/ch/decent/sdk/api/Callback.kt +++ b/library/src/main/java/ch/decent/sdk/api/Callback.kt @@ -1,20 +1,13 @@ package ch.decent.sdk.api -import io.reactivex.Single import io.reactivex.observers.DisposableSingleObserver -abstract class Callback : DisposableSingleObserver() { +abstract class Callback : DisposableSingleObserver(), Cancelable { override fun onError(e: Throwable) {} - fun cancel() = dispose() + override fun cancel() = dispose() } - -fun get(callback: Callback) = Single.just(Unit) - .subscribeWith(callback) - -fun foo() { - get(object : Callback() { - override fun onSuccess(t: Unit) {} - }) +interface Cancelable { + fun cancel() } From 3c79d1d6e8ad355d939a35cfad7b36bae2d1a2af Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Thu, 1 Aug 2019 18:33:43 +0200 Subject: [PATCH 05/19] jvm overloads --- apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt | 5 +++++ apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt | 1 + library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt | 2 ++ 3 files changed, 8 insertions(+) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt index 9de08749..4dfb3be8 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -55,6 +55,11 @@ object Builders { if (f.typeParams.isNotEmpty()) b.addTypeVariable(f.typeParams.single().typeName(i)) DocReader.applyDocs(b, apiDoc, f, i) api.methodBuilder(b, f.type!!.returnType(i)) + f.mods.filterIsInstance().singleOrNull()?.run { + anns.map { it.names }.flatten() + .map { AnnotationSpec.builder(it.className(i)).build() } + .let { b.addAnnotations(it) } + } b.build() } diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt index 9efcad2f..18a65c13 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt @@ -62,6 +62,7 @@ fun String.fullName(imports: List) = when (this) { "Class" -> "java.lang.$this" "List", "Map", "emptyList" -> "kotlin.collections.$this" "Long", "Int", "Short", "Byte", "String", "Boolean", "Unit", "Any" -> "kotlin.$this" + "JvmOverloads" -> "kotlin.jvm.$this" else -> imports.find { it.substringAfterLast(".") == this }?.substringAfter("import ") } ?: this diff --git a/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt index 911cadec..861bd3ea 100644 --- a/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt @@ -182,6 +182,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return account history list */ +/* @Deprecated(message = "Use history API") @JvmOverloads fun searchAccountHistory( @@ -190,6 +191,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, limit: Int = REQ_LIMIT_MAX ): Single> = SearchAccountHistory(accountId, order, from, limit).toRequest() +*/ /** * Create API credentials. From 013aa0de9d7261802afc7f77e8c7e72e9486ad16 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Fri, 2 Aug 2019 10:46:45 +0200 Subject: [PATCH 06/19] docs for callback --- .../java/ch/decent/sdk/poet/ApiDescriptor.kt | 2 ++ .../main/java/ch/decent/sdk/poet/Builders.kt | 3 +- .../main/java/ch/decent/sdk/poet/DocReader.kt | 34 +++++++++---------- .../src/main/java/ch/decent/sdk/poet/Main.kt | 12 ++++--- 4 files changed, 27 insertions(+), 24 deletions(-) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt b/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt index b29b247c..a1c4f975 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/ApiDescriptor.kt @@ -1,5 +1,6 @@ package ch.decent.sdk.poet +import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.TypeName @@ -7,6 +8,7 @@ data class ApiDescriptor( val packageSuffix: String, val createMethodName: String, val returnCodeBlock: String, + val docBuilder: (String) -> String = { it }, val methodBuilder: FunSpec.Builder.(TypeName) -> Any = { returns(it) } ) { val packageName = "$packageNameApi.$packageSuffix" diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt index 4dfb3be8..46ac7919 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -53,7 +53,8 @@ object Builders { .addParameters(f.paramSpecs(i)) if (f.typeParams.isNotEmpty()) b.addTypeVariable(f.typeParams.single().typeName(i)) - DocReader.applyDocs(b, apiDoc, f, i) + val docs = DocReader.applyDocs(apiDoc, f, i) + docs?.let { b.addKdoc(api.docBuilder(it)) } api.methodBuilder(b, f.type!!.returnType(i)) f.mods.filterIsInstance().singleOrNull()?.run { anns.map { it.names }.flatten() diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt b/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt index 336a26ee..52540b8b 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/DocReader.kt @@ -1,6 +1,6 @@ package ch.decent.sdk.poet -import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.CodeBlock import kastree.ast.Node import java.io.File @@ -36,24 +36,22 @@ object DocReader { get() = File(srcApi).listFiles()!! .associate { it.nameWithoutExtension to it.docs() } - fun applyDocs(b: FunSpec.Builder, docs: MutableList, f: Node.Decl.Func, i: List) { - val doc = docs.find { it.name == f.name } - doc?.let { - val args = mutableListOf() - val withImports = it.docs.replace(REGEX_DOC_LINK) { - it.value.drop(1).dropLast(1).let { - if (it.first().isLowerCase()) { - args.add(it.member(i)) - "[%M]" - } else { - args.add(it.className(i)) - "[%T]" + @Suppress("SpreadOperator") + fun applyDocs(docs: MutableList, f: Node.Decl.Func, i: List) = + docs.find { it.name == f.name }?.let { + val args = mutableListOf() + val withImports = it.docs.replace(REGEX_DOC_LINK) { + it.value.drop(1).dropLast(1).let { + if (it.first().isLowerCase()) { + args.add(it.member(i)) + "[%M]" + } else { + args.add(it.className(i)) + "[%T]" + } } } + docs.remove(it) + CodeBlock.of(withImports, *args.toTypedArray()).toString() } - b.addKdoc(withImports, *args.toTypedArray()) - docs.remove(it) - } - - } } diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt index b7b3a718..2602acd7 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt @@ -1,6 +1,7 @@ package ch.decent.sdk.poet import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.asClassName import kastree.ast.Node @@ -24,11 +25,12 @@ val apis = listOf( ApiDescriptor("blocking", "createApiBlocking", "blockingGet()"), ApiDescriptor("futures", "createApiFutures", "toFuture()") { returns(Future::class.asClassName().parameterizedBy(it)) }, - ApiDescriptor("callback", "createApi", "subscribeWith(callback)") - { - returns(ClassName.bestGuess("$packageNameApi.Cancelable")) - addParameter("callback", ClassName.bestGuess("$packageNameApi.Callback").parameterizedBy(it)) - } + ApiDescriptor("callback", "createApi", "subscribeWith(callback)", + { it.substringBefore("@return").trimEnd() + "\n@param callback a callback object that asynchronously receives the result value or error " }, + { + returns(ClassName.bestGuess("$packageNameApi.Cancelable"), CodeBlock.of("a request handler object which can be used to cancel the request")) + addParameter("callback", ClassName.bestGuess("$packageNameApi.Callback").parameterizedBy(it)) + }) ) fun main() { From e169ac2f9467b57b6789bc3f20808c43c5887fc8 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Fri, 2 Aug 2019 11:26:58 +0200 Subject: [PATCH 07/19] fix annotations to iclude deprecated --- .../main/java/ch/decent/sdk/poet/Builders.kt | 17 +++++++++++------ .../main/java/ch/decent/sdk/poet/KastreeExt.kt | 2 +- .../java/ch/decent/sdk/api/rx/AccountApi.kt | 4 +--- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt index 46ac7919..c1d158f1 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -28,7 +28,7 @@ object Builders { fun apiFile(api: ApiDescriptor) = apiClassSpec(api).let { FileSpec.builder(api.packageName, it.name!!).addType(it).build() } private fun apiServiceClasses(api: ApiDescriptor): List = apiClasses -// .filter { it.structured().name == "NftApi" } + .filter { it.structured().name == "AccountApi" } .map { val klass = ClassName(it.pkg!!.names.joinToString("."), it.structured().name) @@ -56,11 +56,16 @@ object Builders { val docs = DocReader.applyDocs(apiDoc, f, i) docs?.let { b.addKdoc(api.docBuilder(it)) } api.methodBuilder(b, f.type!!.returnType(i)) - f.mods.filterIsInstance().singleOrNull()?.run { - anns.map { it.names }.flatten() - .map { AnnotationSpec.builder(it.className(i)).build() } - .let { b.addAnnotations(it) } - } + f.mods.filterIsInstance().map { + it.anns.single().let { + val ba = AnnotationSpec.builder(it.names.single().className(i)) + it.args.singleOrNull()?.let { + val str = ((it.expr as Node.Expr.StringTmpl).elems.single() as Node.Expr.StringTmpl.Elem.Regular).str + ba.addMember("%S", str) + } + ba.build() + } + }.also { b.addAnnotations(it) } b.build() } diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt index 18a65c13..2135f043 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt @@ -61,7 +61,7 @@ fun String.member(imports: List) = MemberName(fullName(imports).substrin fun String.fullName(imports: List) = when (this) { "Class" -> "java.lang.$this" "List", "Map", "emptyList" -> "kotlin.collections.$this" - "Long", "Int", "Short", "Byte", "String", "Boolean", "Unit", "Any" -> "kotlin.$this" + "Long", "Int", "Short", "Byte", "String", "Boolean", "Unit", "Any", "Deprecated" -> "kotlin.$this" "JvmOverloads" -> "kotlin.jvm.$this" else -> imports.find { it.substringAfterLast(".") == this }?.substringAfter("import ") } ?: this diff --git a/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt index 861bd3ea..d323225a 100644 --- a/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/AccountApi.kt @@ -182,8 +182,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { * * @return account history list */ -/* - @Deprecated(message = "Use history API") + @Deprecated("Use history API") @JvmOverloads fun searchAccountHistory( accountId: AccountObjectId, @@ -191,7 +190,6 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { order: SearchAccountHistoryOrder = SearchAccountHistoryOrder.TIME_DESC, limit: Int = REQ_LIMIT_MAX ): Single> = SearchAccountHistory(accountId, order, from, limit).toRequest() -*/ /** * Create API credentials. From 806862993fd51c4c21af46e93a88df2660b2c799 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Fri, 2 Aug 2019 12:06:52 +0200 Subject: [PATCH 08/19] DSDK-701 add link in docs to op ctor for create ops methods --- .../src/main/java/ch/decent/sdk/api/AccountApi.kt | 6 +++--- .../src/main/java/ch/decent/sdk/api/AssetApi.kt | 14 ++++++++------ .../src/main/java/ch/decent/sdk/api/ContentApi.kt | 12 ++++++++---- .../src/main/java/ch/decent/sdk/api/MiningApi.kt | 2 +- library/src/main/java/ch/decent/sdk/api/NftApi.kt | 14 +++++++------- .../src/main/java/ch/decent/sdk/api/PurchaseApi.kt | 2 +- 6 files changed, 28 insertions(+), 22 deletions(-) diff --git a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt b/library/src/main/java/ch/decent/sdk/api/AccountApi.kt index e920277d..014110b0 100644 --- a/library/src/main/java/ch/decent/sdk/api/AccountApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/AccountApi.kt @@ -215,7 +215,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { } /** - * Create a transfer operation. + * Create a transfer operation. For more options see [TransferOperation] constructor. * * @param credentials account credentials * @param nameOrId account id or account name @@ -272,7 +272,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { } /** - * Create a register new account operation. + * Create a register new account operation. For more options see [AccountCreateOperation] constructor. * * @param registrar account id used to register the new account * @param name new account name @@ -311,7 +311,7 @@ class AccountApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(registrar) /** - * Create update account operation. Fills model with actual account values. + * Create update account operation. Fills model with actual account values. For more options see [AccountUpdateOperation] constructor. * * @param nameOrId account id or name * @param fee {@link AssetAmount} fee for the operation or asset id, if left undefined the fee will be computed in DCT asset. diff --git a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt b/library/src/main/java/ch/decent/sdk/api/AssetApi.kt index ca76acbe..15d6e9bd 100644 --- a/library/src/main/java/ch/decent/sdk/api/AssetApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/AssetApi.kt @@ -24,6 +24,7 @@ import ch.decent.sdk.model.operation.AssetIssueOperation import ch.decent.sdk.model.operation.AssetReserveOperation import ch.decent.sdk.model.operation.AssetUpdateAdvancedOperation import ch.decent.sdk.model.operation.AssetUpdateOperation +import ch.decent.sdk.model.operation.TransferOperation import ch.decent.sdk.model.toChainObject import ch.decent.sdk.net.model.request.GetAssets import ch.decent.sdk.net.model.request.GetAssetsData @@ -137,7 +138,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { /** - * Create asset create operation. + * Create asset create operation. For more options see [AssetCreateOperation] constructor. * * @param issuer account id issuing the asset * @param symbol the string symbol, 3-16 uppercase chars @@ -201,7 +202,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create update asset operation. Fills model with actual asset values. + * Create update asset operation. Fills model with actual asset values. For more options see [AssetUpdateOperation] constructor. * * @param assetIdOrSymbol asset to update * @param newIssuer a new issuer account id @@ -253,7 +254,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create update advanced options operation for the asset. + * Create update advanced options operation for the asset. For more options see [AssetUpdateAdvancedOperation] constructor. * * @param assetIdOrSymbol asset to update * @param fee [Fee] fee for the operation, by default the fee will be computed in DCT asset. @@ -294,6 +295,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { /** * Create issue asset operation. Only the issuer of the asset can issue some funds until maxSupply is reached. + * For more options see [AssetIssueOperation] constructor. * * @param assetIdOrSymbol asset to issue * @param amount raw amount to issue @@ -334,7 +336,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create fund asset pool operation. Any account can fund a pool. + * Create fund asset pool operation. Any account can fund a pool. For more options see [AssetFundPoolsOperation] constructor. * * @param assetIdOrSymbol which asset to fund * @param uia UIA raw amount @@ -371,7 +373,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create claim fees operation. Claim funds from asset pool, only the asset issuer can claim. + * Create claim fees operation. Claim funds from asset pool, only the asset issuer can claim. For more options see [AssetClaimFeesOperation] constructor. * * @param assetIdOrSymbol which asset to claim from * @param uia UIA raw amount @@ -408,7 +410,7 @@ class AssetApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create reserve funds operation. Return issued funds to the issuer of the asset. + * Create reserve funds operation. Return issued funds to the issuer of the asset. For more options see [AssetReserveOperation] constructor. * * @param assetIdOrSymbol which asset to reserve from * @param amount raw amount to remove from current supply diff --git a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt b/library/src/main/java/ch/decent/sdk/api/ContentApi.kt index 9ab03095..979764e4 100644 --- a/library/src/main/java/ch/decent/sdk/api/ContentApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/ContentApi.kt @@ -120,7 +120,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { ): Single> = SearchContent(term, order, user, regionCode, type, startId, limit).toRequest() /** - * Create a purchase content operation. + * Create a purchase content operation. For more options see [PurchaseContentOperation] constructor. * * @param credentials account credentials * @param contentId object id of the content, 2.13.* @@ -139,7 +139,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { /** - * Create a purchase content operation. + * Create a purchase content operation. For more options see [PurchaseContentOperation] constructor. * * @param credentials account credentials * @param uri uri of the content @@ -197,7 +197,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { /** * Create amount transfer operation of one asset to content. Amount is transferred to author and co-authors of the content, if they are specified. - * Fees are paid by the "from" account. + * Fees are paid by the "from" account. For more options see [TransferOperation] constructor. * * @param credentials account credentials * @param id content id @@ -244,6 +244,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { /** * Create remove content operation. Sets expiration to head block time, so the content cannot be purchased, but remains in database. + * For more options see [RemoveContentOperation] constructor. * * @param content content id * @param fee {@link AssetAmount} fee for the operation or asset id, if left undefined the fee will be computed in DCT asset. @@ -255,6 +256,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { /** * Create remove content operation. Sets expiration to head block time, so the content cannot be purchased, but remains in database. + * For more options see [RemoveContentOperation] constructor. * * @param content content uri * @param fee {@link AssetAmount} fee for the operation or asset id, if left undefined the fee will be computed in DCT asset. @@ -293,7 +295,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { } /** - * Create request to submit content operation. + * Create request to submit content operation. For more options see [AddOrUpdateContentOperation] constructor. * * @param author author of the content. If co-authors is not filled, this account will receive full payout * @param coAuthors if map is not empty, payout will be split - the parameter maps co-authors @@ -374,6 +376,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { /** * Create request to update content operation. Fills the model with actual content values. + * For more options see [AddOrUpdateContentOperation] constructor. * * @param content content id * @param fee {@link AssetAmount} fee for the operation or asset id, if left undefined the fee will be computed in DCT asset. @@ -387,6 +390,7 @@ class ContentApi internal constructor(api: DCoreApi) : BaseApi(api) { /** * Create request to update content operation. Fills the model with actual content values. + * For more options see [AddOrUpdateContentOperation] constructor. * * @param content content uri * @param fee {@link AssetAmount} fee for the operation or asset id, if left undefined the fee will be computed in DCT asset. diff --git a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt b/library/src/main/java/ch/decent/sdk/api/MiningApi.kt index 58cfe987..3e9d11b2 100644 --- a/library/src/main/java/ch/decent/sdk/api/MiningApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/MiningApi.kt @@ -143,7 +143,7 @@ class MiningApi internal constructor(api: DCoreApi) : BaseApi(api) { ): Single> = SearchMinerVoting(accountName, searchTerm, onlyMyVotes, order, id, limit).toRequest() /** - * Create vote for miner operation. + * Create vote for miner operation. For more options see [AccountUpdateOperation] constructor. * * @param accountId account object id, 1.2.* * @param minerIds list of miner account ids diff --git a/library/src/main/java/ch/decent/sdk/api/NftApi.kt b/library/src/main/java/ch/decent/sdk/api/NftApi.kt index 23435bcd..ee989f2c 100644 --- a/library/src/main/java/ch/decent/sdk/api/NftApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/NftApi.kt @@ -290,7 +290,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { fun searchNftHistory(nftDataId: ChainObject): Single> = SearchNftHistory(nftDataId).toRequest() /** - * Create NFT create operation + * Create NFT create operation. For more options see [NftCreateOperation] constructor. * * @param symbol NFT symbol * @param options NFT options @@ -310,7 +310,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { ): Single = Single.just(NftCreateOperation(symbol, options, NftModel.createDefinitions(clazz), transferable, fee)) /** - * Create NFT create operation + * Create NFT create operation. For more options see [NftCreateOperation] constructor. * * @param symbol NFT symbol * @param options NFT options @@ -382,7 +382,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { ): Single = create(credentials, symbol, maxSupply, fixedMaxSupply, description, clazz.kotlin, transferable, fee) /** - * Create NFT update operation. Fills model with actual values. + * Create NFT update operation. Fills model with actual values. For more options see [NftUpdateOperation] constructor. * * @param idOrSymbol NFT object id or symbol * @param fee [Fee] fee for the operation, by default the fee will be computed in DCT asset. @@ -418,7 +418,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create NFT issue operation. Creates a NFT data instance. + * Create NFT issue operation. Creates a NFT data instance. For more options see [NftIssueOperation] constructor. * * @param issuer NFT issuer * @param idOrSymbol NFT object id or symbol @@ -461,7 +461,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create NFT data instance transfer operation + * Create NFT data instance transfer operation. For more options see [NftTransferOperation] constructor. * * @param from NFT data instance owner account object id * @param to receiver account object id @@ -500,7 +500,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { .broadcast(credentials) /** - * Create NFT data instance update operation + * Create NFT data instance update operation. For more options see [NftUpdateDataOperation] constructor. * * @param modifier NFT data instance owner account object id, updatable values are set in [NftUpdateDataOperation.data] map * @param id NFT data instance object id @@ -521,7 +521,7 @@ class NftApi internal constructor(api: DCoreApi) : BaseApi(api) { } /** - * Create NFT data instance update operation + * Create NFT data instance update operation. For more options see [NftUpdateDataOperation] constructor. * * @param modifier NFT data instance owner account object id * @param id NFT data instance object id diff --git a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt b/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt index cd21c663..a4c37b6b 100644 --- a/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/PurchaseApi.kt @@ -108,7 +108,7 @@ class PurchaseApi internal constructor(api: DCoreApi) : BaseApi(api) { ): Single> = SearchFeedback(user, uri, startId, count).toRequest() /** - * Create a rate and comment content operation. + * Create a rate and comment content operation. For more options see [LeaveRatingAndCommentOperation] constructor. * * @param uri a uri of the content * @param consumer object id of the account, 1.2.* From 0e76e22dbcbb9bb9edced9d7b263975b40840130 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Fri, 2 Aug 2019 12:26:45 +0200 Subject: [PATCH 09/19] remove debug filter for accountApi, setup travis --- .travis.yml | 2 +- apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt | 2 +- apiGen/src/main/java/ch/decent/sdk/poet/Main.kt | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index dbb8b375..2d6b0237 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,7 +37,7 @@ before_script: # - docker-compose exec DCore id dcore script: - - ./gradlew build test + - ./gradlew run build test - ./gradlew jacocoTestReport - java -jar codacy-coverage-reporter-assembly.jar report -l Java -r library/build/reports/jacoco/test/jacocoTestReport.xml deploy: diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt index c1d158f1..4fb04f6d 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -28,7 +28,7 @@ object Builders { fun apiFile(api: ApiDescriptor) = apiClassSpec(api).let { FileSpec.builder(api.packageName, it.name!!).addType(it).build() } private fun apiServiceClasses(api: ApiDescriptor): List = apiClasses - .filter { it.structured().name == "AccountApi" } +// .filter { it.structured().name == "AccountApi" } .map { val klass = ClassName(it.pkg!!.names.joinToString("."), it.structured().name) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt index 2602acd7..b7d42055 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Main.kt @@ -34,7 +34,6 @@ val apis = listOf( ) fun main() { - File("").absolutePath.print() // val path = System.out val path = out apis.forEach { From 3b94832c230d163360bbfdc9c055b1b830be0226 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Fri, 2 Aug 2019 14:16:34 +0200 Subject: [PATCH 10/19] DSDK-716 get value throuh reflection set to accessible beforehand --- library/src/main/java/ch/decent/sdk/model/NftModel.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/library/src/main/java/ch/decent/sdk/model/NftModel.kt b/library/src/main/java/ch/decent/sdk/model/NftModel.kt index 5f29a77e..dce9e98c 100644 --- a/library/src/main/java/ch/decent/sdk/model/NftModel.kt +++ b/library/src/main/java/ch/decent/sdk/model/NftModel.kt @@ -10,6 +10,7 @@ import kotlin.reflect.KType import kotlin.reflect.full.createType import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.findAnnotation +import kotlin.reflect.jvm.isAccessible interface NftModel { fun values(): List = values(this) @@ -44,7 +45,11 @@ interface NftModel { .let { model.constructors.first().call(*it) } @Suppress("UNCHECKED_CAST") - internal fun values(model: T) = ordered(model::class).map { (it as KProperty1).get(model) } + internal fun values(model: T) = ordered(model::class).map { + val prop = (it as KProperty1) + prop.isAccessible = true + prop.get(model) + } @Suppress("IMPLICIT_CAST_TO_ANY") private fun parseType(values: JsonArray, idx: Int, type: KType) = From 3ebfb5814ed2795f6ee603f6bf825df8fd543629 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Mon, 5 Aug 2019 16:19:34 +0200 Subject: [PATCH 11/19] refactor variable names --- .../main/java/ch/decent/sdk/poet/Builders.kt | 32 +++++++------------ .../java/ch/decent/sdk/poet/KastreeExt.kt | 13 ++++++++ 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt index 4fb04f6d..73c20d40 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Builders.kt @@ -45,29 +45,19 @@ object Builders { val methods = it.structured().members .filterIsInstance() .filterNot { it.hasKeyword(Node.Modifier.Keyword.PRIVATE) } - .map { f -> - val i = it.imports.map { it.names.joinToString(".") } + .map { func -> + val imports = it.imports.map { it.names.joinToString(".") } - val b = FunSpec.builder(f.name!!) - .addCode("return $apiNameRef.%L(${f.paramNames()}).%L", f.name, api.returnCodeBlock) - .addParameters(f.paramSpecs(i)) + val builder = FunSpec.builder(func.name!!) + .addCode("return $apiNameRef.%L(${func.paramNames()}).%L", func.name, api.returnCodeBlock) + .addParameters(func.paramSpecs(imports)) - if (f.typeParams.isNotEmpty()) b.addTypeVariable(f.typeParams.single().typeName(i)) - val docs = DocReader.applyDocs(apiDoc, f, i) - docs?.let { b.addKdoc(api.docBuilder(it)) } - api.methodBuilder(b, f.type!!.returnType(i)) - f.mods.filterIsInstance().map { - it.anns.single().let { - val ba = AnnotationSpec.builder(it.names.single().className(i)) - it.args.singleOrNull()?.let { - val str = ((it.expr as Node.Expr.StringTmpl).elems.single() as Node.Expr.StringTmpl.Elem.Regular).str - ba.addMember("%S", str) - } - ba.build() - } - }.also { b.addAnnotations(it) } - - b.build() + if (func.typeParams.isNotEmpty()) builder.addTypeVariable(func.typeParams.single().typeName(imports)) + val docs = DocReader.applyDocs(apiDoc, func, imports) + docs?.let { builder.addKdoc(api.docBuilder(it)) } + api.methodBuilder(builder, func.type!!.returnType(imports)) + builder.addAnnotations(func.mods.filterIsInstance().buildAnnotations(imports)) + builder.build() } TypeSpec.classBuilder(klass) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt index 2135f043..a06edf50 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt @@ -8,6 +8,7 @@ package ch.decent.sdk.poet +import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.MemberName @@ -88,3 +89,15 @@ fun Node.Type.returnType(imports: List): TypeName = fun Node.TypeParam.typeName(imports: List): TypeVariableName = TypeVariableName(name, ClassName.bestGuess((type!! as Node.TypeRef.Simple).fullName(imports))) + +fun List.buildAnnotations(imports: List) = + map { + it.anns.single().let { + val builder = AnnotationSpec.builder(it.names.single().className(imports)) + it.args.singleOrNull()?.let { + val str = ((it.expr as Node.Expr.StringTmpl).elems.single() as Node.Expr.StringTmpl.Elem.Regular).str + builder.addMember("%S", str) + } + builder.build() + } + } From aec66a0649e958e0e84dd54fa010dccabb9a002f Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Mon, 5 Aug 2019 18:04:52 +0200 Subject: [PATCH 12/19] fixes for develop, JvmName --- apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt index a06edf50..b9817f58 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/KastreeExt.kt @@ -43,7 +43,7 @@ fun Node.Decl.Func.paramSpecs(imports: List) = this.params.map { p -> when { this.args.isEmpty() && this.expr.name().first().isLowerCase() -> CodeBlock.of("%M()", this.expr.name().member(imports)) this.args.isEmpty() -> CodeBlock.of("%T()", this.expr.name().className(imports)) - else -> throw IllegalStateException() + else -> throw IllegalStateException(this.toString()) } } else -> throw IllegalStateException() @@ -63,7 +63,7 @@ fun String.fullName(imports: List) = when (this) { "Class" -> "java.lang.$this" "List", "Map", "emptyList" -> "kotlin.collections.$this" "Long", "Int", "Short", "Byte", "String", "Boolean", "Unit", "Any", "Deprecated" -> "kotlin.$this" - "JvmOverloads" -> "kotlin.jvm.$this" + "JvmOverloads", "JvmName" -> "kotlin.jvm.$this" else -> imports.find { it.substringAfterLast(".") == this }?.substringAfter("import ") } ?: this From a532fbabbcacb11ba2217b49e51d361635a7d417 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Wed, 7 Aug 2019 14:45:09 +0200 Subject: [PATCH 13/19] added docs & jvmstatic to API entry class --- .../main/java/ch/decent/sdk/poet/Factory.kt | 19 +++++++++++++++++-- jitpack.yml | 6 ++++++ library/build.gradle.kts | 1 + library/jitpack.yml | 3 --- .../main/java/ch/decent/sdk/DCoreClient.kt | 2 +- 5 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 jitpack.yml delete mode 100644 library/jitpack.yml diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt index 28acf13b..bb33a66a 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt @@ -9,6 +9,17 @@ import com.squareup.kotlinpoet.asClassName object Factory { + private val docs = """ + Create Api. At least one of HTTP or WebSocket URLs must be set. + + @param client OkHttp client handling the requests + @param webSocketUrl URL for the webSocket requests, eg: wss://testnet-socket.dcore.io/ + @param httpUrl URL for the HTTP requests, eg: https://testnet.dcore.io/ + @param logger optional logger for requests + + @return DCore API for making requests + """.trimIndent() + private fun nullable(name: String, klass: ClassName) = ParameterSpec.builder(name, klass.copy(nullable = true)).defaultValue("null").build() @@ -21,12 +32,16 @@ object Factory { fun builder(methodName: String, pckg: String) = FunSpec.builder(methodName) .addParameters(params) - .addStatement("return %T(%T(%T(client, websocketUrl, httpUrl, logger)))", ClassName(pckg, apiRef.simpleName), apiRef, clientRef) + .addStatement("return %T(%T(%T(client, webSocketUrl, httpUrl, logger)))", ClassName(pckg, apiRef.simpleName), apiRef, clientRef) + .addAnnotation(JvmStatic::class) + .addKdoc(docs) .build() val rx = FunSpec.builder("createApiRx") .addParameters(params) - .addStatement("return %T(%T(client, websocketUrl, httpUrl, logger))", apiRef, clientRef) + .addStatement("return %T(%T(client, webSocketUrl, httpUrl, logger))", apiRef, clientRef) + .addAnnotation(JvmStatic::class) + .addKdoc(docs) .build() val file: FileSpec diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 00000000..21f68827 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,6 @@ + +jdk: +- oraclejdk8 + +install: + - ./gradlew clean -xtest run build publishToMavenLocal diff --git a/library/build.gradle.kts b/library/build.gradle.kts index 086f32a6..0190aee1 100644 --- a/library/build.gradle.kts +++ b/library/build.gradle.kts @@ -66,6 +66,7 @@ dockerCompose { val dokka by tasks.getting(DokkaTask::class) { outputFormat = "javadoc" outputDirectory = "$buildDir/javadoc" + reportUndocumented = false } val dokkaJar by tasks.creating(Jar::class) { diff --git a/library/jitpack.yml b/library/jitpack.yml deleted file mode 100644 index abf62560..00000000 --- a/library/jitpack.yml +++ /dev/null @@ -1,3 +0,0 @@ - -jdk: -- oraclejdk9 diff --git a/library/src/main/java/ch/decent/sdk/DCoreClient.kt b/library/src/main/java/ch/decent/sdk/DCoreClient.kt index da267f25..2e5d09d2 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreClient.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreClient.kt @@ -52,7 +52,7 @@ class DCoreClient internal constructor( internal val gson = gsonBuilder.create() private val rxWebSocket: RxWebSocket? = webSocketUrl?.let { RxWebSocket(client, it, gson, logger) } private val rpc: RpcService? = restUrl?.let { RpcService(it, client, gson) } - private val chainId = makeRequest(GetChainId).cache() + private val chainId by lazy { makeRequest(GetChainId).cache() } init { require(restUrl?.isNotBlank() == true || webSocketUrl?.isNotBlank() == true) { "at least one url must be set" } From 8cfd1864a4758e6c463cdcf3425085a081f08e5d Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Wed, 7 Aug 2019 15:00:42 +0200 Subject: [PATCH 14/19] generated param typo fix --- apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt b/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt index bb33a66a..d17a5730 100644 --- a/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt +++ b/apiGen/src/main/java/ch/decent/sdk/poet/Factory.kt @@ -25,7 +25,7 @@ object Factory { val params = listOf( ParameterSpec.builder("client", ClassName.bestGuess("okhttp3.OkHttpClient")).build(), - nullable("websocketUrl", String::class.asClassName()), + nullable("webSocketUrl", String::class.asClassName()), nullable("httpUrl", String::class.asClassName()), nullable("logger", ClassName.bestGuess("org.slf4j.Logger")) ) From b3787e6d6b87afd8386b2da5e5d709d012f99039 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Thu, 8 Aug 2019 09:04:55 +0200 Subject: [PATCH 15/19] add apiGen run as lib compile dependency --- .travis.yml | 2 +- jitpack.yml | 6 ------ library/build.gradle.kts | 4 ++++ 3 files changed, 5 insertions(+), 7 deletions(-) delete mode 100644 jitpack.yml diff --git a/.travis.yml b/.travis.yml index 2d6b0237..dbb8b375 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,7 +37,7 @@ before_script: # - docker-compose exec DCore id dcore script: - - ./gradlew run build test + - ./gradlew build test - ./gradlew jacocoTestReport - java -jar codacy-coverage-reporter-assembly.jar report -l Java -r library/build/reports/jacoco/test/jacocoTestReport.xml deploy: diff --git a/jitpack.yml b/jitpack.yml deleted file mode 100644 index 21f68827..00000000 --- a/jitpack.yml +++ /dev/null @@ -1,6 +0,0 @@ - -jdk: -- oraclejdk8 - -install: - - ./gradlew clean -xtest run build publishToMavenLocal diff --git a/library/build.gradle.kts b/library/build.gradle.kts index 0190aee1..49ca7a36 100644 --- a/library/build.gradle.kts +++ b/library/build.gradle.kts @@ -50,6 +50,10 @@ tasks { getByName("clean") { delete.add("gen") } + + getByName("compileKotlin") { + dependsOn.add(":apiGen:run") + } } detekt { From 2f35d07e45b17c172cf6d1acbdc114f1da2a7cc4 Mon Sep 17 00:00:00 2001 From: Marian Vanderka Date: Thu, 8 Aug 2019 09:19:26 +0200 Subject: [PATCH 16/19] supress magic number warn; --- library/src/main/java/ch/decent/sdk/DCoreConstants.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/library/src/main/java/ch/decent/sdk/DCoreConstants.kt b/library/src/main/java/ch/decent/sdk/DCoreConstants.kt index 6ca24209..23ee693c 100644 --- a/library/src/main/java/ch/decent/sdk/DCoreConstants.kt +++ b/library/src/main/java/ch/decent/sdk/DCoreConstants.kt @@ -14,6 +14,7 @@ object DCoreConstants { private const val DCT_PRECISION: Byte = 8 private const val DCT_SUPPLY = 7319777577456900 + @Suppress("MagicNumber") @JvmField val PROXY_TO_SELF = AccountObjectId(3) @JvmField val DCT_ASSET_ID = AssetObjectId() @JvmField val DCT = Asset( From 5495e702c498c1bdb0ec85dd3ba6c57d73492223 Mon Sep 17 00:00:00 2001 From: Peter Vanderka <45463125+petervanderkadecent@users.noreply.github.com> Date: Thu, 8 Aug 2019 11:42:55 +0200 Subject: [PATCH 17/19] Test new DCore error code handling (#93) --- .../src/test/java/ch/decent/sdk/Scratchpad.kt | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/library/src/test/java/ch/decent/sdk/Scratchpad.kt b/library/src/test/java/ch/decent/sdk/Scratchpad.kt index 883d66b2..36369d80 100644 --- a/library/src/test/java/ch/decent/sdk/Scratchpad.kt +++ b/library/src/test/java/ch/decent/sdk/Scratchpad.kt @@ -3,10 +3,8 @@ package ch.decent.sdk import ch.decent.sdk.crypto.Address import ch.decent.sdk.crypto.DumpedPrivateKey import ch.decent.sdk.crypto.ECKeyPair -import ch.decent.sdk.model.AssetAmount -import ch.decent.sdk.model.Fee -import ch.decent.sdk.model.Memo -import ch.decent.sdk.model.TransactionConfirmation +import ch.decent.sdk.exception.DCoreException +import ch.decent.sdk.model.* import ch.decent.sdk.model.operation.CustomOperation import ch.decent.sdk.model.operation.TransferOperation import ch.decent.sdk.utils.hash512 @@ -183,6 +181,16 @@ class Scratchpad { println(trx) } + @Test fun `new error codes`() { + val logger = LoggerFactory.getLogger("LOG") + val api = DCoreSdk.createForWebSocket(Helpers.client(logger), Helpers.wsUrl, logger) +// non existing account + val test = api.historyApi.findAllOperations("1.2.33333".toChainObject(), startOffset = 2, limit = 3).test() + test.awaitTerminalEvent() + test.assertError(DCoreException::class.java) + } + + /* @Test fun `transfers to various receivers`() { val api = DCoreSdk.createApiRx(client, url, logger = LoggerFactory.getLogger("DCoreApi")) val dpk = DumpedPrivateKey.fromBase58(private) From 4597c471a95f001d5af17c5e7b1c8da58f30e956 Mon Sep 17 00:00:00 2001 From: Peter Vanderka <45463125+petervanderkadecent@users.noreply.github.com> Date: Mon, 19 Aug 2019 13:42:48 +0200 Subject: [PATCH 18/19] kluent version to 1.49 (#98) * kluent version to 1.49 because its dependency is failing to resolve: Could not GET 'https://repo.maven.apache.org/maven2/net/bytebuddy/byte-buddy/1.6.14/byte-buddy-1.6.14.jar'. Received status code 403 from server: Forbidden * travis gradle cache --- .travis.yml | 9 +++++++++ buildSrc/src/main/java/Dependencies.kt | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index dbb8b375..e0a34489 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,15 @@ services: docker env: - DOCKER_COMPOSE_VERSION=1.23.2 +before_cache: + - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + +cache: + directories: + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ + before_install: - sudo rm /usr/local/bin/docker-compose - curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose diff --git a/buildSrc/src/main/java/Dependencies.kt b/buildSrc/src/main/java/Dependencies.kt index e5e883f9..b0f61efe 100644 --- a/buildSrc/src/main/java/Dependencies.kt +++ b/buildSrc/src/main/java/Dependencies.kt @@ -19,7 +19,7 @@ object Versions { val threeTen = "1.3.6" val slf4j = "1.7.25" val guava = "25.0-android" //jdk7 support - val kluent = "1.41" + val kluent = "1.49" val okio = "2.2.2" val bouncyProv = "1.59" From 66427b407ba1feff10594ac15a73f926866f466d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juraj=20=C5=A0korv=C3=A1nek?= Date: Mon, 19 Aug 2019 14:10:22 +0200 Subject: [PATCH 19/19] Added get message by id method (#96) --- .../java/ch/decent/sdk/api/rx/MessagingApi.kt | 46 ++++++++++++++----- .../sdk/net/model/request/GetMessages.kt | 15 ++++++ .../src/test/java/ch/decent/sdk/Helpers.kt | 3 ++ .../java/ch/decent/sdk/api/MessagingSuite.kt | 18 ++++++-- test-dcore-node/dockerfile | 2 +- 5 files changed, 67 insertions(+), 17 deletions(-) create mode 100644 library/src/main/java/ch/decent/sdk/net/model/request/GetMessages.kt diff --git a/library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt b/library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt index 0e66af60..4539fba8 100644 --- a/library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt +++ b/library/src/main/java/ch/decent/sdk/api/rx/MessagingApi.kt @@ -9,12 +9,14 @@ import ch.decent.sdk.model.Fee import ch.decent.sdk.model.Memo import ch.decent.sdk.model.Message import ch.decent.sdk.model.MessagePayload +import ch.decent.sdk.model.MessagingObjectId import ch.decent.sdk.model.MessagePayloadReceiver import ch.decent.sdk.model.MessageRequest import ch.decent.sdk.model.MessageResponse import ch.decent.sdk.model.TransactionConfirmation import ch.decent.sdk.model.operation.SendMessageOperation import ch.decent.sdk.net.model.request.GetMessageObjects +import ch.decent.sdk.net.model.request.GetMessages import ch.decent.sdk.utils.REQ_LIMIT_MAX_1K import io.reactivex.Single import io.reactivex.functions.BiFunction @@ -22,7 +24,7 @@ import io.reactivex.functions.BiFunction class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { /** - * Get all message operations + * Find all message operations * * @param sender filter by sender account id * @param receiver filter by receiver account id @@ -31,11 +33,11 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of message operation responses */ @JvmOverloads - fun getAllOperations(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = + fun findAllOperations(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = GetMessageObjects(sender, receiver, maxCount).toRequest() /** - * Get all messages + * Find all messages * * @param sender filter by sender account id * @param receiver filter by receiver account id @@ -44,12 +46,12 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAll(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = + fun findAll(sender: AccountObjectId? = null, receiver: AccountObjectId? = null, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = GetMessageObjects(sender, receiver, maxCount).toRequest() .map { it.map { Message.create(it) }.flatten() } /** - * Get all messages and decrypt + * Find all messages and decrypt * * @param credentials account credentials used for decryption, must be either sender's or receiver's * @param sender filter by sender account id @@ -59,7 +61,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAllDecrypted( + fun findAllDecrypted( credentials: Credentials, sender: AccountObjectId? = null, receiver: AccountObjectId? = null, @@ -73,7 +75,7 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { } /** - * Get all messages for sender and decrypt + * Find all messages for sender and decrypt * * @param credentials sender account credentials with decryption keys * @param maxCount max items to return @@ -81,11 +83,11 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAllDecryptedForSender(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = - getAllDecrypted(credentials, sender = credentials.account, maxCount = maxCount) + fun findAllDecryptedForSender(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = + findAllDecrypted(credentials, sender = credentials.account, maxCount = maxCount) /** - * Get all messages for receiver and decrypt + * Find all messages for receiver and decrypt * * @param credentials receiver account credentials with decryption keys * @param maxCount max items to return @@ -93,8 +95,8 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { * @return list of messages */ @JvmOverloads - fun getAllDecryptedForReceiver(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = - getAllDecrypted(credentials, receiver = credentials.account, maxCount = maxCount) + fun findAllDecryptedForReceiver(credentials: Credentials, maxCount: Int = REQ_LIMIT_MAX_1K): Single> = + findAllDecrypted(credentials, receiver = credentials.account, maxCount = maxCount) /** * Create message operation, send messages to multiple receivers @@ -172,4 +174,24 @@ class MessagingApi internal constructor(api: DCoreApi) : BaseApi(api) { ): Single = createMessageOperationUnencrypted(credentials, messages, fee).flatMap { api.broadcastApi.broadcastWithCallback(credentials.keyPair, it) } + + /** + * Get messages by ids + * + * @param ids a list of messages ids + * + * @return list of messages + */ + fun getAll(ids: List): Single> = + GetMessages(ids).toRequest() + .map { it.map { Message.create(it) }.flatten() } + + /** + * Get message by id + * + * @param id message id + * + * @return message + */ + fun get(id: MessagingObjectId): Single = getAll(listOf(id)).map { it.first() } } diff --git a/library/src/main/java/ch/decent/sdk/net/model/request/GetMessages.kt b/library/src/main/java/ch/decent/sdk/net/model/request/GetMessages.kt new file mode 100644 index 00000000..db936715 --- /dev/null +++ b/library/src/main/java/ch/decent/sdk/net/model/request/GetMessages.kt @@ -0,0 +1,15 @@ +package ch.decent.sdk.net.model.request + +import ch.decent.sdk.model.MessageResponse +import ch.decent.sdk.model.MessagingObjectId +import ch.decent.sdk.net.model.ApiGroup +import com.google.gson.reflect.TypeToken + +internal class GetMessages( + messages: List +) : BaseRequest>( + ApiGroup.MESSAGING, + "get_messages", + TypeToken.getParameterized(List::class.java, MessageResponse::class.java).type, + listOf(messages) +) diff --git a/library/src/test/java/ch/decent/sdk/Helpers.kt b/library/src/test/java/ch/decent/sdk/Helpers.kt index ae24bae7..4fae5473 100644 --- a/library/src/test/java/ch/decent/sdk/Helpers.kt +++ b/library/src/test/java/ch/decent/sdk/Helpers.kt @@ -4,6 +4,7 @@ import ch.decent.sdk.crypto.Credentials import ch.decent.sdk.model.AccountObjectId import ch.decent.sdk.model.AssetObjectId import ch.decent.sdk.model.ContentObjectId +import ch.decent.sdk.model.MessagingObjectId import ch.decent.sdk.model.PurchaseObjectId import ch.decent.sdk.model.toObjectId import ch.decent.sdk.net.TrustAllCerts @@ -49,6 +50,8 @@ object Helpers { @JvmStatic val createContentId = "2.13.0".toObjectId() @JvmStatic val createContentId2 = "2.13.1".toObjectId() @JvmStatic val createPurchaseId = "2.12.0".toObjectId() + @JvmStatic val messageId1 = "2.18.0".toObjectId() + @JvmStatic val messageId2 = "2.18.1".toObjectId() @JvmStatic val createNft = "APPLE" @JvmStatic val createNftNested = "$createNft.NESTED" } diff --git a/library/src/test/java/ch/decent/sdk/api/MessagingSuite.kt b/library/src/test/java/ch/decent/sdk/api/MessagingSuite.kt index 422cb28b..f28609f8 100644 --- a/library/src/test/java/ch/decent/sdk/api/MessagingSuite.kt +++ b/library/src/test/java/ch/decent/sdk/api/MessagingSuite.kt @@ -34,11 +34,11 @@ class MessagingOperationsTest : BaseOperationsTest() { class MessagingApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get message operations for receiver`() { - api.messagingApi.getAllOperations(receiver = Helpers.account2).testCheck() + api.messagingApi.findAllOperations(receiver = Helpers.account2).testCheck() } @Test fun `should get messages for account and decrypt for receiver`() { - api.messagingApi.getAll(receiver = Helpers.account2).cache().testCheck { + api.messagingApi.findAll(receiver = Helpers.account2).cache().testCheck { assertComplete() assertNoErrors() @@ -61,7 +61,7 @@ class MessagingApiTest(channel: Channel) : BaseApiTest(channel) { @Test fun `should get decrypted messages for sender account`() { val credentials = Credentials(Helpers.account, Helpers.private) - api.messagingApi.getAllDecryptedForSender(credentials).testCheck { + api.messagingApi.findAllDecryptedForSender(credentials).testCheck { assertComplete() assertNoErrors() @@ -70,7 +70,7 @@ class MessagingApiTest(channel: Channel) : BaseApiTest(channel) { } @Test fun `should get fail decrypt messages for sender account with wrong credentials`() { - api.messagingApi.getAll(Helpers.account).testCheck { + api.messagingApi.findAll(Helpers.account).testCheck { assertComplete() assertNoErrors() @@ -81,4 +81,14 @@ class MessagingApiTest(channel: Channel) : BaseApiTest(channel) { .all { it.encrypted } `should equal` true } } + + @Test fun `should get messages by id`() { + api.messagingApi.getAll(listOf(Helpers.messageId1, Helpers.messageId2)) + .testCheck() + } + + @Test fun `should get message by id`() { + api.messagingApi.get(Helpers.messageId1) + .testCheck() + } } diff --git a/test-dcore-node/dockerfile b/test-dcore-node/dockerfile index e1f3c493..99bfe9cd 100644 --- a/test-dcore-node/dockerfile +++ b/test-dcore-node/dockerfile @@ -1,4 +1,4 @@ -FROM decentnetwork/dcore.ubuntu +FROM decentnetwork/dcore.ubuntu:dev COPY --chown=dcore:dcore ./datadir /home/dcore/.decent/data/decentd COPY --chown=dcore:dcore ./genesis-local.json /home/dcore/.decent/genesis.json