-
- All Implemented Interfaces:
-
cash.z.ecc.android.sdk.CloseableSynchronizer,cash.z.ecc.android.sdk.Synchronizer,java.io.Closeable,java.lang.AutoCloseable
public final class SdkSynchronizer implements CloseableSynchronizer
A Synchronizer that attempts to remain operational, despite any number of errors that can occur. It acts as the glue that ties all the pieces of the SDK together. Each component of the SDK is designed for the potential of stand-alone usage but coordinating all the interactions is non- trivial. So the Synchronizer facilitates this, acting as reference that demonstrates how all the pieces can be tied together. Its goal is to allow a developer to focus on their app rather than the nuances of how Zcash works.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public classSdkSynchronizer.Companion
-
Field Summary
Fields Modifier and Type Field Description private final CoroutineScopecoroutineScopeprivate final <ERROR CLASS>orchardBalancesprivate final <ERROR CLASS>saplingBalancesprivate final <ERROR CLASS>transparentBalanceprivate final <ERROR CLASS>exchangeRateUsdprivate final <ERROR CLASS>transactionsprivate final ZcashNetworknetworkprivate final <ERROR CLASS>statusprivate final Flow<PercentDecimal>progressprivate final Flow<CompactBlockProcessor.ProcessorInfo>processorInfoprivate final StateFlow<BlockHeight>networkHeightprivate Function1<Throwable, Boolean>onCriticalErrorHandlerprivate Function1<Throwable, Boolean>onProcessorErrorHandlerprivate Function1<Throwable, Boolean>onSubmissionErrorHandlerprivate Function1<Throwable, Boolean>onSetupErrorHandlerprivate Function2<BlockHeight, BlockHeight, Object>onChainErrorHandlerprivate final <ERROR CLASS>latestHeightprivate final <ERROR CLASS>latestBirthdayHeightprivate final CompactBlockProcessorprocessor
-
Method Summary
Modifier and Type Method Description final CoroutineScopegetCoroutineScope()<ERROR CLASS>getOrchardBalances()A stream of balance values for the orchard pool. <ERROR CLASS>getSaplingBalances()A stream of balance values for the sapling pool. <ERROR CLASS>getTransparentBalance()A stream of a balance for the transparent pool. <ERROR CLASS>getExchangeRateUsd()The latest known USD/ZEC exchange rate, paired with the time it was queried. <ERROR CLASS>getTransactions()ZcashNetworkgetNetwork()<ERROR CLASS>getStatus()Indicates the status of this Synchronizer. Flow<PercentDecimal>getProgress()Indicates the download progress of the Synchronizer. Flow<CompactBlockProcessor.ProcessorInfo>getProcessorInfo()Indicates the latest information about the blocks that have been processed by the SDK. StateFlow<BlockHeight>getNetworkHeight()The latest height seen on the network while processing blocks. Function1<Throwable, Boolean>getOnCriticalErrorHandler()A callback to invoke whenever an uncaught error is encountered. UnitsetOnCriticalErrorHandler(Function1<Throwable, Boolean> onCriticalErrorHandler)A callback to invoke whenever an uncaught error is encountered. Function1<Throwable, Boolean>getOnProcessorErrorHandler()A callback to invoke whenever a processor error is encountered. UnitsetOnProcessorErrorHandler(Function1<Throwable, Boolean> onProcessorErrorHandler)A callback to invoke whenever a processor error is encountered. Function1<Throwable, Boolean>getOnSubmissionErrorHandler()A callback to invoke whenever a server error is encountered while submitting a transaction to lightwalletd. UnitsetOnSubmissionErrorHandler(Function1<Throwable, Boolean> onSubmissionErrorHandler)A callback to invoke whenever a server error is encountered while submitting a transaction to lightwalletd. Function1<Throwable, Boolean>getOnSetupErrorHandler()A callback to invoke whenever a processor is not setup correctly. UnitsetOnSetupErrorHandler(Function1<Throwable, Boolean> onSetupErrorHandler)A callback to invoke whenever a processor is not setup correctly. Function2<BlockHeight, BlockHeight, Object>getOnChainErrorHandler()A callback to invoke whenever a chain error is encountered. UnitsetOnChainErrorHandler(Function2<BlockHeight, BlockHeight, Object> onChainErrorHandler)A callback to invoke whenever a chain error is encountered. <ERROR CLASS>getLatestHeight()<ERROR CLASS>getLatestBirthdayHeight()final CompactBlockProcessorgetProcessor()Flow<FastestServersResult>getFastestServers(Context context, List<LightWalletEndpoint> servers)Measure connection quality and speed of given servers. Unitclose()final Flow<Unit>closeFlow()A Flow-providing version of close function. BlockHeightgetNearestRewindHeight(BlockHeight height)Returns the safest height to which we can rewind, given a desire to rewind to the height provided. UnitrewindToNearestHeight(BlockHeight height)Rewinds to the safest height to which we can rewind, given a desire to rewind to the height provided. UnitquickRewind()Rewinds to the safest height approximately 14 days backward from the current chain tip. Flow<String>getMemos(TransactionOverview transactionOverview)Returns a stream of memos for a transaction. Flow<TransactionRecipient>getRecipients(TransactionOverview transactionOverview)Returns a list of recipients for a transaction. final IntegergetTransactionCount()final UnitrefreshTransactions()final UnitrefreshAllBalances()Calculate the latest balance based on the blocks that have been scanned and transmit this information into the transparentBalance, saplingBalances, and orchardBalances flows. UnitrefreshExchangeRateUsd()Refreshes exchangeRateUsd. final BooleanisValidAddress(String address)StringgetUnifiedAddress(Account account)Returns the current Unified Address for this account. StringgetSaplingAddress(Account account)Returns the legacy Sapling address corresponding to the current Unified Address for this account. StringgetTransparentAddress(Account account)Returns the legacy transparent address corresponding to the current Unified Address for this account. ProposalproposeTransfer(Account account, String recipient, Zatoshi amount, String memo)Creates a proposal for transferring funds to the given recipient. ProposalproposeShielding(Account account, Zatoshi shieldingThreshold, String memo, String transparentReceiver)Creates a proposal for shielding any transparent funds received by the given account. Flow<TransactionSubmitResult>createProposedTransactions(Proposal proposal, UnifiedSpendingKey usk)Creates the transactions in the given proposal. LongsendToAddress(UnifiedSpendingKey usk, Zatoshi amount, String toAddress, String memo)Sends zatoshi. LongshieldFunds(UnifiedSpendingKey usk, String memo)IntegerrefreshUtxos(Account account, BlockHeight since)Download all UTXOs for the given account addresses and store any new ones in the database. ZatoshigetTransparentBalance(String tAddr)Returns the balance that the wallet knows about. BooleanisValidShieldedAddr(String address)Returns true when the given address is a valid z-addr. BooleanisValidTransparentAddr(String address)Returns true when the given address is a valid t-addr. BooleanisValidUnifiedAddr(String address)Returns true when the given address is a valid ZIP 316 unified address. BooleanisValidTexAddr(String address)Returns true when the given address is a valid ZIP 320 TEX address. AddressTypevalidateAddress(String address)Validates the given address, returning information about why it is invalid. ConsensusMatchTypevalidateConsensusBranch()Validate whether the server and this SDK share the same consensus branch. ServerValidationvalidateServerEndpoint(Context context, LightWalletEndpoint endpoint)This function checks whether the provided server endpoint is valid. StringgetExistingDataDbFilePath(Context context, ZcashNetwork network, String alias)Checks and provides file path to the existing data database file for the given input parameters or throws InitializeException.MissingDatabaseException if the database does not exist yet. -
-
Method Detail
-
getCoroutineScope
final CoroutineScope getCoroutineScope()
-
getOrchardBalances
<ERROR CLASS> getOrchardBalances()
A stream of balance values for the orchard pool.
-
getSaplingBalances
<ERROR CLASS> getSaplingBalances()
A stream of balance values for the sapling pool.
-
getTransparentBalance
<ERROR CLASS> getTransparentBalance()
A stream of a balance for the transparent pool.
-
getExchangeRateUsd
<ERROR CLASS> getExchangeRateUsd()
The latest known USD/ZEC exchange rate, paired with the time it was queried.
The rate can be initialized and refreshed by calling refreshExchangeRateUsd.
-
getTransactions
<ERROR CLASS> getTransactions()
-
getNetwork
ZcashNetwork getNetwork()
-
getStatus
<ERROR CLASS> getStatus()
Indicates the status of this Synchronizer. This implementation basically simplifies the status of the processor to focus only on the high level states that matter most. Whenever the processor is finished scanning, the synchronizer updates transaction and balance info and then emits a SYNCED status.
-
getProgress
Flow<PercentDecimal> getProgress()
Indicates the download progress of the Synchronizer. When progress reaches
PercentDecimal.ONE_HUNDRED_PERCENT, that signals that the Synchronizer is in sync with the network. Balances should be considered inaccurate and outbound transactions should be prevented until this sync is complete. It is a simplified version of processorInfo.
-
getProcessorInfo
Flow<CompactBlockProcessor.ProcessorInfo> getProcessorInfo()
Indicates the latest information about the blocks that have been processed by the SDK. This is very helpful for conveying detailed progress and status to the user.
-
getNetworkHeight
StateFlow<BlockHeight> getNetworkHeight()
The latest height seen on the network while processing blocks. This may differ from the latest height scanned and is useful for determining block confirmations and expiration.
-
getOnCriticalErrorHandler
Function1<Throwable, Boolean> getOnCriticalErrorHandler()
A callback to invoke whenever an uncaught error is encountered. By definition, the return value of the function is ignored because this error is unrecoverable. The only reason the function has a return value is so that all error handlers work with the same signature which allows one function to handle all errors in simple apps. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
setOnCriticalErrorHandler
Unit setOnCriticalErrorHandler(Function1<Throwable, Boolean> onCriticalErrorHandler)
A callback to invoke whenever an uncaught error is encountered. By definition, the return value of the function is ignored because this error is unrecoverable. The only reason the function has a return value is so that all error handlers work with the same signature which allows one function to handle all errors in simple apps. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
getOnProcessorErrorHandler
Function1<Throwable, Boolean> getOnProcessorErrorHandler()
A callback to invoke whenever a processor error is encountered. Returning true signals that the error was handled and a retry attempt should be made, if possible. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
setOnProcessorErrorHandler
Unit setOnProcessorErrorHandler(Function1<Throwable, Boolean> onProcessorErrorHandler)
A callback to invoke whenever a processor error is encountered. Returning true signals that the error was handled and a retry attempt should be made, if possible. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
getOnSubmissionErrorHandler
Function1<Throwable, Boolean> getOnSubmissionErrorHandler()
A callback to invoke whenever a server error is encountered while submitting a transaction to lightwalletd. Returning true signals that the error was handled and a retry attempt should be made, if possible. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
setOnSubmissionErrorHandler
Unit setOnSubmissionErrorHandler(Function1<Throwable, Boolean> onSubmissionErrorHandler)
A callback to invoke whenever a server error is encountered while submitting a transaction to lightwalletd. Returning true signals that the error was handled and a retry attempt should be made, if possible. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
getOnSetupErrorHandler
Function1<Throwable, Boolean> getOnSetupErrorHandler()
A callback to invoke whenever a processor is not setup correctly. Returning true signals that the invalid setup should be ignored. If no handler is set, then any setup error will result in a critical error. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
setOnSetupErrorHandler
Unit setOnSetupErrorHandler(Function1<Throwable, Boolean> onSetupErrorHandler)
A callback to invoke whenever a processor is not setup correctly. Returning true signals that the invalid setup should be ignored. If no handler is set, then any setup error will result in a critical error. This callback is not called on the main thread so any UI work would need to switch context to the main thread.
-
getOnChainErrorHandler
Function2<BlockHeight, BlockHeight, Object> getOnChainErrorHandler()
A callback to invoke whenever a chain error is encountered. These occur whenever the processor detects a missing or non-chain-sequential block (i.e. a reorg).
-
setOnChainErrorHandler
Unit setOnChainErrorHandler(Function2<BlockHeight, BlockHeight, Object> onChainErrorHandler)
A callback to invoke whenever a chain error is encountered. These occur whenever the processor detects a missing or non-chain-sequential block (i.e. a reorg).
-
getLatestHeight
<ERROR CLASS> getLatestHeight()
-
getLatestBirthdayHeight
<ERROR CLASS> getLatestBirthdayHeight()
-
getProcessor
final CompactBlockProcessor getProcessor()
-
getFastestServers
Flow<FastestServersResult> getFastestServers(Context context, List<LightWalletEndpoint> servers)
Measure connection quality and speed of given servers.
-
closeFlow
final Flow<Unit> closeFlow()
A Flow-providing version of close function. This safely closes the Synchronizer together with the related components.
-
getNearestRewindHeight
BlockHeight getNearestRewindHeight(BlockHeight height)
Returns the safest height to which we can rewind, given a desire to rewind to the height provided. Due to how witness incrementing works, a wallet cannot simply rewind to any arbitrary height. This handles all that complexity yet remains flexible in the future as improvements are made.
-
rewindToNearestHeight
Unit rewindToNearestHeight(BlockHeight height)
Rewinds to the safest height to which we can rewind, given a desire to rewind to the height provided. Due to how witness incrementing works, a wallet cannot simply rewind to any arbitrary height. This handles all that complexity yet remains flexible in the future as improvements are made.
-
quickRewind
Unit quickRewind()
Rewinds to the safest height approximately 14 days backward from the current chain tip. Due to how witness incrementing works, a wallet cannot simply rewind to any arbitrary height. This handles all that complexity yet remains flexible in the future as improvements are made.
-
getMemos
Flow<String> getMemos(TransactionOverview transactionOverview)
Returns a stream of memos for a transaction. It works for both received and sent transaction.
Note that this function internally resolves any error which comes, logs it, and then transforms it to an empty string.
- Parameters:
transactionOverview- For which the memos will be queried
-
getRecipients
Flow<TransactionRecipient> getRecipients(TransactionOverview transactionOverview)
Returns a list of recipients for a transaction.
-
getTransactionCount
final Integer getTransactionCount()
-
refreshTransactions
final Unit refreshTransactions()
-
refreshAllBalances
final Unit refreshAllBalances()
Calculate the latest balance based on the blocks that have been scanned and transmit this information into the transparentBalance, saplingBalances, and orchardBalances flows.
-
refreshExchangeRateUsd
Unit refreshExchangeRateUsd()
Refreshes exchangeRateUsd.
-
isValidAddress
final Boolean isValidAddress(String address)
-
getUnifiedAddress
String getUnifiedAddress(Account account)
Returns the current Unified Address for this account.
-
getSaplingAddress
String getSaplingAddress(Account account)
Returns the legacy Sapling address corresponding to the current Unified Address for this account.
- Parameters:
account- the account whose address is of interest.
-
getTransparentAddress
String getTransparentAddress(Account account)
Returns the legacy transparent address corresponding to the current Unified Address for this account.
- Parameters:
account- the account whose address is of interest.
-
proposeTransfer
Proposal proposeTransfer(Account account, String recipient, Zatoshi amount, String memo)
Creates a proposal for transferring funds to the given recipient.
- Parameters:
account- the account from which to transfer funds.recipient- the recipient's address.amount- the amount of zatoshi to send.memo- the optional memo to include as part of the proposal's transactions.
-
proposeShielding
Proposal proposeShielding(Account account, Zatoshi shieldingThreshold, String memo, String transparentReceiver)
Creates a proposal for shielding any transparent funds received by the given account.
- Parameters:
account- the account for which to shield funds.shieldingThreshold- the minimum transparent balance required before a proposal will be created.memo- the optional memo to include as part of the proposal's transactions.transparentReceiver- a specific transparent receiver within the account that should be the source of transparent funds.
-
createProposedTransactions
Flow<TransactionSubmitResult> createProposedTransactions(Proposal proposal, UnifiedSpendingKey usk)
Creates the transactions in the given proposal.
- Parameters:
proposal- the proposal for which to create transactions.usk- the unified spending key associated with the account for which the proposal was created.
-
sendToAddress
@Deprecated(message = Upcoming SDK 2.1 will create multiple transactions at once for some recipients., replaceWith = @ReplaceWith(imports = {}, expression = createProposedTransactions(proposeTransfer(usk.account, toAddress, amount, memo), usk))) Long sendToAddress(UnifiedSpendingKey usk, Zatoshi amount, String toAddress, String memo)
Sends zatoshi.
- Parameters:
usk- the unified spending key associated with the notes that will be spent.amount- the amount of zatoshi to send.toAddress- the recipient's address.memo- the optional memo to include as part of the transaction.
-
shieldFunds
@Deprecated(message = Upcoming SDK 2.1 will create multiple transactions at once for some recipients., replaceWith = @ReplaceWith(imports = {}, expression = proposeShielding(usk.account, shieldingThreshold, memo)?.let { createProposedTransactions(it, usk) })) Long shieldFunds(UnifiedSpendingKey usk, String memo)
-
refreshUtxos
Integer refreshUtxos(Account account, BlockHeight since)
Download all UTXOs for the given account addresses and store any new ones in the database.
- Parameters:
account- The Account, for which all addresses blocks will be downloaded.since- The BlockHeight, from which blocks will be downloaded.
-
getTransparentBalance
Zatoshi getTransparentBalance(String tAddr)
Returns the balance that the wallet knows about. This should be called after refreshUtxos.
-
isValidShieldedAddr
Boolean isValidShieldedAddr(String address)
Returns true when the given address is a valid z-addr. Invalid addresses will throw an exception. See valid z-addresses characteristics in related ZIP.
- Parameters:
address- the address to validate.
-
isValidTransparentAddr
Boolean isValidTransparentAddr(String address)
Returns true when the given address is a valid t-addr. Invalid addresses will throw an exception. See valid t-addresses characteristics in related ZIP.
- Parameters:
address- the address to validate.
-
isValidUnifiedAddr
Boolean isValidUnifiedAddr(String address)
Returns true when the given address is a valid ZIP 316 unified address.
This method is intended for type checking (e.g. form validation). Invalid addresses will throw an exception.
- Parameters:
address- the address to validate.
-
isValidTexAddr
Boolean isValidTexAddr(String address)
Returns true when the given address is a valid ZIP 320 TEX address.
This method is intended for type checking (e.g. form validation). Invalid addresses will throw an exception. See valid t-addresses characteristics in the related ZIP.
- Parameters:
address- the address to validate.
-
validateAddress
AddressType validateAddress(String address)
Validates the given address, returning information about why it is invalid. This is a convenience method that combines the behavior of isValidShieldedAddr, isValidTransparentAddr, and isValidUnifiedAddr into one call so that the developer doesn't have to worry about handling the exceptions that they throw. Rather, exceptions are converted to AddressType.Invalid which has a
reasonproperty describing why it is invalid.- Parameters:
address- the address to validate.
-
validateConsensusBranch
ConsensusMatchType validateConsensusBranch()
Validate whether the server and this SDK share the same consensus branch. This is particularly important to check around network updates so that any wallet that's connected to an incompatible server can surface that information effectively. For the SDK, the consensus branch is used when creating transactions as each one needs to target a specific branch. This function compares the server's branch id to this SDK's and returns information that helps determine whether they match.
-
validateServerEndpoint
ServerValidation validateServerEndpoint(Context context, LightWalletEndpoint endpoint)
This function checks whether the provided server endpoint is valid. The validation is based on comparing:
network types,
sapling activation heights
consensus branches
- Parameters:
context- Contextendpoint- LightWalletEndpoint data to be validated
-
getExistingDataDbFilePath
String getExistingDataDbFilePath(Context context, ZcashNetwork network, String alias)
Checks and provides file path to the existing data database file for the given input parameters or throws InitializeException.MissingDatabaseException if the database does not exist yet.
Note that it's the caller's responsibility to provide a network and alias to an existing database. Otherwise InitializeException.MissingDatabaseException is thrown.
-
-
-
-