-
Notifications
You must be signed in to change notification settings - Fork 45
Add account awaiter #559
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add account awaiter #559
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import { assert } from "chai"; | ||
| import { Address } from "../address"; | ||
| import { MarkCompleted, MockNetworkProvider, Wait } from "../testutils/mockNetworkProvider"; | ||
| import { createAccountBalance } from "../testutils/utils"; | ||
| import { loadTestWallet } from "../testutils/wallets"; | ||
| import { Transaction } from "../transaction"; | ||
| import { TransactionComputer } from "../transactionComputer"; | ||
| import { AccountAwaiter } from "./accountAwaiter"; | ||
| import { AccountOnNetwork } from "./accounts"; | ||
| import { ApiNetworkProvider } from "./apiNetworkProvider"; | ||
|
|
||
| describe("AccountAwaiter Tests", () => { | ||
| const provider = new MockNetworkProvider(); | ||
|
|
||
| const watcher = new AccountAwaiter({ | ||
| fetcher: provider, | ||
| pollingIntervalInMilliseconds: 42, | ||
| timeoutIntervalInMilliseconds: 42 * 42, | ||
| patienceTimeInMilliseconds: 0, | ||
| }); | ||
|
|
||
| it("should await on balance increase", async () => { | ||
| const alice = Address.newFromBech32("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"); | ||
| // alice account is created with 1000 EGLD | ||
| const initialBalance = (await provider.getAccount(alice)).balance; | ||
|
|
||
| // Mock balance timeline | ||
| provider.mockAccountBalanceTimelineByAddress(alice, [ | ||
| new Wait(40), | ||
| new Wait(40), | ||
| new Wait(45), | ||
| new MarkCompleted(), | ||
| ]); | ||
|
|
||
| const condition = (account: AccountOnNetwork) => { | ||
| return account.balance === initialBalance + createAccountBalance(7); | ||
| }; | ||
|
|
||
| const account = await watcher.awaitOnCondition(alice, condition); | ||
|
|
||
| assert.equal(account.balance, createAccountBalance(1007)); | ||
| }); | ||
|
|
||
| it("should await for account balance increase on the network", async function () { | ||
| this.timeout(20000); | ||
| const alice = await loadTestWallet("alice"); | ||
| const aliceAddress = alice.getAddress(); | ||
| const frank = Address.newFromBech32("erd1kdl46yctawygtwg2k462307dmz2v55c605737dp3zkxh04sct7asqylhyv"); | ||
|
|
||
| const api = new ApiNetworkProvider("https://devnet-api.multiversx.com"); | ||
| const watcher = new AccountAwaiter({ fetcher: api }); | ||
| const txComputer = new TransactionComputer(); | ||
| const value = 100_000n; | ||
|
|
||
| // Create and sign the transaction | ||
| const transaction = new Transaction({ | ||
| sender: aliceAddress, | ||
| receiver: frank, | ||
| gasLimit: 50000n, | ||
| chainID: "D", | ||
| value, | ||
| }); | ||
| transaction.nonce = (await api.getAccount(aliceAddress)).nonce; | ||
| transaction.signature = await alice.signer.sign(txComputer.computeBytesForSigning(transaction)); | ||
|
|
||
| const initialBalance = (await api.getAccount(frank)).balance; | ||
|
|
||
| const condition = (account: AccountOnNetwork) => { | ||
| return account.balance === initialBalance + value; | ||
| }; | ||
|
|
||
| await api.sendTransaction(transaction); | ||
|
|
||
| const accountOnNetwork = await watcher.awaitOnCondition(frank, condition); | ||
|
|
||
| assert.equal(accountOnNetwork.balance, initialBalance + value); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import { Address } from "../address"; | ||
| import { ExpectedAccountConditionNotReachedError } from "../errors"; | ||
| import { AccountOnNetwork } from "./accounts"; | ||
| import { | ||
| DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS, | ||
| DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS, | ||
| DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS, | ||
| } from "./constants"; | ||
|
|
||
| interface IAccountFetcher { | ||
| getAccount(address: Address): Promise<AccountOnNetwork>; | ||
| } | ||
|
|
||
| export class AccountAwaiter { | ||
| private readonly fetcher: IAccountFetcher; | ||
| private readonly pollingIntervalInMilliseconds: number; | ||
| private readonly timeoutIntervalInMilliseconds: number; | ||
| private readonly patienceTimeInMilliseconds: number; | ||
|
|
||
| /** | ||
| * AccountAwaiter allows one to await until a specific event occurs on a given address. | ||
| * | ||
| * @param fetcher - Used to fetch the account of the network. | ||
| * @param pollingIntervalInMilliseconds - The polling interval, in milliseconds. | ||
| * @param timeoutIntervalInMilliseconds - The timeout, in milliseconds. | ||
| * @param patienceTimeInMilliseconds - The patience, an extra time (in milliseconds) to wait, after the account has reached its desired condition. | ||
| */ | ||
| constructor(options: { | ||
| fetcher: IAccountFetcher; | ||
| pollingIntervalInMilliseconds?: number; | ||
| timeoutIntervalInMilliseconds?: number; | ||
| patienceTimeInMilliseconds?: number; | ||
| }) { | ||
| this.fetcher = options.fetcher; | ||
|
|
||
| this.pollingIntervalInMilliseconds = | ||
| options.pollingIntervalInMilliseconds ?? DEFAULT_ACCOUNT_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS; | ||
|
|
||
| this.timeoutIntervalInMilliseconds = | ||
| options.timeoutIntervalInMilliseconds ?? DEFAULT_ACCOUNT_AWAITING_TIMEOUT_IN_MILLISECONDS; | ||
|
|
||
| this.patienceTimeInMilliseconds = | ||
| options.patienceTimeInMilliseconds ?? DEFAULT_ACCOUNT_AWAITING_PATIENCE_IN_MILLISECONDS; | ||
| } | ||
|
|
||
| /** | ||
| * Waits until the condition is satisfied. | ||
| * | ||
| * @param address - The address to monitor. | ||
| * @param condition - A callable that evaluates the desired condition. | ||
| */ | ||
| async awaitOnCondition( | ||
| address: Address, | ||
| condition: (account: AccountOnNetwork) => boolean, | ||
| ): Promise<AccountOnNetwork> { | ||
| const doFetch = async () => await this.fetcher.getAccount(address); | ||
|
|
||
| return this.awaitConditionally(condition, doFetch, new ExpectedAccountConditionNotReachedError()); | ||
| } | ||
|
|
||
| private async awaitConditionally( | ||
| isSatisfied: (account: AccountOnNetwork) => boolean, | ||
| doFetch: () => Promise<AccountOnNetwork>, | ||
| error: Error, | ||
| ): Promise<AccountOnNetwork> { | ||
| let isConditionSatisfied = false; | ||
| let fetchedData: AccountOnNetwork | null = null; | ||
|
|
||
| const maxNumberOfRetries = Math.floor(this.timeoutIntervalInMilliseconds / this.pollingIntervalInMilliseconds); | ||
|
|
||
| let numberOfRetries = 0; | ||
|
|
||
| while (numberOfRetries < maxNumberOfRetries) { | ||
| try { | ||
| fetchedData = await doFetch(); | ||
| isConditionSatisfied = isSatisfied(fetchedData); | ||
|
|
||
| if (isConditionSatisfied) { | ||
| break; | ||
| } | ||
| } catch (ex) { | ||
| throw ex; | ||
| } | ||
|
|
||
| numberOfRetries += 1; | ||
| await this._sleep(this.pollingIntervalInMilliseconds); | ||
| } | ||
|
|
||
| if (!fetchedData || !isConditionSatisfied) { | ||
| throw error; | ||
| } | ||
|
|
||
| if (this.patienceTimeInMilliseconds) { | ||
| await this._sleep(this.patienceTimeInMilliseconds); | ||
| return doFetch(); | ||
| } | ||
|
|
||
| return fetchedData; | ||
| } | ||
|
|
||
| private async _sleep(milliseconds: number): Promise<void> { | ||
| return new Promise((resolve) => setTimeout(resolve, milliseconds)); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this what we want?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is what we are doing on the transaction watcher also..
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All right then for now. We should check if that's the best approach - for both of them (separately, another task / PR).