Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
ermalkaleci committed Oct 19, 2023
1 parent 7cf80c0 commit e44e361
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 98 deletions.
1 change: 1 addition & 0 deletions packages/core/src/blockchain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,7 @@ export class Blockchain {
*/
async close() {
await releaseWorker()
await this.api.disconnect()
await this.db?.destroy()
}
}
71 changes: 19 additions & 52 deletions packages/core/src/chopsticks-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
ProviderInterfaceCallback,
ProviderInterfaceEmitCb,
ProviderInterfaceEmitted,
ProviderStats,
} from '@polkadot/rpc-provider/types'

import { Blockchain } from './blockchain'
Expand Down Expand Up @@ -35,57 +34,43 @@ interface Subscription extends SubscriptionHandler {
result?: unknown
}

export interface ChopsticksProviderProps {
/** chopsticks Blockchain type */
chain?: Blockchain
}

/**
* A provider for ApiPromise.
*
* Provider for local chopsticks chain
*/
export class ChopsticksProvider implements ProviderInterface {
#isConnected = false
#eventemitter: EventEmitter
#isReadyPromise: Promise<void>
readonly stats?: ProviderStats
#subscriptions: Record<string, Subscription> = {}
#chain: Blockchain

constructor({ chain }: ChopsticksProviderProps) {
if (!chain) {
throw new Error('ChopsticksProvider requires a blockchain instance.')
}
this.#chain = chain

constructor(public readonly chain: Blockchain) {
this.#eventemitter = new EventEmitter()

this.#isReadyPromise = new Promise((resolve, reject): void => {
this.#eventemitter.once('connected', (): void => {
logger.debug('isReadyPromise: connected.')
resolve()
})
this.#eventemitter.once('connected', resolve)
this.#eventemitter.once('error', reject)
})

this.connect()
}

static fromEndpoint = async (endpoint: string) => {
const chain = await setup({
endpoint,
mockSignatureHost: true,
})
const provider = new ChopsticksProvider({ chain })
return provider
static fromEndpoint = async (endpoint: string, block?: number | string | null, cache?: string) => {
return new ChopsticksProvider(
await setup({
endpoint,
mockSignatureHost: true,
block,
db: cache,
}),
)
}

get hasSubscriptions(): boolean {
return true
}

get isClonable(): boolean {
return false
return true
}

get isConnected(): boolean {
Expand All @@ -96,32 +81,18 @@ export class ChopsticksProvider implements ProviderInterface {
return this.#isReadyPromise
}

get chain(): Blockchain {
if (!this.#chain) {
throw new Error('ChopsticksProvider is not connected')
}
return this.#chain
}

clone = () => {
throw new Error('ChopsticksProvider is not clonable')
return new ChopsticksProvider(this.chain)
}

connect = async (): Promise<void> => {
if (this.#isConnected) return
try {
this.#isConnected = true
this.#eventemitter.emit('connected')
} catch (e) {
logger.error('onMessage: connect error.', e)
}
this.#isConnected = true
this.#eventemitter.emit('connected')
}

disconnect = async (): Promise<void> => {
this.#isConnected = false
if (this.#chain) {
await this.#chain?.api.disconnect()
}
this.#eventemitter.emit('disconnected')
}

on = (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): (() => void) => {
Expand Down Expand Up @@ -172,18 +143,14 @@ export class ChopsticksProvider implements ProviderInterface {
subscription?: SubscriptionHandler,
): Promise<T> => {
try {
if (!this.isConnected) {
throw new Error('Api is not connected')
}

logger.debug('send', { method, params })

const rpcHandler = providerHandlers[method]
if (!rpcHandler) {
logger.error(`Unable to find rpc handler=${method}`)
throw new Error(`Unable to find rpc handler=${method}`)
}
const result = await rpcHandler({ chain: this.#chain }, params, this.subscriptionManager)
const result = await rpcHandler({ chain: this.chain }, params, this.subscriptionManager)
logger.debug('send-result', { method, params, result })

if (subscription) {
Expand Down Expand Up @@ -224,7 +191,7 @@ export class ChopsticksProvider implements ProviderInterface {
}

try {
return this.isConnected ? this.send<boolean>(method, [id]) : true
return this.send<boolean>(method, [id])
} catch {
return false
}
Expand Down
24 changes: 11 additions & 13 deletions packages/e2e/src/chopsticks-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,21 @@ import networks from './networks'
const { alice, bob } = testingPairs()

describe('chopsticks provider works', async () => {
let api: ApiPromise
let chopsticksProvider: ChopsticksProvider

const acala = await networks.acala({ blockNumber: 3_800_000, endpoint: env.acala.endpoint })
const { chain } = acala

beforeAll(async () => {
chopsticksProvider = new ChopsticksProvider({ chain })
api = await ApiPromise.create({
provider: chopsticksProvider,
signedExtensions: {
SetEvmOrigin: {
extrinsic: {},
payload: {},
},
const chopsticksProvider = new ChopsticksProvider(chain)
const api = await ApiPromise.create({
provider: chopsticksProvider,
signedExtensions: {
SetEvmOrigin: {
extrinsic: {},
payload: {},
},
})
},
})

beforeAll(async () => {
await api.isReady
await setStorage(chopsticksProvider.chain, {
System: {
Expand Down
10 changes: 3 additions & 7 deletions packages/web-test/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import {
Typography,
} from '@mui/material'
import { Buffer } from 'buffer'
import { ApiPromise } from '@polkadot/api'
import { HexString } from '@polkadot/util/types'
import { Keyring } from '@polkadot/keyring'
import { setStorage, setup } from '@acala-network/chopsticks-core'
import { setupChopsticksApiPromise } from './utils'
import { ChopsticksProvider, setStorage, setup } from '@acala-network/chopsticks-core'
import { styled } from '@mui/system'
import { useEffect, useState } from 'react'
import type { SetupOptions } from '@acala-network/chopsticks-core'
Expand Down Expand Up @@ -110,10 +110,7 @@ function App() {
db: 'cache',
})
globalThis.chain = chain

await setupChopsticksApiPromise({
chain,
})
globalThis.api = new ApiPromise({ provider: new ChopsticksProvider(chain) })

await setStorage(chain, {
System: {
Expand Down Expand Up @@ -142,7 +139,6 @@ function App() {
setupChain()

return () => {
globalThis.chain?.api.disconnect()
globalThis.chain?.close()
}
}, [])
Expand Down
17 changes: 0 additions & 17 deletions packages/web-test/src/utils.ts

This file was deleted.

16 changes: 7 additions & 9 deletions packages/web-test/tests/chopsticks-provider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ test.describe.skip('chopsticks provider', async () => {

let page: Page
let api: ApiPromise
let chopsticksProvider: ChopsticksProvider

test.beforeAll(async ({ browser }) => {
test.setTimeout(5 * 60000)
Expand All @@ -21,19 +20,19 @@ test.describe.skip('chopsticks provider', async () => {
await page.waitForLoadState()

const chain = await setup({ block: 3_800_000, endpoint: 'wss://acala-rpc.aca-api.network' })
chopsticksProvider = new ChopsticksProvider({ chain })
api = await ApiPromise.create({
provider: chopsticksProvider,
})
await api.isReady
await setStorage(chopsticksProvider.chain, {
await setStorage(chain, {
System: {
Account: [
[[alice.address], { providers: 1, data: { free: 1 * 1e12 } }],
[[bob.address], { providers: 1, data: { free: 1 * 1e12 } }],
],
},
})

api = await ApiPromise.create({
provider: new ChopsticksProvider(chain),
})
await api.isReady
})

test.afterAll(async () => {
Expand Down Expand Up @@ -79,8 +78,7 @@ test.describe.skip('chopsticks provider', async () => {
const bob = keyring.addFromUri('//Bob')

await api.tx.balances.transfer(bob.address, 1000).signAndSend(alice)
await api.rpc('new_block')

await chain.upcomingBlocks()
const bobAccount = await api.query.system.account(bob.address)
expect(bobAccount.data.free.toHuman()).toBe(`${1 * 1e12 + 1000}`)
})
Expand Down

0 comments on commit e44e361

Please sign in to comment.