123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382 |
- 'use strict'
- const debug = require('debug')('joystream:runtime:base')
- const debugTx = require('debug')('joystream:runtime:base:tx')
- const { types } = require('@joystream/types')
- const { ApiPromise, WsProvider } = require('@polkadot/api')
- const { IdentitiesApi } = require('@joystream/storage-runtime-api/identities')
- const { BalancesApi } = require('@joystream/storage-runtime-api/balances')
- const { WorkersApi } = require('@joystream/storage-runtime-api/workers')
- const { AssetsApi } = require('@joystream/storage-runtime-api/assets')
- const { DiscoveryApi } = require('@joystream/storage-runtime-api/discovery')
- const { SystemApi } = require('@joystream/storage-runtime-api/system')
- const AsyncLock = require('async-lock')
- const Promise = require('bluebird')
- const { sleep } = require('@joystream/storage-utils/sleep')
- Promise.config({
- cancellation: true,
- })
- const TX_TIMEOUT = 20 * 1000
- class RuntimeApi {
- static async create(options) {
- const runtimeApi = new RuntimeApi()
- await runtimeApi.init(options || {})
- return runtimeApi
- }
- async init(options) {
- debug('Init')
- options = options || {}
- const provider = new WsProvider(options.provider_url || 'ws://localhost:9944')
- let attempts = 0
-
- while (true) {
- attempts++
- if (options.retries && attempts > options.retries) {
- throw new Error('Timeout trying to connect to node')
- }
- try {
- this.api = await ApiPromise.create({ provider, types: types })
- break
- } catch (err) {
- debug('Connecting to node failed, will retry..')
- }
- await sleep(5000)
- }
- await this.api.isReady
- this.asyncLock = new AsyncLock()
-
- this.storageProviderId = parseInt(options.storageProviderId)
-
- this.identities = await IdentitiesApi.create(this, {
- accountFile: options.account_file,
- passphrase: options.passphrase,
- canPromptForPassphrase: options.canPromptForPassphrase,
- })
- this.balances = await BalancesApi.create(this)
- this.workers = await WorkersApi.create(this)
- this.assets = await AssetsApi.create(this)
- this.discovery = await DiscoveryApi.create(this)
- this.system = await SystemApi.create(this)
- }
- disconnect() {
- this.api.disconnect()
- }
- async untilChainIsSynced() {
- debug('Waiting for chain to be synced before proceeding.')
- while (true) {
- const isSyncing = await this.chainIsSyncing()
- if (isSyncing) {
- debug('Still waiting for chain to be synced.')
- await sleep(1 * 30 * 1000)
- } else {
- return
- }
- }
- }
- async chainIsSyncing() {
- const { isSyncing } = await this.api.rpc.system.health()
- return isSyncing.isTrue
- }
- async providerHasMinimumBalance(minimumBalance) {
- const providerAccountId = this.identities.key.address
- return this.balances.hasMinimumBalanceOf(providerAccountId, minimumBalance)
- }
- async providerIsActiveWorker() {
- return this.workers.isRoleAccountOfStorageProvider(this.storageProviderId, this.identities.key.address)
- }
- executeWithAccountLock(accountId, func) {
- return this.asyncLock.acquire(`${accountId}`, func)
- }
- static matchingEvents(subscribed = [], events = []) {
- const filtered = events.filter((record) => {
- const { event } = record
-
- const matching = subscribed.filter((value) => {
- if (value[0] === '*' && value[1] === '*') {
- return true
- } else if (value[0] === '*') {
- return event.method === value[1]
- } else if (value[1] === '*') {
- return event.section === value[0]
- } else {
- return event.section === value[0] && event.method === value[1]
- }
- })
- return matching.length > 0
- })
- return filtered.map((record) => {
- const { event } = record
- const types = event.typeDef
- const payload = new Map()
-
- if (event.data) {
- event.data.forEach((data, index) => {
- const type = types[index].type
- payload.set(index, { type, data })
- })
- }
- const fullName = `${event.section}.${event.method}`
- debugTx(`matched event: ${fullName} =>`, event.data && event.data.join(', '))
- return [fullName, payload]
- })
- }
-
- async signAndSend(accountId, tx, subscribed) {
-
- accountId = this.identities.keyring.encodeAddress(accountId)
-
- const fromKey = this.identities.keyring.getPair(accountId)
-
- if (fromKey.isLocked) {
- throw new Error('Must unlock key before using it to sign!')
- }
- const callbacks = {
-
-
-
-
- onFinalizedSuccess: null,
-
- onFinalizedFailed: null,
-
-
- unsubscribe: null,
- }
-
- const out = {
- lastResult: { status: {} },
- }
-
- await this.executeWithAccountLock(accountId, async () => {
- const nonce = await this.api.rpc.system.accountNextIndex(accountId)
- const signed = tx.sign(fromKey, { nonce })
- const txhash = signed.hash
- try {
- callbacks.unsubscribe = await signed.send(
- RuntimeApi.createTxUpdateHandler(callbacks, { nonce, txhash, subscribed }, out)
- )
- const serialized = JSON.stringify({
- nonce,
- txhash,
- tx: signed.toHex(),
- })
-
-
-
-
- if (out.lastResult.status.isFuture) {
- debugTx(`Warning: Submitted Tx with future nonce: ${serialized}`)
- } else {
- debugTx(`Submitted: ${serialized}`)
- }
- } catch (err) {
- const errstr = err.toString()
- debugTx(`Rejected: ${errstr} txhash: ${txhash} nonce: ${nonce}`)
- throw err
- }
- })
-
-
-
- if (out.lastResult.status.isFuture) {
- return {}
- }
-
-
-
-
-
- return new Promise((resolve, reject) => {
- callbacks.onFinalizedSuccess = resolve
- callbacks.onFinalizedFailed = reject
- }).timeout(TX_TIMEOUT)
- }
-
- async signAndSendThenGetEventResult(senderAccountId, tx, { module, event, index, type }) {
- if (!module || !event || index === undefined || !type) {
- throw new Error('MissingSubscribeEventDetails')
- }
- const subscribed = [[module, event]]
- const { mappedEvents } = await this.signAndSend(senderAccountId, tx, subscribed)
- if (!mappedEvents) {
-
- throw new Error('NoEventsWereCaptured')
- }
- if (!mappedEvents.length) {
-
- throw new Error('ExpectedEventNotFound')
- }
-
-
- const firstEvent = mappedEvents[0]
- if (firstEvent[0] !== `${module}.${event}`) {
- throw new Error('WrongEventCaptured')
- }
- const payload = firstEvent[1]
- if (!payload.has(index)) {
- throw new Error('DataIndexOutOfRange')
- }
- const value = payload.get(index)
- if (value.type !== type) {
- throw new Error('DataTypeNotExpectedType')
- }
- return value.data
- }
- static createTxUpdateHandler(callbacks, submittedTx, out = {}) {
- const { nonce, txhash, subscribed } = submittedTx
- return function handleTxUpdates(result) {
- const { events = [], status } = result
- const { unsubscribe, onFinalizedFailed, onFinalizedSuccess } = callbacks
- if (!result || !status) {
- return
- }
- out.lastResult = result
- const txinfo = () => {
- return JSON.stringify({
- nonce,
- txhash,
- })
- }
- if (result.isError) {
- unsubscribe()
- debugTx(`Error: ${status.type}`, txinfo())
- onFinalizedFailed &&
- onFinalizedFailed({ err: status.type, result, tx: status.isUsurped ? status.asUsurped : undefined })
- } else if (result.isCompleted) {
- unsubscribe()
- debugTx('Finalized', txinfo())
- const mappedEvents = RuntimeApi.matchingEvents(subscribed, events)
- const failed = result.findRecord('system', 'ExtrinsicFailed')
- const success = result.findRecord('system', 'ExtrinsicSuccess')
- const sudid = result.findRecord('sudo', 'Sudid')
- const sudoAsDone = result.findRecord('sudo', 'SudoAsDone')
- if (failed) {
- const {
- event: { data },
- } = failed
- const dispatchError = data[0]
- onFinalizedFailed({
- err: 'ExtrinsicFailed',
- mappedEvents,
- result,
- block: status.asCompleted,
- dispatchError,
- })
- } else if (success) {
-
-
- if (sudid) {
- const dispatchSuccess = sudid.event.data[0]
- if (dispatchSuccess.isOk) {
- onFinalizedSuccess({ mappedEvents, result, block: status.asCompleted })
- } else {
- onFinalizedFailed({ err: 'SudoFailed', mappedEvents, result, block: status.asCompleted })
- }
- } else if (sudoAsDone) {
- const dispatchSuccess = sudoAsDone.event.data[0]
- if (dispatchSuccess.isOk) {
- onFinalizedSuccess({ mappedEvents, result, block: status.asCompleted })
- } else {
- onFinalizedFailed({ err: 'SudoAsFailed', mappedEvents, result, block: status.asCompleted })
- }
- } else {
- onFinalizedSuccess({ mappedEvents, result, block: status.asCompleted })
- }
- }
- }
- }
- }
- }
- module.exports = {
- RuntimeApi,
- }
|