123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- 'use strict'
- const debug = require('debug')('joystream:runtime:base')
- const { registerJoystreamTypes } = 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 { GenericExtrinsicPayloadV2 } = require('../../../pioneer/packages/apps/build/main.a723bde4')
- 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 || {}
-
- registerJoystreamTypes()
- const provider = new WsProvider(options.provider_url || 'ws://localhost:9944')
-
- this.api = await ApiPromise.create({ provider })
-
- this.asyncLock = new AsyncLock()
-
- this.nonces = {}
-
- 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()
- }
- 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()
- event.data.forEach((data, index) => {
- const type = types[index].type
- payload.set(index, { type, data })
- })
- const fullName = `${event.section}.${event.method}`
- debug(`matched event: ${fullName} =>`, ...event.data.map((data) => `${data},`))
- 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!')
- }
-
-
-
-
- let onFinalizedSuccess
-
- let onFinalizedFailed
-
-
- let unsubscribe
- let lastTxUpdateResult
- const handleTxUpdates = (result) => {
- const { events = [], status } = result
- if (!result || !status) {
- return
- }
- lastTxUpdateResult = result
-
-
- if (status.isUsurped) {
- debug(status.type)
- debug(JSON.stringify(status.asUsurped))
- onFinalizedFailed && onFinalizedFailed({ err: 'Usurped', result, tx: status.asFinalized })
- }
- if (status.isDropped) {
- debug(status.type)
- debug(JSON.stringify(status.asDropped))
- onFinalizedFailed && onFinalizedFailed({ err: 'Dropped', result, tx: status.asFinalized })
- }
-
-
-
- if (status.isInvalid) {
- debug(status.type)
- debug(JSON.stringify(status.asInvalid))
- onFinalizedFailed && onFinalizedFailed({ err: 'Invalid', result, tx: status.asFinalized })
- }
- if (status.isFinalized) {
- 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,
- tx: status.asFinalized,
- dispatchError,
- })
- } else if (success) {
-
-
- if (sudid) {
- const dispatchSuccess = sudid.event.data[0]
- if (dispatchSuccess.isTrue) {
- onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
- } else {
- onFinalizedFailed({ err: 'SudoFailed', mappedEvents, result, tx: status.asFinalized })
- }
- } else if (sudoAsDone) {
- const dispatchSuccess = sudoAsDone.event.data[0]
- if (dispatchSuccess.isTrue) {
- onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
- } else {
- onFinalizedFailed({ err: 'SudoAsFailed', mappedEvents, result, tx: status.asFinalized })
- }
- } else {
- onFinalizedSuccess({ mappedEvents, result, tx: status.asFinalized })
- }
- }
- }
- if (result.isCompleted) {
- unsubscribe()
- }
- }
-
- await this.executeWithAccountLock(accountId, async () => {
- const nonce = this.nonces[accountId] || (await this.api.query.system.accountNonce(accountId))
- try {
- unsubscribe = await tx.sign(fromKey, { nonce }).send(handleTxUpdates)
- debug('TransactionSubmitted')
-
- this.nonces[accountId] = nonce.addn(1)
- } catch (err) {
- const errstr = err.toString()
- debug('TransactionRejected:', errstr)
-
-
-
-
-
-
-
- if (errstr.indexOf('ExtrinsicStatus:: 1010: Invalid Transaction: Stale') !== -1) {
-
-
-
- delete this.nonces[accountId]
- }
-
-
-
-
- if (errstr.indexOf('ExtrinsicStatus:: 1014: Priority is too low') !== -1) {
- delete this.nonces[accountId]
- }
- throw err
- }
- })
-
- if (lastTxUpdateResult.status.isFuture) {
- debug('Warning: Submitted extrinsic with future nonce')
- return {}
- }
-
-
-
- return new Promise((resolve, reject) => {
- onFinalizedSuccess = resolve
- 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
- }
- }
- module.exports = {
- RuntimeApi,
- }
|