Skip to content

Commit

Permalink
wip: refactor(agent,cw,scrt): 114 type checks left 🤞
Browse files Browse the repository at this point in the history
  • Loading branch information
egasimus committed May 6, 2024
1 parent f19d87a commit 9b7892f
Show file tree
Hide file tree
Showing 15 changed files with 247 additions and 166 deletions.
7 changes: 5 additions & 2 deletions packages/agent/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,11 @@ export abstract class Backend extends Logged {

abstract connect ():
Promise<Connection>
abstract connect (parameter?: string|Partial<Identity>):
Promise<Connection>
abstract connect (name: string):
Promise<Agent>
abstract connect (identity: Partial<Identity>):
Promise<Agent>

abstract getIdentity (name: string):
Promise<{ address?: Address, mnemonic?: string }>
}
Expand Down
4 changes: 2 additions & 2 deletions packages/agent/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,8 @@ export class ContractInstance extends DeploymentUnit {
}

/** Returns a client to this contract instance. */
connect (
agent?: Connection): Contract
connect (agent?: Connection):
Contract
connect <C extends typeof Contract> (
connection?: Connection, $C: C = Contract as C
) {
Expand Down
113 changes: 68 additions & 45 deletions packages/agent/stub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ export class StubConnection extends Connection {
this.backend ??= new StubBackend()
}

batch (): Batch<this, StubAgent> {
return new StubBatch({ connection: this }) as unknown as Batch<this, StubAgent>
batch (): Batch<StubConnection, StubAgent> {
return new StubBatch({ connection: this }) as unknown as Batch<StubConnection, StubAgent>
}

protected override fetchHeightImpl () {
Expand All @@ -46,13 +46,19 @@ export class StubConnection extends Connection {
return Promise.resolve(new StubBlock({ height: + new Date() }))
}

protected override fetchBalanceImpl (token?: string, address?: string): Promise<string> {
token ??= this.defaultDenom
const balance = (this.backend.balances.get(address!)||{})[token] ?? 0
return Promise.resolve(String(balance))
protected override fetchBalanceImpl (
...args: Parameters<Connection["fetchBalanceImpl"]>
): Promise<string> {
throw new Error('unimplemented!')
//token ??= this.defaultDenom
//const balance = (this.backend.balances.get(address!)||{})[token] ?? 0
//return Promise.resolve(String(balance))
return Promise.resolve('')
}

protected override fetchCodeInfoImpl ({ ids }: { ids: CodeId[]|undefined }):
protected override fetchCodeInfoImpl (
...args: Parameters<Connection["fetchCodeInfoImpl"]>
):
Promise<Record<string, UploadedCode>>
{
if (!ids) {
Expand All @@ -70,12 +76,18 @@ export class StubConnection extends Connection {
}
}

protected override fetchCodeInstancesImpl (id: CodeId) {
return Promise.resolve([...this.backend.uploads.get(id)!.instances]
.map(address=>({address})))
protected override async fetchCodeInstancesImpl (
...args: Parameters<Connection["fetchCodeInstancesImpl"]>
) {
throw new Error('unimplemented!')
return {}
//return Promise.resolve([...this.backend.uploads.get(id)!.instances]
//.map(address=>({address})))
}

protected override fetchContractInfoImpl ({ addresses }: { addresses: Address[] }):
protected override fetchContractInfoImpl (
...args: Parameters<Connection["fetchContractInfoImpl"]>
):
Promise<Record<Address, Contract>>
{
const results = {}
Expand All @@ -97,8 +109,10 @@ export class StubConnection extends Connection {
return Promise.resolve(results)
}

protected override queryImpl <Q> (contract: { address: Address }, message: Message): Promise<Q> {
return Promise.resolve({} as Q)
protected override queryImpl <T> (
...args: Parameters<Connection["queryImpl"]>
): Promise<T> {
return Promise.resolve({} as T)
}

authenticate (identity: Identity): StubAgent {
Expand All @@ -107,8 +121,10 @@ export class StubConnection extends Connection {
}

export class StubAgent extends Agent {

declare connection: StubConnection
protected sendImpl (recipient: Address, sums: Token.ICoin[], opts?: never): Promise<void> {

protected sendImpl (...args: Parameters<Agent["sendImpl"]>): Promise<void> {
if (!this.address) {
throw new Error('not authenticated')
}
Expand All @@ -134,27 +150,27 @@ export class StubAgent extends Agent {
backend.balances.set(recipient, recipientBalances)
return Promise.resolve()
}
protected sendManyImpl (outputs: [Address, Token.ICoin[]][], opts?: never): Promise<void> {
return Promise.resolve()
}
protected async uploadImpl (codeData: Uint8Array): Promise<UploadedCode> {

protected async uploadImpl (
...args: Parameters<Agent["uploadImpl"]>
): Promise<UploadedCode> {
return new UploadedCode(await this.connection.backend.upload(codeData))
}

protected async instantiateImpl (
codeId: CodeId, options: Parameters<Agent["instantiateImpl"]>[1]
...args: Parameters<Agent["instantiateImpl"]>
): Promise<ContractInstance & { address: Address }> {
return new ContractInstance(await this.connection.backend.instantiate(
this.address!, codeId, options
)) as ContractInstance & {
address: Address
}
}
protected executeImpl (
contract: { address: Address, codeHash: CodeHash },
message: Message,
options?: Parameters<Agent["executeImpl"]>[2]
): Promise<void|unknown> {
return Promise.resolve({})

protected executeImpl <T> (
...args: Parameters<Agent["executeImpl"]>
): Promise<T> {
return Promise.resolve({} as T)
}
}

Expand Down Expand Up @@ -214,23 +230,31 @@ export class StubBackend extends Backend {
}
}

async connect ():
Promise<Connection>
async connect (parameter: string|Partial<Identity & { mnemonic?: string }>):
Promise<Agent>
async connect (parameter: string|Partial<Identity & { mnemonic?: string }> = {}): Promise<unknown> {
if (typeof parameter === 'string') {
parameter = await this.getIdentity(parameter)
}
if (parameter.mnemonic && !parameter.address) {
parameter.address = `${this.prefix}${parameter.name}`
}
return new StubConnection({
connect ():
Promise<StubConnection>
connect (name: string):
Promise<StubAgent>
connect (identity: Partial<Identity>):
Promise<StubAgent>
async connect (...args: unknown[]): Promise<StubConnection|StubAgent> {
const connection = new StubConnection({
chainId: this.chainId,
url: 'stub',
alive: this.alive,
backend: this,
}).authenticate(new Identity(parameter))
})
if (!args[0]) {
return connection
}
if (typeof args[0] === 'string') {
return connection.authenticate(new Identity(await this.getIdentity(args[0])))
}
const parameter = args[0] as Partial<Identity> & { mnemonic?: string }
if (parameter.mnemonic && !parameter.address) {
parameter.address = `${this.prefix}${parameter.name}`
return connection.authenticate(new Identity(parameter))
}
throw new Error('invalid argument')
}

getIdentity (name: string): Promise<Identity> {
Expand Down Expand Up @@ -268,19 +292,18 @@ export class StubBackend extends Backend {
return upload
}

async instantiate (
creator: Address, codeId: CodeId, options: unknown
): Promise<Partial<ContractInstance> & {
address: Address
}> {
async instantiate (args: { creator: Address, codeId: CodeId }):
Promise<ContractInstance & { address: Address }>
{
const { codeId, creator } = args
const address = randomBech32(this.prefix)
const code = this.uploads.get(codeId)
if (!code) {
throw new Error(`invalid code id ${codeId}`)
throw new Error(`invalid code id ${args.codeId}`)
}
code.instances.add(address)
this.instances.set(address, { address, codeId, creator })
return { address, codeId }
return new ContractInstance({ address, codeId }) as ContractInstance & { address: Address }
}

async execute (...args: unknown[]): Promise<unknown> {
Expand Down
7 changes: 3 additions & 4 deletions packages/cw/cw-bank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ type Connection = {
api: CosmWasmClient|Promise<CosmWasmClient>
}

export async function getBalance (
{ api }: Connection,
token: string,
address: Address
export async function fetchBalance (
{ api }: Connection,
balances: Parameters<Chain.Connection["fetchBalanceImpl"]>[0]
) {
api = await Promise.resolve(api)
if (!address) {
Expand Down
68 changes: 64 additions & 4 deletions packages/cw/cw-compute.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { CosmWasmClient, SigningCosmWasmClient } from '@hackbg/cosmjs-esm'
import { Deploy } from '@fadroma/agent'
import type { Address, CodeId, Chain, Message, Token, Core } from '@fadroma/agent'
import { Chain, Deploy } from '@fadroma/agent'
import type { Address, CodeId, Message, Token, Core } from '@fadroma/agent'
import { Amino } from '@hackbg/cosmjs-esm'
import type { CWConnection, CWAgent } from './cw-connection'

type Connection = {
chainId?: string,
Expand All @@ -16,6 +17,65 @@ export type SigningConnection = {
api: SigningCosmWasmClient|Promise<SigningCosmWasmClient>
}

export async function fetchCodeInfo (
conn: CWConnection,
args: Parameters<Chain.Connection["fetchCodeInfoImpl"]>[0]
):
Promise<Record<Deploy.CodeId, Deploy.UploadedCode>>
{
throw new Error('unimplemented!')
return {}
//const { ids = [] } = parameters || {}
//if (!ids || ids.length === 0) {
//return Compute.getCodes(this)
//} else if (ids.length === 1) {
//return Compute.getCodes(this, ids)
//} else {
//throw new Error('CWConnection.fetchCodeInfo({ ids: [multiple] }): unimplemented!')
//}
//protected override fetchCodesImpl () {
//return Compute.getCodes(this)
//}
//protected override fetchCodeIdImpl (address: Address): Promise<CodeId> {
//return getCodeId(this, address)
//}
//protected override fetchCodeHashOfCodeIdImpl (codeId: CodeId): Promise<CodeHash> {
//return Compute.getCodeHashOfCodeId(this, codeId)
//}
}

export async function fetchCodeInstances (
conn: CWConnection,
args: Parameters<Chain.Connection["fetchCodeInstancesImpl"]>[0]
):
Promise<Record<Deploy.CodeId, Record<Chain.Address, Chain.Contract>>>
{
throw new Error('unimplemented!')
return {}
//protected override fetchContractsByCodeIdImpl (id: CodeId): Promise<Iterable<{address: Address}>> {
//return Compute.getContractsByCodeId(this, id)
//}
}

export async function fetchContractInfo (
conn: CWConnection,
args: Parameters<Chain.Connection["fetchContractInfoImpl"]>[0]
):
Promise<{
[address in keyof typeof args["contracts"]]: InstanceType<typeof args["contracts"][address]>
}>
{
throw new Error('unimplemented!')
return {}
//return Compute.getCodeId(this, address)
//protected override fetchCodeHashOfAddressImpl (address: Address): Promise<CodeHash> {
//return Compute.getCodeHashOfAddress(this, address)
//}
//protected override fetchLabelImpl (address: Address): Promise<string> {
//return Compute.getLabel(this, address)
//}
}

export async function getCodes (
{ chainId, api }: Connection
) {
Expand Down Expand Up @@ -141,7 +201,7 @@ export async function instantiate (
options.initFee as Amino.StdFee || 'auto',
{ admin: address, funds: options.initSend, memo: options.initMemo }
)
return {
return new Deploy.ContractInstance({
codeId: options.codeId,
codeHash: options.codeHash,
label: options.label,
Expand All @@ -154,7 +214,7 @@ export async function instantiate (
initFee: options.initFee || 'auto',
initSend: options.initSend,
initMemo: options.initMemo
}
}) as Deploy.ContractInstance & { address: Address }
}

export async function execute (
Expand Down
Loading

0 comments on commit 9b7892f

Please sign in to comment.