Skip to content

Commit

Permalink
wip: refactor(agent,cw,scrt): 59 type checks left 🤞
Browse files Browse the repository at this point in the history
  • Loading branch information
egasimus committed May 6, 2024
1 parent 9b7892f commit 78c54fe
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 82 deletions.
12 changes: 8 additions & 4 deletions fadroma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ export default function main (...args: any) {
(...units: string[]) => getProject().getDeployment().then(async deployment=>deployment.upload({
compiler: await getCompiler(),
uploadStore: getUploadStore(),
uploader: getConnection(),
uploader: getAgent(),
units
})))
.addCommand(
{name: 'reupload', info: 'reupload the project or specific contracts from it', args: ''},
(...units: string[]) => getProject().getDeployment().then(async deployment=>deployment.upload({
compiler: await getCompiler(),
uploadStore: getUploadStore(),
uploader: getConnection(),
uploader: getAgent(),
reupload: true,
units,
})))
Expand All @@ -80,7 +80,7 @@ export default function main (...args: any) {
compiler: await getCompiler(),
uploadStore: getUploadStore(),
deployStore: getDeployStore(),
deployer: getConnection(),
deployer: getAgent(),
units
})))
.addCommand(
Expand All @@ -89,7 +89,7 @@ export default function main (...args: any) {
compiler: await getCompiler(),
uploadStore: getUploadStore(),
deployStore: getDeployStore(),
deployer: getConnection(),
deployer: getAgent(),
redeploy: true,
units,
})))
Expand Down Expand Up @@ -123,6 +123,10 @@ export function getConnection (): Chain.Connection {
throw new Error('not implemented')
}

export function getAgent (): Chain.Agent {
throw new Error('not implemented')
}

export function getCompiler (pkg = "@fadroma/compile"): Promise<Program.Compiler> {
return import(pkg).catch(e=>{
console.error(
Expand Down
44 changes: 33 additions & 11 deletions fixtures/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,18 @@ export async function testConnectionWithBackend <
const uploadFee = Connection.gas(10000000).asFee()
const initFee = Connection.gas(10000000).asFee()
const execFee = Connection.gas(10000000).asFee()

const [alice, bob] = await Promise.all([backend.connect('Alice'), backend.connect('Bob')])
//ok(alice.identity.address && bob.identity?.address)
await alice.height
const [aliceBalance, bobBalance] = await Promise.all([alice.balance, bob.balance])

ok(alice.address && bob.address)

await alice.connection.height

const [aliceBalance, bobBalance] = await Promise.all([
alice.fetchBalance(),
bob.fetchBalance()
])

const guest = await backend.connect({
name: 'Guest',
mnemonic: [
Expand All @@ -103,19 +111,33 @@ export async function testConnectionWithBackend <
'angry tiny foil prosper water news'
].join(' ')
} as any)
equal((await guest.balance)??'0', '0')

equal((await guest.fetchBalance())??'0', '0')

await alice.send(guest, [Connection.gas(1)], { sendFee })
equal(await guest.balance, '1')

equal(await guest.fetchBalance(), '1')

await bob.send(guest, [Connection.gas(11)], { sendFee })
equal(await guest.balance, '12')

equal(await guest.fetchBalance(), '12')

const uploaded = await alice.upload(code)
equal(Object.keys(await bob.getCodes()).length, 1)
equal(await bob.getCodeHashOfCodeId(uploaded.codeId), uploaded.codeHash)
rejects(()=>bob.getCodeHashOfCodeId('missing'))

equal(Object.keys(await bob.connection.fetchCodeInfo()).length, 1)

equal(await bob.connection.fetchCodeInfo(uploaded.codeId), uploaded.codeHash)

rejects(()=>bob.connection.fetchCodeInfo('missing'))

const label = 'my-contract-label'

const instance = await bob.instantiate(uploaded, { label, initMsg, initFee })
equal(await guest.getCodeHashOfAddress(instance.address), uploaded.codeHash)

equal(await guest.connection.fetchContractInfo(instance.address), uploaded.codeHash)

const txResult = await alice.execute(instance, null as any, { execFee })
const qResult = await alice.query(instance, null as any)

const qResult = await alice.connection.query(instance, null as any)
return { backend, alice, bob, guest }
}
58 changes: 23 additions & 35 deletions packages/agent/chain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,58 +19,48 @@ export default new Suite([

export async function testHeight () {
const connection = new Stub.StubConnection()
assert(
await connection.height)
assert(
await connection.nextBlock)
assert(await connection.height)
assert(await connection.nextBlock)
Object.defineProperty(connection, 'height', { configurable: true, get () {
return Promise.resolve('NaN')
} })
assert.equal(
await connection.nextBlock, NaN)
assert.equal(await connection.nextBlock, NaN)
Object.defineProperty(connection, 'height', { configurable: true, get () {
Object.defineProperty(connection, 'height', { configurable: true, get () {
throw new Error('yeet')
} })
return Promise.resolve(0)
} })
assert.rejects(
()=>connection.nextBlock)
assert(
await connection.query('', {}))
assert.rejects(()=>connection.nextBlock)
assert(await connection.query('', {}))
}

export async function testCodes () {

const backend = new Stub.StubBackend({})
backend.uploads.set("123", { codeHash: "abc", codeData: new Uint8Array() } as any)
backend.instances.set("stub1abc", {
codeId: "123",
address: 'stub1instancefoo',
creator: 'stub1instancefoo'
initBy: 'stub1instancefoo'
})

const connection = new Stub.StubConnection({ backend })
assert.equal(
await connection.getCodeId('stub1abc'), "123")
assert.equal(
await connection.getCodeHashOfAddress('stub1abc'), "abc")
assert.equal(
await connection.getCodeHashOfCodeId('123'), "abc")

const { codeId, codeHash } = await connection.fetchContractInfo('stub1abs')
assert.equal(codeId, "123")
assert.equal(codeHash, "abc")
assert.equal((await connection.fetchCodeInfo('123')).codeHash, "abc")
}

export async function testAuth () {
throws(()=>new Identity().sign(''))
const identity = new Identity({ name: 'foo', address: 'foo1bar' })
const connection = new Stub.StubConnection({ identity })
const connection = new Stub.StubConnection().authenticate(identity)
//assert.equal(connection[Symbol.toStringTag], 'stub (mocknet): testing1')
assert(connection instanceof Stub.StubConnection)
assert(connection.identity?.address)
assert(connection.identity?.name)
connection.height
connection.nextBlock
await connection.query('', {})
connection.connection.height
connection.connection.nextBlock
await connection.connection.query('', {})
await connection.send('x', [])
//await connection.sendMany([])

Expand All @@ -84,10 +74,10 @@ export async function testAuth () {
rejects(()=>connection.instantiate('1', { label: 'foo' }))
rejects(()=>connection.instantiate('1', { initMsg: {} }))

await connection.getContractsByCodeId('1')
rejects(connection.getContractsByCodeIds(null as any))
await connection.getContractsByCodeIds(['1', '2'])
await connection.getContractsByCodeIds({'1': Contract, '2': Contract})
await connection.connection.fetchCodeInstances('1')
rejects(connection.connection.fetchCodeInstances(null as any))
await connection.connection.fetchCodeInstances(['1', '2'])
await connection.connection.fetchCodeInstances({'1': Contract, '2': Contract})

await connection.execute('stub', {}, {})
await connection.execute('stub', 'method', {})
Expand All @@ -106,7 +96,7 @@ export async function testAuth () {
}

export async function testBatch () {
const connection = new Stub.StubConnection({ identity: new Identity() })
const connection = new Stub.StubConnection().authenticate(new Identity())
const batch = connection.batch()

Check failure on line 100 in packages/agent/chain.test.ts

View workflow job for this annotation

GitHub Actions / PNPM CI

Property 'batch' does not exist on type 'StubAgent'.
.upload({})
.upload({})
Expand All @@ -121,15 +111,13 @@ export async function testBatch () {
export async function testClient () {
const instance = { address: 'addr', codeHash: 'code-hash-stub', codeId: '100' }
const connection = new Stub.StubConnection()
const client = connection.getContract(instance)
const client = await connection.fetchContractInfo('addr')
assert.equal(client.connection, connection)
assert.equal(client.instance, instance)
assert.equal(client.address, 'addr')
await client.query({foo: 'bar'})
await client.execute({foo: 'bar'})
await connection.getContract('addr')

assert(new Contract('addr'))
assert(new Contract(new ContractInstance({ address: 'addr' })))
await connection.fetchContractInfo('addr')
assert(new Contract({ address: 'addr' }))
assert.throws(()=>new Contract({}).query({}))
assert.throws(()=>new Contract({ connection }).query({}))
assert.throws(()=>new Contract({}).execute({}))
Expand Down
45 changes: 23 additions & 22 deletions packages/agent/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,10 +337,10 @@ export abstract class Connection extends Endpoint {
fetchCodeInfo ():
Promise<Record<Deploy.CodeId, Deploy.UploadedCode>>
/** Fetch info about a single code ID. */
fetchCodeInfo (codeId: Deploy.CodeId, options: { parallel?: boolean }):
fetchCodeInfo (codeId: Deploy.CodeId, options?: { parallel?: boolean }):
Promise<Deploy.UploadedCode>
/** Fetch info about multiple code IDs. */
fetchCodeInfo (codeIds: Iterable<Deploy.CodeId>, options: { parallel?: boolean }):
fetchCodeInfo (codeIds: Iterable<Deploy.CodeId>, options?: { parallel?: boolean }):
Promise<Record<Deploy.CodeId, Deploy.UploadedCode>>

fetchCodeInfo (...args: unknown[]): Promise<unknown> {
Expand Down Expand Up @@ -514,7 +514,7 @@ export abstract class Connection extends Endpoint {
if (typeof args[0] === 'string') {
this.log.debug(`Fetching contract ${args[0]}`)
const contracts = await timed(
()=>this.fetchContractInfoImpl({ addresses: [args[0] as Address] }),
()=>this.fetchContractInfoImpl({ contracts: [args[0] as Address] }),

Check failure on line 517 in packages/agent/chain.ts

View workflow job for this annotation

GitHub Actions / PNPM CI

Type 'string' is not assignable to type 'typeof Contract'.
({ elapsed }) => this.log.debug(
`Fetched in ${bold(elapsed)}: contract ${args[0]}`
))
Expand All @@ -529,15 +529,15 @@ export abstract class Connection extends Endpoint {
if (args[0][Symbol.iterator]) {
const addresses = args[0] as Address[]
this.log.debug(`Fetching ${addresses.length} contracts`)
const contracts = await timed(
()=>this.fetchContractInfoImpl({ addresses, parallel }),
const results = await timed(
()=>this.fetchContractInfoImpl({ contracts, parallel }),

Check failure on line 533 in packages/agent/chain.ts

View workflow job for this annotation

GitHub Actions / PNPM CI

Cannot find name 'contracts'. Did you mean 'Contract'?
({ elapsed }) => this.log.debug(
`Fetched in ${bold(elapsed)}: ${addresses.length} contracts`
))
if (custom) {
return addresses.map(address=>new $C(contracts[address]))
return addresses.map(address=>new $C(results[address]))
} else {
return addresses.map(address=>contracts[address])
return addresses.map(address=>results[address])
}
}

Expand Down Expand Up @@ -618,7 +618,7 @@ export abstract class Agent extends Logged {
return this.identity?.address
}

async fetchBalance (tokens?: string[]|string): Promise<void> {
async fetchBalance (tokens?: string[]|string): Promise<Record<string, Token.Uint128>> {
throw new Error("unimplemented!")
}

Expand Down Expand Up @@ -843,25 +843,28 @@ export class Contract extends Logged {
constructor (properties: Partial<Contract>) {
super((typeof properties === 'string')?{}:properties)
if (typeof properties === 'string') {
properties = { instance: { address: properties } }
}
assign(this, properties, [ 'instance', 'connection' ])
let { instance, connection } = properties
this.instance = instance as Partial<Deploy.ContractInstance>
this.connection = connection
properties = { address: properties }
}
assign(this, properties, [
'connection',
'agent',
'codeId',
'codeHash',
'address',
'label',
'initBy'
])
}

/** Execute a query on the specified instance as the specified Connection. */
query <Q> (message: Message): Promise<Q> {
if (!this.connection) {
throw new Error("can't query instance without connection")
}
if (!this.instance?.address) {
if (!this.address) {
throw new Error("can't query instance without address")
}
return this.connection.query<Q>(
this.instance as Deploy.ContractInstance & { address: Address }, message
)
return this.connection.query<Q>(this as { address }, message)
}

/** Execute a transaction on the specified instance as the specified Connection. */
Expand All @@ -872,11 +875,9 @@ export class Contract extends Logged {
if (!this.agent?.execute) {
throw new Error("can't transact with instance without authorizing the connection")
}
if (!this.instance?.address) {
if (!this.address) {
throw new Error("can't transact with instance without address")
}
return this.agent?.execute(
this.instance as Deploy.ContractInstance & { address: Address }, message, options
)
return this.agent?.execute(this as { address }, message, options)
}
}
Loading

0 comments on commit 78c54fe

Please sign in to comment.