Skip to content
This repository has been archived by the owner on Sep 14, 2023. It is now read-only.

Commit

Permalink
fix errors
Browse files Browse the repository at this point in the history
  • Loading branch information
harrysolovay committed Feb 20, 2023
1 parent 51176ee commit 47ffeba
Show file tree
Hide file tree
Showing 20 changed files with 66 additions and 77 deletions.
20 changes: 9 additions & 11 deletions _tasks/download_frame_metadata.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { rawClient as kusama } from "kusama/client.ts"
import { rawClient as polkadot } from "polkadot/client.ts"
import { rawClient as rococo } from "rococo/client.ts"
import { rawClient as westend } from "westend/client.ts"
import { RpcServerError } from "../rpc/mod.ts"
import { chain as kusama } from "kusama/mod.ts"
import { chain as polkadot } from "polkadot/mod.ts"
import { chain as rococo } from "rococo/mod.ts"
import { chain as westend } from "westend/mod.ts"

const knownClients = { kusama, polkadot, westend, rococo }
const knownChains = { kusama, polkadot, westend, rococo }

const names = Object.keys(knownClients)
const names = Object.keys(knownChains)
const outDir = new URL("../frame_metadata/_downloaded", import.meta.url)
try {
Deno.removeSync(outDir, { recursive: true })
Expand Down Expand Up @@ -34,11 +33,10 @@ async function download(name: string) {
Deno.writeTextFileSync(modFilePath, modFileContents, { create: true })

await Promise.all(
Object.entries(knownClients).map(async ([name, client]) => {
const result = await client.call<string>("state_getMetadata", [])
if (result.error) throw new RpcServerError(result)
Object.entries(knownChains).map(async ([name, chain]) => {
const result = await chain.connection.call("state_getMetadata").run()
const outPath = new URL(`_downloaded/${name}.scale`, outDir)
console.log(`Downloading ${name} metadata to "${outPath}".`)
await Deno.writeTextFile(outPath, result.result)
await Deno.writeTextFile(outPath, result)
}),
)
10 changes: 5 additions & 5 deletions codegen/frame/FrameCodegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { typeVisitor } from "./typeVisitor.ts"

export interface FrameCodegenProps {
metadata: Metadata
clientFile: File
chainFile: File
}

export class FrameCodegen {
Expand All @@ -20,9 +20,9 @@ export class FrameCodegen {
typeVisitor
typeFiles = new Map<string, TypeFile>()

constructor({ metadata, clientFile }: FrameCodegenProps) {
constructor({ metadata, chainFile }: FrameCodegenProps) {
this.metadata = metadata
this.clientFile = clientFile
this.clientFile = chainFile

this.typeVisitor = typeVisitor(this)

Expand All @@ -33,7 +33,7 @@ export class FrameCodegen {

this.files.set("codecs.ts", codecs(this))

this.files.set("client.ts", clientFile)
this.files.set("chain.ts", chainFile)

const callTy = Object
.fromEntries(this.metadata.extrinsic.ty.params.map((x) => [x.name.toLowerCase(), x.ty]))
Expand All @@ -60,7 +60,7 @@ export class FrameCodegen {
this.typeVisitor.visit(eventTy)
}>
export * from "./client.ts"
export * from "./chain.ts"
export * as types from "./types/mod.ts"
${palletNamespaceExports}
Expand Down
6 changes: 3 additions & 3 deletions codegen/frame/pallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ export function pallet(ctx: FrameCodegen, pallet: Pallet) {
import * as codecs from "./codecs.ts"
import { $ } from "./capi.ts"
import * as C from "./capi.ts"
import { client } from "./client.ts"
import { chain } from "./chain.ts"
`]
for (const entry of pallet.storage?.entries ?? []) {
items.push(
makeDocComment(entry.docs)
+ `export const ${entry.name} = client.metadata()`
+ `export const ${entry.name} = chain.metadata()`
+ `.pallet(${S.string(pallet.name)})`
+ `.storage(${S.string(entry.name)})`
+ `["_asCodegenStorage"](${
Expand All @@ -39,7 +39,7 @@ export function pallet(ctx: FrameCodegen, pallet: Pallet) {
items.push(
makeDocComment(call.docs)
+ `export function ${type}<X>(...args: Parameters<typeof ${typeName}<X>>): C.ExtrinsicRune<C.RunicArgs.U<X>, Chain>`
+ `{ return client.extrinsic(C.Rune.rec({ type: ${
+ `{ return chain.extrinsic(C.Rune.rec({ type: ${
S.string(pallet.name)
}, value: ${typeName}(...args) })) }`,
)
Expand Down
4 changes: 2 additions & 2 deletions examples/block_author.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { babeBlockAuthor } from "capi/patterns/consensus/mod.ts"
import { client } from "polkadot/mod.ts"
import { chain } from "polkadot/mod.ts"

const result = await babeBlockAuthor(client, client.latestBlock.hash).run()
const result = await babeBlockAuthor(chain, chain.latestBlock.hash).run()

console.log(result)
4 changes: 2 additions & 2 deletions examples/block_events.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { client } from "polkadot/mod.ts"
import { chain } from "polkadot/mod.ts"

const result = await client.latestBlock.events().run()
const result = await chain.latestBlock.events().run()

console.log(result)
4 changes: 2 additions & 2 deletions examples/block_extrinsics.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { client } from "polkadot/mod.ts"
import { chain } from "polkadot/mod.ts"

const result = await client.latestBlock.extrinsics().run()
const result = await chain.latestBlock.extrinsics().run()

console.log(result)
4 changes: 2 additions & 2 deletions examples/dynamic/balance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { alice } from "capi"
import { client } from "polkadot_dev/mod.ts"
import { chain } from "polkadot_dev/mod.ts"

const result = await client
const result = await chain
.metadata()
.pallet("System")
.storage("Account")
Expand Down
14 changes: 0 additions & 14 deletions examples/foo.ts

This file was deleted.

12 changes: 6 additions & 6 deletions examples/ink_e2e/main.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { AddressRune, alice } from "capi"
import { AddressRune, alice, Rune } from "capi"
import {
InkMetadataRune,
instantiationEventIntoPublicKey,
isInstantiatedEvent,
} from "capi/patterns/ink/mod.ts"
import { client } from "zombienet/rococo_contracts.toml/collator/@latest/mod.ts"
import { chain } from "zombienet/rococo_contracts.toml/collator/@latest/mod.ts"
import { parse } from "../../deps/std/flags.ts"

export const metadata = InkMetadataRune.from(
client,
chain,
Deno.readTextFileSync("examples/ink_e2e/metadata.json"),
)

Expand All @@ -34,15 +34,15 @@ if (!address) {
)
.unhandle(FailedToFindContractInstantiatedError)
.pipe(instantiationEventIntoPublicKey)
.address(client)
.address(chain)
.run()
}
console.log(`Contract address: ${address}`)

const publicKey = AddressRune.from(client, address).publicKey()
const publicKey = Rune.resolve(address).into(AddressRune, chain).publicKey()
console.log("Contract public key:", await publicKey.run())

const contract = metadata.instance(client, publicKey)
const contract = metadata.instance(chain, publicKey)

console.log("Get:", await contract.call({ sender, method: "get" }).run())

Expand Down
4 changes: 2 additions & 2 deletions examples/metadata.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { client } from "polkadot_dev/mod.ts"
import { chain } from "polkadot_dev/mod.ts"

const result = await client.metadata().run()
const result = await chain.metadata().run()

console.log(result)
14 changes: 8 additions & 6 deletions examples/multisig_transfer.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { alice, bob, charlie, dave, ValueRune } from "capi"
import { alice, bob, charlie, dave, Rune, ValueRune } from "capi"
import { MultisigRune } from "capi/patterns/MultisigRune.ts"
import { Balances, client, System } from "polkadot_dev/mod.ts"
import { Balances, chain, System } from "polkadot_dev/mod.ts"
// TODO: utilize type exposed from capi/patterns/MultisigRune.ts (when we enable client env specificity)
import { MultiAddress } from "polkadot_dev/types/sp_runtime/multiaddress.ts"

const multisig = MultisigRune.from(client, {
signatories: [alice.publicKey, bob.publicKey, charlie.publicKey],
threshold: 2,
})
const multisig = Rune
.constant({
signatories: [alice.publicKey, bob.publicKey, charlie.publicKey],
threshold: 2,
})
.into(MultisigRune, chain)

// Read dave's initial balance (to-be changed by the call)
console.log("Dave initial balance:", await System.Account.entry([dave.publicKey]).run())
Expand Down
4 changes: 2 additions & 2 deletions examples/watch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Rune } from "capi"
import { client, Timestamp } from "polkadot/mod.ts"
import { chain, Timestamp } from "polkadot/mod.ts"

const block = client.latestBlock
const block = chain.latestBlock
const extrinsics = block.extrinsics()
const events = block.events()
const now = Timestamp.Now.entry([], block.hash)
Expand Down
4 changes: 2 additions & 2 deletions examples/xcm_asset_teleportation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { alice, Rune, ValueRune } from "capi"
import { types, XcmPallet } from "zombienet/statemine.toml/alice/@latest/mod.ts"
import { Event as XcmPalletEvent } from "zombienet/statemine.toml/alice/@latest/types/pallet_xcm/pallet.ts"
import { RuntimeEvent as AliceRuntimeEvent } from "zombienet/statemine.toml/alice/@latest/types/rococo_runtime/mod.ts"
import { client, System } from "zombienet/statemine.toml/collator/@latest/mod.ts"
import { chain, System } from "zombienet/statemine.toml/collator/@latest/mod.ts"
import { Event as ParachainSystemEvent } from "zombienet/statemine.toml/collator/@latest/types/cumulus_pallet_parachain_system/pallet.ts"
import { RuntimeEvent as CollatorRuntimeEvent } from "zombienet/statemine.toml/collator/@latest/types/statemine_runtime.ts"

Expand Down Expand Up @@ -64,7 +64,7 @@ const initiatedEvent = XcmPallet
.log("Initiated event:")

const processedEvent = System.Events
.entry([], client.latestBlock.hash)
.entry([], chain.latestBlock.hash)
.into(ValueRune)
.map((events) =>
events
Expand Down
2 changes: 1 addition & 1 deletion fluent/ChainRune.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ConnectionRune } from "./ConnectionRune.ts"
import { ExtrinsicRune } from "./ExtrinsicRune.ts"
import { MetadataRune } from "./MetadataRune.ts"

export interface Chain<C = any, E extends Event = Event> {
export interface Chain<C = any, E extends Event = any> {
connection: Connection
_call?: $.Codec<C>
_event?: $.Codec<E>
Expand Down
7 changes: 6 additions & 1 deletion fluent/ConnectionRune.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Calls, Subscription, Subscriptions } from "../rpc/known/mod.ts"
import { Connection, RpcClientError, RpcServerError, RpcSubscriptionMessage } from "../rpc/mod.ts"
import { Batch, MetaRune, Run, Rune, RunicArgs, RunStream } from "../rune/mod.ts"
import { Batch, MetaRune, Run, Rune, RunicArgs, RunStream, ValueRune } from "../rune/mod.ts"
import { ChainRune } from "./ChainRune.ts"

class RunConnection extends Run<Connection, never> {
constructor(ctx: Batch, readonly initConnection: (signal: AbortSignal) => Connection) {
Expand Down Expand Up @@ -55,6 +56,10 @@ export class ConnectionRune<U> extends Rune<Connection, U> {
})
.throws(RpcClientError, RpcServerError)
}

chain() {
return this.into(ValueRune).map((x) => ({ connection: x })).into(ChainRune)
}
}

class RunRpcSubscription<Method extends string, NotificationData>
Expand Down
5 changes: 2 additions & 3 deletions patterns/MultisigRune.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { types } from "polkadot_dev/mod.ts"
import * as bytes from "../deps/std/bytes.ts"
import { Chain, ChainRune } from "../fluent/ChainRune.ts"
import { ExtrinsicRune } from "../fluent/mod.ts"
Expand Down Expand Up @@ -108,8 +107,8 @@ export class MultisigRune<out U, out C extends Chain = Chain> extends Rune<Multi
private maybeTimepoint<X>(...[callHash]: RunicArgs<X, [callHash: Uint8Array]>) {
return Rune.captureUnhandled(
[this, this.chain, callHash],
(multisig, client, callHash) =>
multisig.into(MultisigRune, client.into(ChainRune))
(multisig, chain, callHash) =>
multisig.into(MultisigRune, chain.into(ChainRune))
.proposal(callHash)
.unsafeAs<{ when: unknown }>()
.into(ValueRune)
Expand Down
1 change: 1 addition & 0 deletions patterns/ink/InkMetadataRune.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export class InkMetadataRune<out U, out C extends Chain = Chain> extends Rune<In
.map(DeriveCodec)
}

// TODO: remove
static from<U, C extends Chain, X>(
chain: ChainRune<U, C>,
...[jsonText]: RunicArgs<X, [jsonText: string]>
Expand Down
12 changes: 6 additions & 6 deletions providers/frame/FrameProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export abstract class FrameProvider extends Provider {

codegenCtxsPending: Record<string, Promise<FrameCodegen>> = {}

abstract client(pathInfo: PathInfo, signal: AbortSignal): Promise<Connection>
abstract clientFile(pathInfo: PathInfo): Promise<File>
abstract connect(pathInfo: PathInfo, signal: AbortSignal): Promise<Connection>
abstract chainFile(pathInfo: PathInfo): Promise<File>

async handle(request: Request, pathInfo: PathInfo): Promise<Response> {
const { vRuntime, filePath } = pathInfo
Expand Down Expand Up @@ -50,7 +50,7 @@ export abstract class FrameProvider extends Provider {
// TODO: memo
async latestVersion(pathInfo: PathInfo) {
return await withSignal(async (signal) => {
const client = await this.client(pathInfo, signal)
const client = await this.connect(pathInfo, signal)
const version = await this.clientCall<string>(client, "system_version", [])
return this.normalizeRuntimeVersion(version)
})
Expand All @@ -68,8 +68,8 @@ export abstract class FrameProvider extends Provider {
codegen(pathInfo: PathInfo) {
return this.codegenMemo.run(this.cacheKey(pathInfo), async () => {
const metadata = await this.getMetadata(pathInfo)
const clientFile = await this.clientFile(pathInfo)
return new FrameCodegen({ metadata, clientFile })
const chainFile = await this.chainFile(pathInfo)
return new FrameCodegen({ metadata, chainFile })
})
}

Expand All @@ -82,7 +82,7 @@ export abstract class FrameProvider extends Provider {
if (pathInfo.vRuntime !== await this.latestVersion(pathInfo)) {
throw f.serverError("Cannot get metadata for old runtime version")
}
const client = await this.client(pathInfo, signal)
const client = await this.connect(pathInfo, signal)
const metadata = fromPrefixedHex(
await this.clientCall(client, "state_getMetadata", []),
)
Expand Down
10 changes: 4 additions & 6 deletions providers/frame/FrameProxyProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export abstract class FrameProxyProvider extends FrameProvider {
}

async proxyWs(request: Request, pathInfo: PathInfo) {
console.log("new connection")
const url = await this.dynamicUrl(pathInfo)
const server = new WebSocket(url)
const { socket: client, response } = Deno.upgradeWebSocket(request)
Expand Down Expand Up @@ -59,21 +58,20 @@ export abstract class FrameProxyProvider extends FrameProvider {
).toString()
}

async client(pathInfo: PathInfo, signal: AbortSignal) {
async connect(pathInfo: PathInfo, signal: AbortSignal) {
return WsConnection.connect(await this.dynamicUrl(pathInfo), signal)
}

async clientFile(pathInfo: PathInfo) {
async chainFile(pathInfo: PathInfo) {
const url = this.staticUrl(pathInfo)
return new File(`
import * as C from "./capi.ts"
import type { Chain } from "./mod.ts"
export const discoveryValue = "${url}"
export const client = C.rpcClient(C.WsRpcConn, discoveryValue)["_asCodegen"]<Chain>()
export const rawClient = new C.RpcClient(C.WsRpcConn, discoveryValue)
export const chain = C.connection((signal) => C.WsConnection.connect(discoveryValue, signal))
.chain()["_asCodegen"]<Chain>()
`)
}
}
2 changes: 1 addition & 1 deletion rpc/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export abstract class Connection {
const connection = new this(discovery)
connection.ref(signal)
connection.signal.addEventListener("abort", () => {
memo.delete(connection)
memo.delete(discovery)
})
return connection
})
Expand Down

0 comments on commit 47ffeba

Please sign in to comment.