UNPKG

@aeternity/aepp-sdk

Version:

SDK for the æternity blockchain

105 lines (100 loc) 2.88 kB
import { pause } from '../utils/other.js'; import { oracleQueryId } from '../tx/builder/helpers.js'; import { unpackTx, buildTxAsync } from '../tx/builder/index.js'; import { Tag } from '../tx/builder/constants.js'; import { RequestTimedOutError } from '../utils/errors.js'; import { decode } from '../utils/encoder.js'; import { _getPollInterval, getHeight } from '../chain.js'; import { sendTransaction } from '../send-transaction.js'; import OracleBase from './OracleBase.js'; /** * @category oracle */ /** * @category oracle */ export default class OracleClient extends OracleBase { /** * @param address - Oracle public key * @param options - Options object * @param options.onAccount - Account to use * @param options.onNode - Node to use */ constructor(address, options) { super(address, options); this.options = options; } /** * Post query to oracle * @param query - Query to oracle * @param options - Options object * @returns Transaction details and query ID */ async postQuery(query, options = {}) { const opt = { ...this.options, ...options }; const senderId = opt.onAccount.address; const oracleQueryTx = await buildTxAsync({ _isInternalBuild: true, ...opt, tag: Tag.OracleQueryTx, oracleId: this.address, senderId, query }); const { nonce } = unpackTx(oracleQueryTx, Tag.OracleQueryTx); return { ...(await sendTransaction(oracleQueryTx, opt)), queryId: oracleQueryId(senderId, nonce, this.address) }; } /** * Poll for oracle response to query * @param queryId - Oracle Query id * @param options - Options object * @param options.interval - Poll interval * @returns Oracle response */ async pollForResponse(queryId, options = {}) { var _opt$interval; const opt = { ...this.options, ...options }; const interval = (_opt$interval = opt.interval) !== null && _opt$interval !== void 0 ? _opt$interval : await _getPollInterval('micro-block', opt); let height; let ttl; let response; do { ({ response, ttl } = await this.getQuery(queryId, opt)); const responseBuffer = decode(response); if (responseBuffer.length > 0) return responseBuffer.toString(); await pause(interval); height = await getHeight({ ...opt, cached: true }); } while (ttl >= height); throw new RequestTimedOutError(height); } /** * Post query to oracle and wait for response * @param query - Query to oracle * @param options - Options object * @returns Oracle response */ async query(query, options = {}) { const { queryId } = await this.postQuery(query, options); return this.pollForResponse(queryId, options); } } //# sourceMappingURL=OracleClient.js.map