Import
Copy import AndromedaClient from "@andromedaprotocol/andromeda.js"
Class
A helper class for interacting with the Andromeda ecosystem
Copy export default class AndromedaClient {
public signer : string = "" ;
private gasPrice ?: GasPrice ;
public chainClient ?: ChainClient ;
/**
* Instantiate all provided APIs
*/
public ado = new ADOAPI ( this );
public registry = new RegistryAPI ( this );
public adoDB = new ADODBAPI ( 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" );
}
Methods
connect
Connects to a new chain by endpoint.
Copy async connect (
endpoint: string ,
registryAddress: string ,
addressPrefix: string ,
signer ?: OfflineSigner | OfflineDirectSigner ,
options ?: SigningCosmWasmClientOptions
) {
delete this .chainClient;
this .gasPrice = options ?.gasPrice;
this .chainClient = createClient (addressPrefix);
await this . chainClient .connect (endpoint , signer , options);
await this .assignKeyAddresses (registryAddress);
}
assignKeyAddresses
Assigns key addresses to provided APIs.
Copy private async assignKeyAddresses (registryAddress: string) {
if ( ! registryAddress || registryAddress . length === 0 ) {
console .warn ( "No registry address provided" );
return ;
}
this . registry .address = registryAddress;
await this . factory .getAddressFromRegistry ( this .registry);
}
disconnect
Disconnects the assigned clients.
Copy disconnect () {
this .chainClient ! .disconnect ();
delete this .chainClient;
this .signer = "" ;
delete this .gasPrice;
this .registry = new RegistryAPI ( this );
this .adoDB = new ADODBAPI ( this );
}
isConnected
Getter method to indicate whether the client is currently connected.
Copy get isConnected () {
return isUndefined ( this .cosmWasmClient) || isUndefined ( this .queryClient);
}
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.
Copy async signAndBroadcast (
messages: EncodeObject[] ,
fee: Fee ,
memo ?: string
): Promise < DeliverTxResponse > {
this.preMessage();
return this.chainClient!.signAndBroadcast(messages , fee , memo);
}
Fee
Copy export type Fee = number | StdFee | "auto"
Check StdFee .
EncodeObject
Copy 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.
Copy async upload (code: Uint8Array , fee ?: Fee , memo ?: string) {
this .preMessage ();
return this .chainClient ! .upload (code , fee , memo);
}
execute
Wrapper function for CosmWasm execute . Execute the defined message.
Copy 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.
Copy 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 ,
});
}
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 .
Copy async queryContract< T = any >(address : string , query : Msg ) {
this .preMessage ();
return ( await this .chainClient ! .queryClient !! .queryContractSmart (
address ,
query
)) as T ;
}
Msg
Copy export type Msg = Record < string , unknown >;
migrate
Wrapper function to ComsWasm migrate .
Copy 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.
Copy 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.
Copy async estimateMigrateFee (address: string , codeId: number , msg: Msg) {
this .preMessage ();
return this .estimateFee ([
this .chainClient ! .encodeMigrateMessage (address , codeId , msg) ,
]);
}
simulateExecute
Estimates the gas cost of sending an execute transaction.
Copy 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.
Copy 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.
Copy 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.
Copy async simulateUpload (wasmByteCode: Uint8Array) {
return this . chainClient ?.simulateUpload (wasmByteCode);
}
estimateUploadFee
Estimates the fee cost of sending an upload transaction.
Copy async estimateUploadFee (wasmByteCode: Uint8Array) {
this .preMessage ();
return this .estimateFee ([
this .chainClient ! .encodeUploadMessage (wasmByteCode) ,
]);
}
calculateFee
Wrapped around cosmjs calculateFee using client's set gasPrice. Errors if no gas price provided.
Copy calculcateFee (gas: number) {
const gasPrice = this .gasPrice;
if ( ! gasPrice)
throw new Error (
"No gas prices provided for client. Cannot simulate Tx fee."
);
const multiplier = 1.3 ;
return calculateFee ( Math .round (gas * multiplier) , gasPrice);
}
estimateFee
Simulates provided messages and calculates an estimated fee.
Copy 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);
}
estimateExecuteFee
Estimates the fee cost of sending an execute transaction.
Copy 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.
Copy 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
);
}
getBalance
Gets the balance for a given address and denom. Defaults to the signing wallet address if none provided.
Copy async getBalance (denom: string , address ?: string) {
this .preMessage ();
const _address = address && address . length > 0 ? address : this .signer;
if ( ! _address || _address . length === 0 ) throw new Error ( "Invalid address" );
return this .chainClient ! .queryClient ! .getBalance (_address , denom);
}
getSentTxsByAddress
Gets all send transactions for a given address.
Copy async getSentTxsByAddress (addr: string) {
this .preMessage ();
return this .chainClient ! .queryClient ! ?.searchTx ({
tags : [{ key : "message.sender" , value : addr }] ,
});
}
getTx
Wrapper around the cosm.js client's getTx function.
Copy async getTx (hash: string) {
this .preMessage ();
return this .chainClient ! .queryClient ! .getTx (hash);
}
getTxsByContract
Gets all transactions sent to a contract.
Copy async getTxsByContract (addr: string) {
this .preMessage ();
return this .chainClient ! .queryClient ! ?.searchTx ({
tags : [{ key : "execute._contract_address" , value : addr }] ,
});
}
getBankTxsByAddress
Gets all bank messages sent to or from an address.
Copy async getBankTxsByAddress (addr: string) {
this .preMessage ();
return this .chainClient ! .queryClient ! ?.searchTx ({
sentFromOrTo : addr ,
});
}
getAllTxsByAddress
Queries all possible transactions for a given address.
Copy 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 ));
}
sendTokens
wrapper around the cosm.js client's sendTokens function. Send tokens to another address.
Copy 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
Copy 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;
};
Returns the Uint8Array.