Skip to content

Commit

Permalink
Merge pull request #1485 from Phala-Network/jssdk-random-improve
Browse files Browse the repository at this point in the history
JSSDK: Preload metadata in `getClient` & bugfix
  • Loading branch information
Leechael authored Dec 24, 2023
2 parents e8f0cfa + f3be121 commit b027efd
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 9 deletions.
2 changes: 1 addition & 1 deletion frontend/packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@phala/sdk",
"version": "0.5.7",
"version": "0.5.8",
"description": "Phala Phat Contract JS SDK",
"license": "Apache-2.0",
"author": [
Expand Down
5 changes: 5 additions & 0 deletions frontend/packages/sdk/src/OnChainRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ export class OnChainRegistry {
pruntimeURL: options.pruntimeURL,
}
await instance.connect(workerInfo)
} else if (options.clusterId && !options.strategy) {
await instance.connect({
clusterId: options.clusterId,
strategy: 'ack-first',
} as StrategicWorkerInfo)
} else if (options.strategy) {
await instance.connect({
clusterId: options.clusterId,
Expand Down
4 changes: 2 additions & 2 deletions frontend/packages/sdk/src/contracts/PinkBlueprint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ export class PinkBlueprintPromise {
throw new Error('Method not found')
}
return withMeta(meta[0], (options: PinkBlueprintSendOptions, ...arags: unknown[]) => {
return this.#send(prop as string, options, ...arags)
return this._send(prop as string, options, ...arags)
})
},
}
Expand Down Expand Up @@ -356,7 +356,7 @@ export class PinkBlueprintPromise {
}
}

async #send(constructorOrId: string, options: PinkBlueprintSendOptions, ...args: unknown[]) {
private async _send(constructorOrId: string, options: PinkBlueprintSendOptions, ...args: unknown[]) {
const { cert: userCert, ...rest } = options
const txOptions: PinkBlueprintOptions = {
gasLimit: options.gasLimit,
Expand Down
4 changes: 2 additions & 2 deletions frontend/packages/sdk/src/contracts/PinkContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ export class PinkContractPromise<
throw new Error('Method not found')
}
return withMeta(meta[0], (options: PinkContractSendOptions, ...arags: unknown[]) => {
return this.#send(prop as string, options, ...arags)
return this._send(prop as string, options, ...arags)
})
},
}
Expand Down Expand Up @@ -453,7 +453,7 @@ export class PinkContractPromise<
})
}

async #send(messageOrId: string, options: PinkContractSendOptions, ...args: unknown[]) {
private async _send(messageOrId: string, options: PinkContractSendOptions, ...args: unknown[]) {
const { cert: userCert, ...rest } = options
const txOptions: PinkContractOptions = {
gasLimit: options.gasLimit,
Expand Down
19 changes: 16 additions & 3 deletions frontend/packages/sdk/src/factory_functions.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import { ApiPromise, Keyring, WsProvider } from '@polkadot/api'
import type { AccountId } from '@polkadot/types/interfaces'
import type { HexString } from '@polkadot/util/types'
import { cryptoWaitReady } from '@polkadot/util-crypto'
import { PinkContractPromise } from './contracts/PinkContract'
import { PinkLoggerContractPromise } from './contracts/PinkLoggerContract'
import { type CreateOptions, OnChainRegistry } from './OnChainRegistry'
import { options } from './options'
import createPruntimeClient from './pruntime/createPruntimeClient'
import type { AbiLike } from './types'
import { type LiteralRpc, fetchMetadata } from './utils/fetchMetadata'

export type GetClientOptions = {
transport: string | WsProvider
transport: LiteralRpc | WsProvider

// Provides metadata instead loading via RPC when initializing the client.
// It's optional since if the RPC under the phala.network domain, we will
// try to preload the metadata via HTTP unless the `noPreloadMetadata` is
// set to true.
metadata?: Record<string, HexString>
noPreloadMetadata?: boolean
} & CreateOptions

export async function getClient(opts: GetClientOptions): Promise<OnChainRegistry> {
const { transport, ...rest } = opts
const { transport, metadata: _metadata, noPreloadMetadata, ...rest } = opts
const provider = typeof transport === 'string' ? new WsProvider(transport) : transport
const api = await ApiPromise.create(options({ provider, noInitWarn: true }))
let metadata = _metadata
if (typeof transport === 'string' && !metadata && transport.indexOf('phala.network/') !== -1 && !noPreloadMetadata) {
metadata = await fetchMetadata(transport)
}
const api = await ApiPromise.create(options({ provider, noInitWarn: true, metadata }))
return await OnChainRegistry.create(api, rest)
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/packages/sdk/src/ha/ack-first.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function ackFirst() {
try {
return await Promise.any(pairs.map(([workerId, endpoint]) => ack(workerId, endpoint)))
} catch (_err) {
throw new Error('No worker available.')
throw new Error(`No worker available: ${_err}`)
}
}
}
1 change: 1 addition & 0 deletions frontend/packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export { ackFirst } from './ha/ack-first'
export * from './ha/periodicity-checker'
export * from './ha/fixture'
export * from './factory_functions'
export * from './utils/fetchMetadata'

export const pruntimeRpc = pruntime_rpc
export type PhactoryAPI = pruntime_rpc.PhactoryAPI
Expand Down
29 changes: 29 additions & 0 deletions frontend/packages/sdk/src/utils/fetchMetadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import fetch from 'cross-fetch'

async function requestRpc(http: string, body: string) {
return fetch(http, {
method: 'POST',
body,
headers: { 'content-type': 'application/json' },
}).then((resp) => resp.json())
}

export type LiteralRpc = `ws://${string}` | `wss://${string}`

export async function fetchMetadata(rpc: LiteralRpc) {
const http = rpc
.replace('wss://', 'https://')
.replace('ws://', 'http://')
.replace('ws:/', 'http://')
.replace('wss:/', 'https://')
const [blockHashResp, specResp, metadataResp] = await Promise.all([
requestRpc(http, '{"id":1,"jsonrpc":"2.0","method":"chain_getBlockHash","params":[0]}'),
requestRpc(http, '{"id":2,"jsonrpc":"2.0","method":"state_getRuntimeVersion","params":[]}'),
requestRpc(http, '{"id":3,"jsonrpc":"2.0","method":"state_getMetadata","params":[]}'),
])
const id = `${blockHashResp.result}-${specResp.result.specVersion}`

return {
[id]: metadataResp.result,
}
}

0 comments on commit b027efd

Please sign in to comment.