Skip to content

Commit

Permalink
wip 30
Browse files Browse the repository at this point in the history
  • Loading branch information
egasimus committed Oct 31, 2023
1 parent 9de20f7 commit c435710
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 56 deletions.
23 changes: 5 additions & 18 deletions agent/base.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** Fadroma. Copyright (C) 2023 Hack.bg. License: GNU AGPLv3 or custom.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. **/
import { Error as BaseError } from '@hackbg/oops'
import { Error } from '@hackbg/oops'
import { Console, bold, colors } from '@hackbg/logs'
import type { Deployment } from './deploy'

Expand Down Expand Up @@ -79,22 +79,9 @@ export type Address = string
export type TxHash = string

/** Error kinds. */
class FadromaError extends BaseError {
/** Thrown when a required parameter is missing. */
static Missing: typeof FadromaError_Missing
}
class FadromaError extends Error {}

class FadromaError_Missing extends FadromaError.define(
'Missing', (msg='a required parameter was missing') => msg as string
) {
static Address = this.define('Address', () => 'no address')
static Name = this.define("Name", () => "no name")
static Uploader = this.define('Uploader', () => "no uploader")
static Workspace = this.define('Workspace', () => "no workspace")
export {
Console,
FadromaError as Error
}

export const Error = Object.assign(FadromaError, {
Missing: FadromaError_Missing,
})

export { Console }
10 changes: 5 additions & 5 deletions agent/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,16 +292,16 @@ export abstract class Agent {
contract = new UploadedCode({ codeId: contract })
}
if (isNaN(Number(contract.codeId))) {
throw new Error(`invalid code id: ${contract.codeId}`)
throw new Error(`can't instantiate contract with missing code id: ${contract.codeId}`)
}
if (!contract.codeId) {
throw new Error.Missing.CodeId()
throw new Error("can't instantiate contract without code id")
}
if (!options.label) {
throw new Error.Missing.Label()
throw new Error("can't instantiate contract without label")
}
if (!options.initMsg) {
throw new Error.Missing.InitMsg()
throw new Error("can't instantiate contract without init message")
}
const t0 = performance.now()
const result = await this.doInstantiate(contract.codeId, {
Expand Down Expand Up @@ -363,7 +363,7 @@ export abstract class Agent {
abstract getCodeHashOfCodeId (codeId: CodeId):
Promise<CodeHash>

abstract doQuery (contract: { address: Address }, message: Message):
protected abstract doQuery (contract: { address: Address }, message: Message):
Promise<unknown>

/** Send native tokens to 1 recipient. */
Expand Down
11 changes: 7 additions & 4 deletions agent/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ export class ContractClient {
/** Execute a query on the specified contract as the specified Agent. */
query <Q> (message: Message): Promise<Q> {
if (!this.agent) {
throw new Error.Missing.Agent(this.constructor?.name)
throw new Error("can't query contract without agent")
}
if (!this.contract.address) {
throw new Error.Missing.Address()
throw new Error("can't query contract without address")
}
return this.agent.query<Q>(
this.contract as ContractInstance & { address: Address }, message
Expand All @@ -44,10 +44,13 @@ export class ContractClient {
/** Execute a transaction on the specified contract as the specified Agent. */
execute (message: Message, options: Parameters<Agent["execute"]>[2] = {}): Promise<unknown> {
if (!this.agent) {
throw new Error.Missing.Agent(this.constructor?.name)
throw new Error("can't transact with contract without agent")
}
if (!this.agent.execute) {
throw new Error("can't transact with contract without authorizing the agent")
}
if (!this.contract.address) {
throw new Error.Missing.Address()
throw new Error("can't transact with contract without address")
}
return this.agent.execute(
this.contract as ContractInstance & { address: Address }, message, options
Expand Down
2 changes: 1 addition & 1 deletion connect/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const connectModes = {

// Support for OKP4:
OKP4Testnet: CW.OKP4.testnet,
OKP4Devnet: (...args: Parameters<typeof CW.OKP4.Agent.devnet>): CW.OKP4.Chain => {
OKP4Devnet: (...args: Parameters<typeof CW.OKP4.Agent.devnet>): CW.OKP4.Agent => {
throw new Error('Devnets are only available through @hackbg/fadroma')
},

Expand Down
15 changes: 7 additions & 8 deletions connect/cw/cw-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,12 @@ class CWAgent extends Agent {
}

protected async doUpload (data: Uint8Array): Promise<Partial<UploadedCode>> {
if (!this.address) throw new Error.Missing.Address()
if (!this.address) {
throw new CWError("can't upload contract without sender address")
}
if (!(this.api as SigningCosmWasmClient)?.instantiate) {
throw new CWError("can't upload contract without authorizing the agent")
}
const result = await this.api.upload(
this.address, data, this.fees?.upload || 'auto', "Uploaded by Fadroma"
)
Expand All @@ -151,12 +156,6 @@ class CWAgent extends Agent {
codeId: CodeId,
options: Parameters<Agent["doInstantiate"]>[1]
): Promise<Partial<ContractInstance>> {
if (!options.label) {
throw new CWError("can't instantiate contract without label")
}
if (!options.initMsg) {
throw new CWError("can't instantiate contract without init message")
}
if (!this.address) {
throw new CWError("can't instantiate contract without sender address")
}
Expand All @@ -167,7 +166,7 @@ class CWAgent extends Agent {
this.address!,
Number(codeId),
options.initMsg,
options.label,
options.label!,
options.initFee || 'auto',
{ admin: this.address, funds: options.initSend, memo: options.initMemo }
)
Expand Down
8 changes: 2 additions & 6 deletions connect/cw/okp4/okp4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,23 +82,20 @@ class OKP4Agent extends Agent {
/** Get clients for all Cognitarium instances,
* keyed by address. */
async cognitaria ({ map = true } = {}) {
const { api } = await this.ready
const ids = Object.values(cognitariumCodeIds)
return await this.getContractsById(Cognitarium, ids, map)
}

/** Get clients for all Objectarium instances,
* keyed by address. */
async objectaria ({ map = true } = {}) {
const { api } = await this.ready
const ids = Object.values(objectariumCodeIds)
return await this.getContractsById(Objectarium, ids, map)
}

/** Get clients for all Law Stone instances,
* keyed by address. */
async lawStones ({ map = true } = {}) {
const { api } = await this.ready
const ids = Object.values(lawStoneCodeIds)
return await this.getContractsById(LawStone, ids, map)
}
Expand All @@ -110,14 +107,13 @@ class OKP4Agent extends Agent {
): Promise<
typeof map extends true ? Map<Address, C> : Record<Address, C>
> {
const { api } = await this.ready
const chainId = this.chainId
const contracts = map ? new Map() : {}
for (const id of ids) {
const codeId = Number(id)
if (isNaN(codeId)) throw new Error('non-number code ID encountered')
const { checksum: codeHash } = await api.getCodeDetails(codeId)
const addresses = await api.getContracts(codeId)
const { checksum: codeHash } = await this.api.getCodeDetails(codeId)
const addresses = await this.api.getContracts(codeId)
for (const address of addresses) {
const contract = new Client(
{ address, codeHash, chainId, codeId: String(codeId) },
Expand Down
4 changes: 3 additions & 1 deletion connect/scrt/scrt-chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,9 @@ class ScrtAgent extends Agent {
}

async encrypt (codeHash: CodeHash, msg: Message) {
if (!codeHash) throw new Error.Missing.CodeHash()
if (!codeHash) {
throw new Error("can't encrypt message without code hash")
}
const { encryptionUtils } = this.api as any
const encrypted = await encryptionUtils.encrypt(codeHash, msg as object)
return base64.encode(encrypted)
Expand Down
8 changes: 6 additions & 2 deletions connect/scrt/scrt-mocknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -556,8 +556,12 @@ export class MocknetContract<V extends CW> {
const height = Math.floor(now/5000)
const time = Math.floor(now/1000)
const sent_funds: any[] = []
if (!this.address) throw new Error.Missing.Address()
if (!this.codeHash) throw new Error.Missing.CodeHash()
if (!this.address) {
throw new Error("can't run contract without address")
}
if (!this.codeHash) {
throw new Error("can't run contract without code hash")
}
const { address, codeHash } = this
if (this.cwVersion === '0.x') {
const block = { height, time, chain_id }
Expand Down
8 changes: 6 additions & 2 deletions ops/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ export abstract class LocalRustCompiler extends Compiler {
protected resolveSource (source: string|Partial<SourceCode>): Partial<SourceCode> {
if (typeof source === 'string') source = { crate: source }
let { crate, workspace = this.workspace, revision = 'HEAD' } = source
if (!crate) throw new Error.Missing.Crate()
if (!crate) {
throw new Error("missing crate name")
}
// If the `crate` field contains a slash, this is a crate path and not a crate name.
// Add the crate path to the workspace path, and set the real crate name.
if (source.crate && source.crate.includes(sep)) {
Expand Down Expand Up @@ -581,7 +583,9 @@ export class RawLocalRustCompiler extends LocalRustCompiler {
source.workspace ??= this.workspace
source.revision ??= HEAD
const { workspace, revision, crate } = source
if (!crate && !workspace) throw new Error.Missing.Crate()
if (!(crate || workspace)) {
throw new Error("missing crate name or workspace path")
}
const { env, tmpGit, tmpBuild } = this.getEnvAndTemp(source, workspace, revision)
// Run the build script as a subprocess
const location = await this.runBuild(source, env)
Expand Down
8 changes: 6 additions & 2 deletions ops/devnets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,12 @@ export class Devnet implements DevnetHandle {
this.log.debug('Creating...')
// ensure we have image and chain id
const image = await this.image
if (!this.image) throw new DevnetError.Missing.DevnetImage()
if (!this.chainId) throw new DevnetError.Missing.ChainId()
if (!this.image) {
throw new DevnetError("missing devnet container image")
}
if (!this.chainId) {
throw new DevnetError("can't create devnet without chain ID")
}
// if port is unspecified or taken, increment
this.port = await ports.getFreePort(this.port)
// create container
Expand Down
8 changes: 5 additions & 3 deletions ops/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,9 @@ export class Project extends CommandContext {
'export', `export current deployment to JSON`,
async (path?: string) => {
const deployment = await this.selectDeployment()
if (!deployment) throw new Error.Missing.Deployment()
if (!deployment) {
throw new Error("deployment not found")
}
if (!path) path = process.cwd()
// If passed a directory, generate file name
let file = $(path)
Expand All @@ -344,12 +346,12 @@ export class Project extends CommandContext {
contracts: Record<string, Partial<ContractInstance>> = {},
): InstanceType<typeof this.Deployment> {
if (!name) {
throw new Error.Missing.Name()
throw new Error("missing deployment name")
}
if (this.deployStore.has(name)) {
return this.Deployment.fromReceipt(this.deployStore.get(name)!)
} else {
throw new Error.Missing.Deployment()
throw new Error(`deployment not found: ${name}`)
}
}

Expand Down
16 changes: 12 additions & 4 deletions ops/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ export class JSONFileUploadStore extends UploadStore {
}

get (codeHash: CodeHash|{ codeHash: CodeHash }): UploadedCode|undefined {
if (typeof codeHash === 'object') codeHash = codeHash.codeHash
if (!codeHash) throw new Error.Missing.CodeHash()
if (typeof codeHash === 'object') {
codeHash = codeHash.codeHash
}
if (!codeHash) {
throw new Error("can't get upload info: missing code hash")
}
const receipt = this.dir.at(`${codeHash!.toLowerCase()}.json`).as(JSONFile<any>)
if (receipt.exists()) {
const uploaded = receipt.load()
Expand All @@ -53,8 +57,12 @@ export class JSONFileUploadStore extends UploadStore {
}

set (codeHash: CodeHash|{ codeHash: CodeHash }, value: Partial<UploadedCode>): this {
if (typeof codeHash === 'object') codeHash = codeHash.codeHash
if (!codeHash) throw new Error.Missing.CodeHash()
if (typeof codeHash === 'object') {
codeHash = codeHash.codeHash
}
if (!codeHash) {
throw new Error("can't set upload info: missing code hash")
}
const receipt = this.dir.at(`${codeHash.toLowerCase()}.json`).as(JSONFile<any>)
this.log('writing', receipt.shortPath)
receipt.save(super.get(codeHash)!.toReceipt())
Expand Down

0 comments on commit c435710

Please sign in to comment.