Skip to content

Commit

Permalink
tidying
Browse files Browse the repository at this point in the history
  • Loading branch information
karnthis committed Oct 16, 2024
1 parent 323f59e commit 44c1fa0
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 97 deletions.
52 changes: 29 additions & 23 deletions src/classes/clientHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
IWrappedEncodeObject,
} from '@/interfaces'
import { TSockets, TSocketSet } from '@/types'
import { Coin, DeliverTxResponse, StdFee } from '@cosmjs/stargate'
import { DeliverTxResponse, StdFee } from '@cosmjs/stargate'

export class ClientHandler implements IClientHandler {
protected readonly jklQuery: TJackalQueryClient
Expand Down Expand Up @@ -278,7 +278,8 @@ export class ClientHandler implements IClientHandler {

/**
* Create Wasm Handler session, defaults to Archway.
* @returns {Promise<IWasmHandler>}
* @param {IWasmDetails} [details]
* @returns {Promise<IStorageHandler>}
*/
async createWasmStorageHandler (details: IWasmDetails = {}): Promise<IStorageHandler> {
try {
Expand All @@ -289,20 +290,20 @@ export class ClientHandler implements IClientHandler {
} = details
this.myCosmwasm = await WasmHandler.init(this)
const ica = await this.myCosmwasm.getICAContractAddress(contract).catch(err => {
console.warn("can't get ica", err)
console.warn('can\'t get ica', err)
})
console.log("ICA: ", ica)
console.log('ICA: ', ica)
if (ica) {
console.log("Set ICA correctly")
console.log('Set ICA correctly')
this.myContractAddress = ica
} else {
console.log("Failed to set ICA")
console.log('Failed to set ICA')
await this.myCosmwasm.instantiateICA(
contract,
connIdA,
connIdB,
)
await new Promise(r => setTimeout(r, 5000));
await new Promise(r => setTimeout(r, 5000))
this.myContractAddress = await this.myCosmwasm.getICAContractAddress(contract)
}
console.log(this.myContractAddress)
Expand All @@ -312,9 +313,9 @@ export class ClientHandler implements IClientHandler {
const state = await this.myCosmwasm.getContractChannelState(
this.myContractAddress,
)
console.log("State: ", state)
console.log('State: ', state)
if (state === 'STATE_CLOSED') {
console.log("needs to re-open channel")
console.log('needs to re-open channel')
await this.myCosmwasm.reOpenChannel(
contract,
connIdA,
Expand Down Expand Up @@ -458,23 +459,30 @@ export class ClientHandler implements IClientHandler {
return this.getJackalNetworkBalance(this.getICAJackalAddress())
}

async ibcSend (address: string, amount: Coin, sourceChannel: string): Promise<DeliverTxResponse> {
/**
*
* @param {string} address
* @param {DCoin} amount
* @param {string} sourceChannel
* @returns {Promise<DeliverTxResponse>}
*/
async ibcSend (address: string, amount: DCoin, sourceChannel: string): Promise<DeliverTxResponse> {
if (!this.hostSigner) {
throw new Error(signerNotEnabled('ClientHandler', 'ibcSend'))
}


const fee: Coin = {amount: "35774392000000000", denom: "aarch"}
const f: StdFee = {amount: [fee], gas: "200000"}
try {
return await this.hostSigner.sendIbcTokens(this.hostAddress, address, amount, "transfer", sourceChannel, undefined, Date.now() * 1000 * 1000 + 2 * 60 * 60 * 1000 * 1000 * 1000, f, undefined)
const fee: DCoin = { amount: '35774392000000000', denom: 'aarch' }
const standardFee: StdFee = { amount: [fee], gas: '200000' }

return await this.hostSigner.sendIbcTokens(this.hostAddress, address, amount, 'transfer', sourceChannel, undefined, Date.now() * 1000 * 1000 + 2 * 60 * 60 * 1000 * 1000 * 1000, standardFee, undefined)
} catch (err) {
throw warnError('clientHandler ibcSend()', err)
}
}

/**
*
* @param {string} address
* @returns {Promise<DCoin>}
*/
async getJackalNetworkBalance (address: string): Promise<DCoin> {
Expand All @@ -483,7 +491,7 @@ export class ClientHandler implements IClientHandler {
}
try {
const res = await this.jklQuery.queries.bank.balance({
address: address,
address,
denom: 'ujkl',
})
return res.balance as DCoin
Expand All @@ -494,18 +502,16 @@ export class ClientHandler implements IClientHandler {

/**
*
* @param {string} address
* @param {string} denom
* @returns {Promise<DCoin>}
*/
async getHostNetworkBalance (address: string, denom: string): Promise<DCoin> {
if (!this.jklSigner) {
throw new Error(signerNotEnabled('ClientHandler', 'getHostNetworkBalance'))
}
if (!this.hostQuery) {
throw new Error(signerNotEnabled('ClientHandler', 'getHostNetworkBalance'))
}
try {
const res = await this.hostQuery.getBalance(address,denom)
return res
return await this.hostQuery.getBalance(address, denom)
} catch (err) {
throw warnError('clientHandler getHostNetworkBalance()', err)
}
Expand Down Expand Up @@ -548,7 +554,7 @@ export class ClientHandler implements IClientHandler {
* Returns true if ICA address has been set by wasm signer.
* @returns {boolean}
*/
wasmIsConnected(): boolean {
wasmIsConnected (): boolean {
return this.getICAJackalAddress() !== this.jklAddress
}

Expand Down Expand Up @@ -621,8 +627,8 @@ export class ClientHandler implements IClientHandler {
events,
msgs,
this.myIcaAddress || this.hostAddress,
queryOverride,
socketOverrides,
queryOverride,
)
console.log('connectionBundles:', connectionBundles)

Expand Down
2 changes: 1 addition & 1 deletion src/classes/encodingHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ export class EncodingHandler {
protected encodePostKey (key: string): DEncodeObject {
const forKey: DMsgPostKey = {
creator: this.jackalClient.getICAJackalAddress(),
key: key,
key,
}
return this.jackalSigner.txLibrary.fileTree.msgPostKey(forKey)
}
Expand Down
2 changes: 1 addition & 1 deletion src/classes/storageHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1517,7 +1517,7 @@ export class StorageHandler extends EncodingHandler implements IStorageHandler {
// console.log(providers)
return await this.findProviderIps(providers)
} catch (err) {
throw warnError('storageHandler loadProvidersFromChain()', err)
throw warnError('storageHandler getAllProviders()', err)
}
}

Expand Down
130 changes: 66 additions & 64 deletions src/classes/wasmHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,21 @@ export class WasmHandler extends EncodingHandler implements IWasmHandler {
* @returns {Promise<IWasmHandler>} - Instance of WasmHandler.
*/
static async init (client: IClientHandler): Promise<IWasmHandler> {
const jackalSigner = client.getJackalSigner()
if (!jackalSigner) {
throw new Error(signerNotEnabled('WasmHandler', 'init'))
}
const hostSigner = client.getHostSigner()
if (!hostSigner) {
throw new Error(signerNotEnabled('WasmHandler', 'init'))
try {
const jackalSigner = client.getJackalSigner()
if (!jackalSigner) {
throw new Error(signerNotEnabled('WasmHandler', 'init'))
}
const hostSigner = client.getHostSigner()
if (!hostSigner) {
throw new Error(signerNotEnabled('WasmHandler', 'init'))
}
let dummyKey = await stringToShaHex('')
const keyPair = PrivateKey.fromHex(dummyKey)
return new WasmHandler(client, jackalSigner, hostSigner, keyPair)
} catch (err) {
throw warnError('wasmHandler init()', err)
}
let dummyKey = await stringToShaHex('')
const keyPair = PrivateKey.fromHex(dummyKey)
return new WasmHandler(client, jackalSigner, hostSigner, keyPair)
}

/**
Expand All @@ -52,18 +56,17 @@ export class WasmHandler extends EncodingHandler implements IWasmHandler {
async instantiateICA (
contractAddress: string,
connectionIdA: string,
connectionIdB: string
connectionIdB: string,
): Promise<DDeliverTxResponse> {
try {

const msg = {
create_outpost: {
channel_open_init_options: {
connection_id: connectionIdA,
counterparty_connection_id: connectionIdB,
tx_encoding: "proto3"
}
}
tx_encoding: 'proto3',
},
},
}

const eo = this.jackalClient.getTxs().cosmwasm.msgExecuteContract({
Expand All @@ -75,28 +78,34 @@ export class WasmHandler extends EncodingHandler implements IWasmHandler {
const wrapped: IWrappedEncodeObject = { encodedObject: eo, modifier: 0 }

const postBroadcast =
//{queryOverride: `execute._contract_address = '${contractAddress}'`}
await this.jackalClient.broadcastAndMonitorMsgs(wrapped, {queryOverride: `message.action = '/cosmwasm.wasm.v1.MsgExecuteContract' AND message.sender = '${this.hostAddress}'`})
await this.jackalClient.broadcastAndMonitorMsgs(wrapped, { queryOverride: `message.action = '/cosmwasm.wasm.v1.MsgExecuteContract' AND message.sender = '${this.hostAddress}'` })
return postBroadcast.txResponse
} catch (err) {
throw warnError('wasmHandler instantiateICA()', err)
}
}

/**
*
* @param {string} contractAddress
* @param {string} connectionIdA
* @param {string} connectionIdB
* @returns {Promise<DDeliverTxResponse>}
*/
async reOpenChannel (
contractAddress: string,
connectionIdA: string,
connectionIdB: string
connectionIdB: string,
): Promise<DDeliverTxResponse> {
try {
const msg = {
create_channel: {
channel_open_init_options: {
connection_id: connectionIdA,
counterparty_connection_id: connectionIdB,
tx_encoding: "proto3"
}
}
tx_encoding: 'proto3',
},
},
}

const eo = this.jackalClient.getTxs().cosmwasm.msgExecuteContract({
Expand All @@ -106,9 +115,8 @@ export class WasmHandler extends EncodingHandler implements IWasmHandler {
sender: this.jackalClient.getHostAddress(),
})
const wrapped: IWrappedEncodeObject = { encodedObject: eo, modifier: 0 }

const postBroadcast =
await this.jackalClient.broadcastAndMonitorMsgs(wrapped, {queryOverride: `execute._contract_address = '${contractAddress}'`})
await this.jackalClient.broadcastAndMonitorMsgs(wrapped, { queryOverride: `execute._contract_address = '${contractAddress}'` })
return postBroadcast.txResponse
} catch (err) {
throw warnError('wasmHandler reOpenChannel()', err)
Expand All @@ -122,28 +130,20 @@ export class WasmHandler extends EncodingHandler implements IWasmHandler {
*/
async getICAContractAddress (contractAddress: string): Promise<string> {
try {

const query = {
get_user_outpost_address: {
user_address: this.hostAddress,
},
}

const q = stringToUint8Array(JSON.stringify(query))


const uintQuery = stringToUint8Array(JSON.stringify(query))
const req: DQuerySmartContractStateRequest = {
address: contractAddress,
queryData: q,
queryData: uintQuery,
}

const state =
await this.hostSigner.queries.cosmwasm.smartContractState(req)

const uint8Array = state.data instanceof Uint8Array ? state.data : new Uint8Array(state.data);

const uint8Array = state.data instanceof Uint8Array ? state.data : new Uint8Array(state.data)
return uintArrayToString(uint8Array).replaceAll('"', '')

} catch (err) {
throw warnError('wasmHandler getICAContractAddress()', err)
}
Expand All @@ -169,51 +169,53 @@ export class WasmHandler extends EncodingHandler implements IWasmHandler {
* @returns {Promise<string>} - Jkl address.
*/
async getJackalAddressFromContract (contractAddress: string): Promise<string> {
const retries = 30
let attempt = 0
while (attempt < retries) {
try {
const q = { get_contract_state: {} }

const req: DQuerySmartContractStateRequest = {
address: contractAddress,
queryData: stringToUint8Array(JSON.stringify(q)),
}

console.log(req)
const res = await this.hostSigner.queries.cosmwasm.smartContractState(req)
const str = uintArrayToString(res.data as Uint8Array)
console.log(str)
const data = JSON.parse(str)
if ("ica_info" in data) {
return data.ica_info.ica_address
try {
const retries = 30
let attempt = 0
while (attempt < retries) {
try {
const query = { get_contract_state: {} }
const req: DQuerySmartContractStateRequest = {
address: contractAddress,
queryData: stringToUint8Array(JSON.stringify(query)),
}
console.log(req)
const res = await this.hostSigner.queries.cosmwasm.smartContractState(req)
const str = uintArrayToString(res.data as Uint8Array)
console.log(str)
const data = JSON.parse(str)
if ('ica_info' in data) {
return data.ica_info.ica_address
}
attempt++
await new Promise(r => setTimeout(r, 5000))
} catch (err) {
console.warn('wasmHandler getJackalAddressFromContract()', err)
}
attempt ++
await new Promise(r => setTimeout(r, 5000));
} catch (err) {
console.warn('wasmHandler getJackalAddressFromContract()', err)
}
throw new Error('can\'t get details from contract')
} catch (err) {
throw warnError('wasmHandler getJackalAddressFromContract()', err)
}

throw warnError('wasmHandler getJackalAddressFromContract()', "can't get details from contract")
}


/**
*
* @param {string} contractAddress
* @returns {Promise<string>}
*/
async getContractChannelState (contractAddress: string): Promise<string> {
try {
const q = { get_channel: {} }

const query = { get_channel: {} }
const req: DQuerySmartContractStateRequest = {
address: contractAddress,
queryData: stringToUint8Array(JSON.stringify(q)),
queryData: stringToUint8Array(JSON.stringify(query)),
}

console.log(req)
const res = await this.hostSigner.queries.cosmwasm.smartContractState(req)
const str = uintArrayToString(res.data as Uint8Array)
console.log(str)
const data = JSON.parse(str)

return data.channel_status
} catch (err) {
throw warnError('wasmHandler getContractChannelState()', err)
Expand Down
2 changes: 1 addition & 1 deletion src/utils/gas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const gasBaselineRate = 56
const gasFallbackTxCost = 142
const gasMap: Record<string, number> = {
/** Filetree */
'/canine_chain.filetree.MsgPostFile': 570,
'/canine_chain.filetree.MsgPostFile': 270,
'/canine_chain.filetree.MsgPostKey': 12,
'/canine_chain.filetree.MsgDeleteFile': 9,
/** Notifications */
Expand Down
Loading

0 comments on commit 44c1fa0

Please sign in to comment.