Skip to content

Commit

Permalink
feat: calculate default polling intervals depending on node settings
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk committed Jan 24, 2022
1 parent bb6ccc1 commit d9c6cf9
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 39 deletions.
8 changes: 6 additions & 2 deletions src/ae/oracle.js
Expand Up @@ -68,7 +68,11 @@ async function getOracleObject (oracleId) {
* @param {Number} [options.interval] Poll interval(default: 5000)
* @return {Function} stopPolling - Stop polling function
*/
function pollForQueries (oracleId, onQuery, { interval = 5000 } = {}) {
function pollForQueries (
oracleId,
onQuery,
{ interval = this._getPollInterval('microblock') } = {}
) {
const knownQueryIds = new Set()
const checkNewQueries = async () => {
const queries = ((await this.api.getOracleQueriesByPubkey(oracleId)).oracleQueries || [])
Expand Down Expand Up @@ -120,7 +124,7 @@ async function getQueryObject (oracleId, queryId) {
export async function pollForQueryResponse (
oracleId,
queryId,
{ attempts = 20, interval = 5000 } = {}
{ attempts = 20, interval = this._getPollInterval('microblock') } = {}
) {
for (let i = 0; i < attempts; i++) {
if (i) await pause(interval)
Expand Down
22 changes: 21 additions & 1 deletion src/chain/index.js
Expand Up @@ -37,7 +37,27 @@ import { required } from '@stamp/required'
* @return {Object} Chain instance
*/
const Chain = stampit({
deepProps: { Ae: { defaults: { waitMined: true, verify: true } } }
deepProps: {
Ae: {
defaults: {
waitMined: true,
verify: true,
_expectedMineRate: 180000,
_microBlockCycle: 3000,
_maxPollInterval: 5000
}
}
},
methods: {
_getPollInterval (type) {
const base = {
block: this.Ae.defaults._expectedMineRate,
microblock: this.Ae.defaults._microBlockCycle
}[type]
if (!base) throw new Error(`Unknown poll type: ${type}`)
return Math.min(base / 3, this.Ae.defaults._maxPollInterval)
}
}
}, required({
methods: {
sendTransaction: required,
Expand Down
10 changes: 8 additions & 2 deletions src/chain/node.js
Expand Up @@ -135,7 +135,10 @@ async function height () {
}
}

async function awaitHeight (height, { interval = 5000, attempts = 20 } = {}) {
async function awaitHeight (
height,
{ interval = this._getPollInterval('block'), attempts = 20 } = {}
) {
let currentHeight
for (let i = 0; i < attempts; i++) {
if (i) await pause(interval)
Expand All @@ -152,7 +155,10 @@ async function topBlock () {
return this.api.getTopHeader()
}

async function poll (th, { blocks = 10, interval = 500, allowUnsynced = false } = {}) {
async function poll (
th,
{ blocks = 10, interval = this._getPollInterval('microblock'), allowUnsynced = false } = {}
) {
const max = await this.height() + blocks
do {
const tx = await this.tx(th).catch(_ => null)
Expand Down
4 changes: 2 additions & 2 deletions test/integration/accounts.js
Expand Up @@ -141,9 +141,9 @@ describe('Accounts', function () {

it('Get Account by block height/hash', async () => {
const h = await sdk.height()
await sdk.awaitHeight(h + 3, { interval: 200, attempts: 100 })
await sdk.awaitHeight(h + 3)
const spend = await sdk.spend(123, 'ak_DMNCzsVoZnpV5fe8FTQnNsTfQ48YM5C3WbHPsJyHjAuTXebFi')
await sdk.awaitHeight(spend.blockHeight + 2, { interval: 200, attempts: 100 })
await sdk.awaitHeight(spend.blockHeight + 2)
const accountAfterSpend = await sdk.getAccount(await sdk.address())
const accountBeforeSpendByHash = await sdk.getAccount(
await sdk.address(), { height: spend.blockHeight - 1 }
Expand Down
15 changes: 5 additions & 10 deletions test/integration/chain.js
Expand Up @@ -56,8 +56,7 @@ describe('Node Chain', function () {

it('waits for specified heights', async () => {
const target = await sdk.height() + 1
await sdk.awaitHeight(target, { interval: 200, attempts: 100 })
.should.eventually.be.at.least(target)
await sdk.awaitHeight(target).should.eventually.be.at.least(target)
return sdk.height().should.eventually.be.at.least(target)
})
it('Can verify transaction from broadcast error', async () => {
Expand Down Expand Up @@ -107,21 +106,17 @@ describe('Node Chain', function () {
const signed = await sdkAccount.signTransaction(tx)
const { txHash } = await sdkAccount.api.postTransaction({ tx: signed })

await sdkAccount.poll(txHash, { interval: 50, attempts: 1200 }).should.eventually.be.fulfilled
return sdkAccount.poll('th_xxx', { blocks: 1, interval: 50, attempts: 1200 }).should.eventually.be.rejected
await sdkAccount.poll(txHash).should.eventually.be.fulfilled
return sdkAccount.poll('th_xxx', { blocks: 1 }).should.eventually.be.rejected
})

it('Wait for transaction confirmation', async () => {
const txData = await sdkAccount.spend(
1000, await sdkAccount.address(), { confirm: true, interval: 400, attempts: 50 }
)
const txData = await sdkAccount.spend(1000, await sdkAccount.address(), { confirm: true })
const isConfirmed = (await sdkAccount.height()) >= txData.blockHeight + 3

isConfirmed.should.be.equal(true)

const txData2 = await sdkAccount.spend(
1000, await sdkAccount.address(), { confirm: 4, interval: 400, attempts: 50 }
)
const txData2 = await sdkAccount.spend(1000, await sdkAccount.address(), { confirm: 4 })
const isConfirmed2 = (await sdkAccount.height()) >= txData2.blockHeight + 4
isConfirmed2.should.be.equal(true)
})
Expand Down
17 changes: 5 additions & 12 deletions test/integration/channel.js
Expand Up @@ -741,7 +741,7 @@ describe('Channel', function () {
const closeSoloTxFee = unpackTx(closeSoloTx).tx.fee
await initiator.sendTransaction(
await initiator.signTransaction(closeSoloTx),
{ waitMined: true, interval: 400, attempts: 10 }
{ waitMined: true }
)
const settleTx = await initiator.channelSettleTx({
channelId: await initiatorCh.id(),
Expand All @@ -750,10 +750,7 @@ describe('Channel', function () {
responderAmountFinal: balances[responderAddr]
})
const settleTxFee = unpackTx(settleTx).tx.fee
await initiator.sendTransaction(
await initiator.signTransaction(settleTx),
{ waitMined: true, interval: 400, attempts: 10 }
)
await initiator.sendTransaction(await initiator.signTransaction(settleTx), { waitMined: true })
const initiatorBalanceAfterClose = await initiator.balance(initiatorAddr)
const responderBalanceAfterClose = await responder.balance(responderAddr)
new BigNumber(initiatorBalanceAfterClose)
Expand Down Expand Up @@ -811,7 +808,7 @@ describe('Channel', function () {
})
const closeSoloTxFee = unpackTx(closeSoloTx).tx.fee
await initiator.sendTransaction(
await initiator.signTransaction(closeSoloTx), { waitMined: true, interval: 400, attempts: 10 }
await initiator.signTransaction(closeSoloTx), { waitMined: true }
)
const slashTx = await responder.channelSlashTx({
channelId: responderCh.id(),
Expand All @@ -820,19 +817,15 @@ describe('Channel', function () {
payload: recentUpdate.signedTx
})
const slashTxFee = unpackTx(slashTx).tx.fee
await responder.sendTransaction(
await responder.signTransaction(slashTx), { waitMined: true, interval: 400, attempts: 10 }
)
await responder.sendTransaction(await responder.signTransaction(slashTx), { waitMined: true })
const settleTx = await responder.channelSettleTx({
channelId: responderCh.id(),
fromId: responderAddr,
initiatorAmountFinal: recentBalances[initiatorAddr],
responderAmountFinal: recentBalances[responderAddr]
})
const settleTxFee = unpackTx(settleTx).tx.fee
await responder.sendTransaction(
await responder.signTransaction(settleTx), { waitMined: true, interval: 400, attempts: 10 }
)
await responder.sendTransaction(await responder.signTransaction(settleTx), { waitMined: true })
const initiatorBalanceAfterClose = await initiator.balance(initiatorAddr)
const responderBalanceAfterClose = await responder.balance(responderAddr)
new BigNumber(initiatorBalanceAfterClose)
Expand Down
4 changes: 2 additions & 2 deletions test/integration/contract-aci.js
Expand Up @@ -247,12 +247,12 @@ describe('Contract instance', function () {
it('deploys and calls contract without waiting for mining', async () => {
testContract.deployInfo = {}
const deployed = await testContract.methods.init('test', 1, 'hahahaha', { waitMined: false })
await sdk.poll(deployed.transaction, { interval: 50, attempts: 1200 })
await sdk.poll(deployed.transaction)
expect(deployed.result).to.be.equal(undefined)
const result = await testContract.methods.intFn.send(2, { waitMined: false })
expect(result.result).to.be.equal(undefined)
expect(result.txData).to.not.be.equal(undefined)
await sdk.poll(result.hash, { interval: 50, attempts: 1200 })
await sdk.poll(result.hash)
})

it('fails on paying to not payable function', async () => {
Expand Down
6 changes: 3 additions & 3 deletions test/integration/contract.js
Expand Up @@ -224,13 +224,13 @@ describe('Contract', function () {

it('call contract/deploy with waitMined: false', async () => {
const deployed = await bytecode.deploy([], { waitMined: false })
await sdk.poll(deployed.transaction, { interval: 50, attempts: 1200 })
await sdk.poll(deployed.transaction)
expect(deployed.result).to.be.equal(undefined)
deployed.txData.should.not.be.equal(undefined)
const result = await deployed.call('getArg', [42], { waitMined: false })
expect(result.result).to.be.equal(undefined)
result.txData.should.not.be.equal(undefined)
await sdk.poll(result.hash, { interval: 50, attempts: 1200 })
await sdk.poll(result.hash)
})

it('calls deployed contracts static', async () => {
Expand Down Expand Up @@ -402,7 +402,7 @@ describe('Contract', function () {
const preclaim = await contract.methods
.signedPreclaim(owner, commitmentIdDecoded, preclaimSig)
preclaim.result.returnType.should.be.equal('ok')
await sdk.awaitHeight((await sdk.height()) + 2, { interval: 200, attempts: 100 })
await sdk.awaitHeight((await sdk.height()) + 2)
// signature for any other name related operations
delegationSignature = await sdk.createAensDelegationSignature(
{ contractId, name }, { onAccount: owner }
Expand Down
11 changes: 9 additions & 2 deletions test/integration/index.js
Expand Up @@ -34,7 +34,14 @@ export const account = Crypto.generateKeyPair()

export const BaseAe = async (params = {}, compose = {}) => Universal
.compose({
deepProps: { Ae: { defaults: { interval: 50, attempts: 1200 } } }
deepProps: {
Ae: {
defaults: {
_expectedMineRate: 1000,
_microBlockCycle: 20
}
}
}
})
.compose(compose)({
...params,
Expand All @@ -49,7 +56,7 @@ export const BaseAe = async (params = {}, compose = {}) => Universal

const spendPromise = (async () => {
const ae = await BaseAe({ networkId, withoutGenesisAccount: false })
await ae.awaitHeight(2, { interval: 200, attempts: 100 })
await ae.awaitHeight(2)
await ae.spend(1e26, account.publicKey)
})()

Expand Down
6 changes: 3 additions & 3 deletions test/integration/oracle.js
Expand Up @@ -59,14 +59,14 @@ describe('Oracle', function () {
if (count !== 4) return
stopPolling()
done()
}, { interval: 100 })
})
oracle.postQuery("{'city': 'Berlin2'}")
.then(() => oracle.postQuery("{'city': 'Berlin3'}"))
.then(() => oracle.postQuery("{'city': 'Berlin4'}"))
}).timeout(10000)

it('Poll for response for query without response', async () => {
return query.pollForResponse({ attempts: 2, interval: 1000 }).should.be.rejectedWith(Error)
return query.pollForResponse().should.be.rejectedWith(Error)
})

it('Respond to query', async () => {
Expand All @@ -79,7 +79,7 @@ describe('Oracle', function () {
})

it('Poll for response', async () => {
const response = await query.pollForResponse({ attempts: 2, interval: 1000 })
const response = await query.pollForResponse()
response.should.be.equal(queryResponse)
})

Expand Down

0 comments on commit d9c6cf9

Please sign in to comment.