AndromedaClient
Import
import AndromedaClient from "@andromedaprotocol/andromeda.js"
Class
A helper class for interacting with the Andromeda ecosystem
export default class AndromedaClient {
public chainClient?: ChainClient;
/**
* Instantiate all provided APIs
*/
public ado = new ADOAPI(this);
public schema = new ADOSchemaAPI(this);
public os = new OperatingSystemAPI(this);
/**
* A pre-message hook to check that the client is connected and functioning
* @param signed Whether the message is signed
*/
private preMessage() {
if (!this.isConnected) throw new Error("Client not connected");
}
chainClient
Client used to interact with the chain, includes a query client when connected and a signing client when connected with a signer.
Methods
connect
Connects to a new chain by endpoint.
async connect(
endpoint: string,
kernelAddress: string,
addressPrefix: string,
signer?: OfflineSigner | OfflineDirectSigner,
// Only used for Cosmos Clients
options?: SigningCosmWasmClientOptions
) {
delete this.chainClient;
this.chainClient = createClient(addressPrefix);
await this.chainClient.connect(endpoint, signer, options);
await this.assignKeyAddresses(kernelAddress);
}
endpoint
string
The endpoint of the chain to connect to.
kernelAddress
string
The contract address of the kernel contract.
addressPrefix
string
The prefixo of the connecting address.
assignKeyAddresses
Assigns the kernel address and fetches the VFS and ADODB addresses.
private async assignKeyAddresses(kernelAddress: string) {
if (kernelAddress && kernelAddress.length > 0) {
await this.os.assignKernelAddress(kernelAddress);
}
}
kernelAddress
string
The address of the kernel contract to assign.
disconnect
Disconnects the assigned clients.
disconnect() {
this.chainClient!.disconnect();
delete this.chainClient;
this.os = new OperatingSystemAPI(this);
}
isConnected
Getter method to indicate whether the client is currently connected.
get isConnected() {
return !isUndefined(this.chainClient) && this.chainClient!.isConnected;
}
signAndBroadcast
Wrapper function for CosmWasm sign and broadcast. Creates a transaction with the given messages, fee and memo and then signs and broadcasts the transaction.
async signAndBroadcast(
messages: EncodeObject[],
fee: Fee,
memo?: string
): Promise<DeliverTxResponse> {
this.preMessage();
return this.chainClient!.signAndBroadcast(messages, fee, memo);
}
memo
string
optional memo to the transaction.
Fee
export type Fee = number | StdFee | "auto"
Check StdFee.
EncodeObject
export interface EncodeObject {
readonly typeUrl: string;
readonly value: any;
}
upload
Wrapper function for CosmWasm upload. Uploads code and returns a receipt, including the code ID.
async upload(code: Uint8Array, fee?: Fee, memo?: string) {
this.preMessage();
return this.chainClient!.upload(code, fee, memo);
}
code
Uint8Array
The code to upload.
memo
string
Optional memo to attatch.
execute
Wrapper function for CosmWasm execute. Execute the defined message.
async execute(
contractAddress: string,
msg: Msg,
fee?: Fee,
memo?: string,
funds?: readonly Coin[]
) {
this.preMessage();
return await this.chainClient!.execute(
contractAddress,
msg,
fee,
memo,
funds
);
}
instantiate
Wrapper function for CosmWasm instantiate. Instantiates the defined message.
async instantiate(
codeId: number,
msg: Msg,
label: string,
fee?: Fee,
options?: InstantiateOptions
) {
this.preMessage();
return await this.chainClient!.instantiate(codeId, msg, label, fee, {
admin: this.chainClient!.signer,
...options,
});
}
codeId
number
The code ID of the contract to instantiate.
label
string
The label attached to instantiation.
fee
string
The fee to pay. Defaults to auto if not specified.
options
Options for the instantiate call. Includes optional admin, funds, and memo.
queryContract
Makes a smart query on the contract, returns the parsed JSON document. Promise is rejected when contract does not exist, for invalid query format, and for invalid response format.
Wrapper function for CosmWasm query.
async queryContract<T = any>(address: string, query: Msg) {
this.preMessage();
return (await this.chainClient!.queryClient!!.queryContractSmart(
address,
query
)) as T;
}
address
string
The address of the contract to query.
Msg
export type Msg = Record<string, unknown>;
migrate
Wrapper function to ComsWasm migrate.
async migrate(
contractAddress: string,
codeId: number,
msg: Msg,
fee?: Fee,
memo?: string
) {
this.preMessage();
return await this.chainClient!.migrate(
contractAddress,
codeId,
msg,
fee,
memo
);
}
simulateMigrate
Estimates the gas cost of sending a migrate transaction.
async simulateMigrate(
address: string,
codeId: number,
msg: Msg,
fee?: StdFee
) {
this.preMessage();
return this.simulateMsgs(
[this.chainClient!.encodeMigrateMessage(address, codeId, msg)],
fee
);
}
estimateMigrateFee
Estimates the fee cost of sending a migrate transaction.
async estimateMigrateFee(address: string, codeId: number, msg: Msg) {
this.preMessage();
return this.estimateFee([
this.chainClient!.encodeMigrateMessage(address, codeId, msg),
]);
}
address
string
The contract address to migrate.
codeId
number
The code Id to migrate to.
simulateExecute
Estimates the gas cost of sending an execute transaction.
async simulateExecute(
address: string,
msg: Msg,
funds: Coin[],
fee?: StdFee,
memo: string = ""
) {
this.preMessage();
return this.simulateMsgs(
[this.chainClient!.encodeExecuteMsg(address, msg, funds)],
fee,
memo
);
}
simulateMsgs
Simulates provided messages returning an estimated gas cost.
async simulateMsgs(
msgs: readonly EncodeObject[],
fee?: StdFee,
memo?: string
) {
const gas = await this.chainClient?.simulateMulti(msgs, fee, memo);
return gas;
}
simulateInstantiate
Estimates the gas cost of sending an instantiate transaction and returns it.
async simulateInstantiate(
codeId: number,
msg: Msg,
label: string,
fee?: StdFee,
memo?: string
) {
this.preMessage();
console.log(msg);
return this.simulateMsgs(
[this.chainClient!.encodeInstantiateMsg(codeId, msg, label)],
fee,
memo
);
}
simulateUpload
Estimates the gas cost of sending an upload transaction.
async simulateUpload(wasmByteCode: Uint8Array) {
return this.chainClient?.simulateUpload(wasmByteCode);
}
wasmByteCode
Uint8Array
The wasm code to simulate uploading.
estimateUploadFee
Estimates the fee cost of sending an upload transaction.
async estimateUploadFee(wasmByteCode: Uint8Array) {
this.preMessage();
return this.estimateFee([
this.chainClient!.encodeUploadMessage(wasmByteCode),
]);
}
wasmByteCode
Uint8Array
The wasm code to simulate uploading.
calculateFee
Wrapped around cosmjs calculateFee using client's set gasPrice. Errors if no gas price provided.
calculcateFee(gas: number) {
const gasPrice = this.chainClient?.gasPrice;
if (!gasPrice)
throw new Error(
"No gas prices provided for client. Cannot simulate Tx fee."
);
const multiplier = 1.3; // Unsure why this is necessary but is added during simulateTx in cosmjs
return calculateFee(Math.round(gas * multiplier), gasPrice);
}
gas
number
The amount of gas.
estimateFee
Simulates provided messages and calculates an estimated fee.
async estimateFee(
msgs: readonly EncodeObject[],
fee?: StdFee,
memo?: string
) {
const gas = await this.simulateMsgs(msgs, fee, memo);
if (!gas) {
throw new Error("Could not simulate transaction");
}
return this.calculcateFee(gas);
}
msgs
EncodeObject[]
The messages to estimate the fee for.
memo
string
Optional memo to attach.
estimateExecuteFee
Estimates the fee cost of sending an execute transaction.
async estimateExecuteFee(
address: string,
msg: Msg,
funds: Coin[],
fee?: StdFee,
memo: string = ""
) {
this.preMessage();
return this.estimateFee(
[this.chainClient!.encodeExecuteMsg(address, msg, funds)],
fee,
memo
);
}
The fields are the same as in execute but will return an estimate of the fees instead of executing the message.
estimateInstantiationFee
Estimates the fee cost of sending an instantiate transaction and returns it.
async estimateInstantiationFee(
codeId: number,
msg: Msg,
label: string,
fee?: StdFee,
memo?: string
) {
this.preMessage();
return this.estimateFee(
[this.chainClient!.encodeInstantiateMsg(codeId, msg, label)],
fee,
memo
);
}
codeId
number
The code ID of the contract to instantiate.
label
string
The label attached to instantiation
memo
string
Optional memo to attach.
getBalance
Gets the balance for a given address and denom. Defaults to the signing wallet address if none provided.
async getBalance(denom: string, address?: string) {
this.preMessage();
const _address =
address && address.length > 0 ? address : this.chainClient!.signer;
if (!_address || _address.length === 0) throw new Error("Invalid address");
return this.chainClient!.queryClient!.getBalance(_address, denom);
}
denom
string
The denom to check the balance for.
address
string
The address to check the balance for. If not specified, the address of the connected signer is used.
getSentTxsByAddress
Gets all send transactions for a given address.
async getSentTxsByAddress(addr: string) {
this.preMessage();
return this.chainClient!.queryClient!?.searchTx([{ key: "message.sender", value: addr }]);
}
addr
string
The address to get the send transactions for.
getTx
Wrapper around the cosm.js client's getTx function.
async getTx(hash: string) {
this.preMessage();
return this.chainClient!.queryClient!.getTx(hash);
}
hash
string
The tx hash.
getTxsByContract
Gets all transactions sent to a contract.
async getTxsByContract(addr: string) {
this.preMessage();
return this.chainClient!.queryClient!?.searchTx({
tags: [{ key: "execute._contract_address", value: addr }],
});
}
addr
string
The contract address to check transactions for.
getBankTxsByAddress
Gets all bank messages sent to or from an address.
async getBankTxsByAddress(addr: string) {
this.preMessage();
const sentQuery = `message.module='bank' AND transfer.sender='${addr}'`;
const receivedQuery = `message.module='bank' AND transfer.recipient='${addr}'`;
const [sent, received] = await Promise.all(
[sentQuery, receivedQuery].map((rawQuery) => this.chainClient!.queryClient!?.searchTx(rawQuery)),
);
const sentHashes = sent.map((t) => t.hash);
return [...sent, ...received.filter((t) => !sentHashes.includes(t.hash))];
};
addr
string
The address to check the bank messages for.
getAllTxsByAddress
Queries all possible transactions for a given address.
async getAllTxsByAddress(addr: string) {
const sentTxs = await this.getSentTxsByAddress(addr);
const contractTxs = await this.getTxsByContract(addr);
const bankTxs = await this.getBankTxsByAddress(addr);
return [
...(sentTxs ?? []),
...(contractTxs ?? []),
...(bankTxs ?? []),
].sort((txA, txB) => (txA.height < txB.height ? 1 : -1));
}
}
addr
string
The address to get all the transactions for.
sendTokens
wrapper around the cosm.js client's sendTokens function. Send tokens to another address.
async sendTokens(
receivingAddress: string,
amount: readonly Coin[],
fee?: Fee,
memo?: string
) {
this.preMessage();
return this.chainClient?.sendTokens(receivingAddress, amount, fee, memo);
}
Helper Function
JsonToArray
Helper function to convert JSON to Uint8Array
const JsonToArray = function (json: Record<string, any>) {
var str = JSON.stringify(json, null, 0);
var ret = new Uint8Array(str.length);
for (var i = 0; i < str.length; i++) {
ret[i] = str.charCodeAt(i);
}
return ret;
};
json
Record<string, any>
JSON object to convert to Uint8Array
Returns the Uint8Array.
Last updated