From da4d43203f7ac441ab34f654808f869466e12b75 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 13 Sep 2023 18:29:47 +0200 Subject: [PATCH 01/44] add fee estimation --- src/sdk.ts | 57 ++++++++++--- src/types/contracts/warp_controller.ts | 29 +++++++ src/utils/big.ts | 9 ++ src/utils/fee.ts | 109 +++++++++++++++++++++++++ src/utils/index.ts | 1 + src/utils/token.ts | 39 +++++++++ 6 files changed, 234 insertions(+), 10 deletions(-) create mode 100644 src/utils/big.ts create mode 100644 src/utils/fee.ts diff --git a/src/sdk.ts b/src/sdk.ts index aa85c5a..949e8d1 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,7 +1,17 @@ import { warp_account, warp_controller, warp_resolver } from './types/contracts'; import { WalletLike, Wallet, wallet } from './wallet'; import { Condition } from './condition'; -import { base64encode, contractQuery, nativeTokenDenom, Token, TransferMsg } from './utils'; +import { + base64encode, + contractQuery, + nativeTokenDenom, + Token, + TransferMsg, + computeBurnFee, + computeCreationFee, + computeMaintenanceFee, + feeConfigByChainId, +} from './utils'; import { CreateTxOptions, TxInfo, LCDClientConfig, LCDClient } from '@terra-money/feather.js'; import { TxBuilder } from './tx'; import Big from 'big.js'; @@ -14,6 +24,10 @@ import { Job, parseJob } from './types/job'; const FEE_ADJUSTMENT_FACTOR = 3; +export type EstimateJobMsg = Omit & { + duration_days: number; +}; + export class WarpSdk { public wallet: Wallet; public condition: Condition; @@ -174,17 +188,23 @@ export class WarpSdk { return { ...controllerConfig, template_fee: templatesConfig.template_fee }; } - public async estimateJobReward( - sender: string, - createJobMsg: Omit - ): Promise { + public async state(): Promise { + const { state: controllerState } = await contractQuery< + Extract, + warp_controller.StateResponse + >(this.wallet.lcd, this.chain.contracts.controller, { query_state: {} }); + + return { ...controllerState }; + } + + public async estimateJobReward(sender: string, estimateJobMsg: EstimateJobMsg): Promise { const account = await this.account(sender); - const hydratedVars = await this.hydrateVars({ vars: createJobMsg.vars }); + const hydratedVars = await this.hydrateVars({ vars: estimateJobMsg.vars }); const hydratedMsgs = await this.hydrateMsgs({ vars: hydratedVars, - msgs: createJobMsg.msgs, + msgs: estimateJobMsg.msgs, }); const msgs = []; @@ -201,7 +221,7 @@ export class WarpSdk { ...( await this.tx.executeHydrateMsgs(account.account, { vars: hydratedVars, - msgs: createJobMsg.msgs, + msgs: estimateJobMsg.msgs, }) ).msgs ); @@ -209,13 +229,13 @@ export class WarpSdk { msgs.push( ...( await this.tx.executeResolveCondition(account.account, { - condition: createJobMsg.condition, + condition: estimateJobMsg.condition, vars: hydratedVars, }) ).msgs ); - if (createJobMsg.recurring) { + if (estimateJobMsg.recurring) { msgs.push( ...( await this.tx.executeApplyVarFn(account.account, { @@ -248,6 +268,23 @@ export class WarpSdk { return Big(fee.amount.get(denom).amount.toString()).mul(FEE_ADJUSTMENT_FACTOR); } + public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg): Promise { + const state = await this.state(); + const feeConfig = feeConfigByChainId[this.chain.config.chainID]; + + const jobRewardMicro = await this.estimateJobReward(sender, estimateJobMsg); + const jobRewardUnmicro = jobRewardMicro.div(Big(10).pow(feeConfig.nativeToken.decimals)); + + const burnFeeUnmicro = computeBurnFee(jobRewardUnmicro, feeConfig); + const maintenanceFeeUnmicro = computeMaintenanceFee(estimateJobMsg.duration_days, feeConfig); + const creationFeeUnmicro = computeCreationFee(Number(state.q), feeConfig); + + const totalFeeUnmicro = jobRewardUnmicro.add(burnFeeUnmicro).add(creationFeeUnmicro).add(maintenanceFeeUnmicro); + const totalFeeMicro = totalFeeUnmicro.mul(Big(10).pow(feeConfig.nativeToken.decimals)); + + return totalFeeMicro; + } + public async nativeTokenDenom(): Promise { return nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); } diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index af6c16d..8b949d1 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -51,6 +51,15 @@ export module warp_controller { } | { update_config: UpdateConfigMsg; + } + | { + migrate_accounts: MigrateAccountsMsg; + } + | { + migrate_pending_jobs: MigrateJobsMsg; + } + | { + migrate_finished_jobs: MigrateJobsMsg; }; export type AssetInfo = | { @@ -130,6 +139,15 @@ export module warp_controller { t_max?: Uint64 | null; t_min?: Uint64 | null; } + export interface MigrateAccountsMsg { + limit: number; + start_after?: string | null; + warp_account_code_id: Uint64; + } + export interface MigrateJobsMsg { + limit: number; + start_after?: Uint64 | null; + } export interface InstantiateMsg { a_max: Uint128; a_min: Uint128; @@ -185,6 +203,9 @@ export module warp_controller { } | { query_config: QueryConfigMsg; + } + | { + query_state: QueryStateMsg; }; export interface QueryJobMsg { id: Uint64; @@ -211,4 +232,12 @@ export module warp_controller { start_after?: string | null; } export interface QueryConfigMsg {} + export interface QueryStateMsg {} + export interface State { + current_job_id: Uint64; + q: Uint64; + } + export interface StateResponse { + state: State; + } } diff --git a/src/utils/big.ts b/src/utils/big.ts new file mode 100644 index 0000000..b976bea --- /dev/null +++ b/src/utils/big.ts @@ -0,0 +1,9 @@ +import Big from 'big.js'; + +export function max(a: Big, b: Big): Big { + return a.cmp(b) >= 0 ? a : b; +} + +export function min(a: Big, b: Big): Big { + return a.cmp(b) <= 0 ? a : b; +} diff --git a/src/utils/fee.ts b/src/utils/fee.ts new file mode 100644 index 0000000..b3630c0 --- /dev/null +++ b/src/utils/fee.ts @@ -0,0 +1,109 @@ +import Big from 'big.js'; +import { max } from './big'; +import { NativeToken, NATIVE_TOKENS } from './token'; + +type FeeConfig = { + creationFeeMin: number; + creationFeeMax: number; + burnFeeMin: number; + maintenanceFeeMin: number; + maintenanceFeeMax: number; + nativeToken: NativeToken; +}; + +export const feeConfigByChainId: Record = { + 'pisco-1': { + creationFeeMin: 0.5, + creationFeeMax: 100, + burnFeeMin: 0.1, + maintenanceFeeMin: 0.05, + maintenanceFeeMax: 10, + nativeToken: NATIVE_TOKENS.LUNA, + }, + 'phoenix-1': { + creationFeeMin: 0.5, + creationFeeMax: 100, + burnFeeMin: 0.1, + maintenanceFeeMin: 0.05, + maintenanceFeeMax: 10, + nativeToken: NATIVE_TOKENS.LUNA, + }, + 'pion-1': { + creationFeeMin: 1, + creationFeeMax: 200, + burnFeeMin: 0.5, + maintenanceFeeMin: 0.1, + maintenanceFeeMax: 20, + nativeToken: NATIVE_TOKENS.NEUTRON, + }, + 'neutron-1': { + creationFeeMin: 1, + creationFeeMax: 200, + burnFeeMin: 0.5, + maintenanceFeeMin: 0.1, + maintenanceFeeMax: 20, + nativeToken: NATIVE_TOKENS.NEUTRON, + }, + 'injective-1': { + creationFeeMin: 0.05, + creationFeeMax: 10, + burnFeeMin: 0.025, + maintenanceFeeMin: 0.005, + maintenanceFeeMax: 1, + nativeToken: NATIVE_TOKENS.INJ, + }, + 'injective-888': { + creationFeeMin: 0.05, + creationFeeMax: 10, + burnFeeMin: 0.025, + maintenanceFeeMin: 0.005, + maintenanceFeeMax: 1, + nativeToken: NATIVE_TOKENS.INJ, + }, +}; + +export function computeCreationFee(queue_size: number, feeConfig: FeeConfig): Big { + const x1 = 5000; + const y1 = feeConfig.creationFeeMin; + const x2 = 50000; + const y2 = feeConfig.creationFeeMax; + + const slope = (y2 - y1) / (x2 - x1); + const y_intercept = y1 - slope * x1; + + if (queue_size < x1) { + return Big(feeConfig.creationFeeMin); + } else if (queue_size < x2) { + return Big(slope * queue_size + y_intercept); + } else { + return Big(feeConfig.creationFeeMax); + } +} + +function sigmoid(x: number): number { + return 1 / (1 + Math.exp(-x)); +} + +function smoothTransition(x: number, min: number, max: number, k: number = 0.2): number { + const a = min; + const b = max; + const c = (max + min) / 2; + + const sigmoid_val = sigmoid(k * (x - c)); + + return a + (b - a) * sigmoid_val; +} + +export function computeMaintenanceFee(duration_days: number, feeConfig: FeeConfig, k: number = 0.2): Big { + if (duration_days < 10) { + return Big(feeConfig.maintenanceFeeMin); + } else if (duration_days <= 100) { + return Big(smoothTransition(duration_days, feeConfig.maintenanceFeeMin, feeConfig.maintenanceFeeMax, k)); + } else { + return Big(feeConfig.maintenanceFeeMax); + } +} + +export function computeBurnFee(jobReward: Big, feeConfig: FeeConfig): Big { + return max(Big(feeConfig.burnFeeMin), jobReward.mul(0.25)); +} diff --git a/src/utils/index.ts b/src/utils/index.ts index 42b6cdb..1170637 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,3 +1,4 @@ export * from './contract'; export * from './token'; export * from './mapping'; +export * from './fee'; diff --git a/src/utils/token.ts b/src/utils/token.ts index e145542..1357eb8 100644 --- a/src/utils/token.ts +++ b/src/utils/token.ts @@ -34,6 +34,45 @@ export type IBCToken = TokenBase & { export type Token = NativeToken | CW20Token | IBCToken; +export const LUNA: NativeToken = { + key: 'uluna', + type: 'native', + denom: 'uluna', + name: 'LUNA', + symbol: 'LUNA', + decimals: 6, + icon: 'https://assets.terra.dev/icon/svg/LUNA.png', + coinGeckoId: 'terra-luna-2', +}; + +export const NEUTRON: NativeToken = { + key: 'untrn', + type: 'native', + denom: 'untrn', + name: 'Neutron', + symbol: 'NTRN', + decimals: 6, + icon: 'https://assets.terra.dev/icon/svg/ibc/ATOM.svg', + coinGeckoId: 'neutron', +}; + +export const INJ: NativeToken = { + key: 'inj', + type: 'native', + denom: 'inj', + name: 'Injective', + symbol: 'INJ', + decimals: 18, + icon: 'https://assets.terra.dev/icon/svg/ibc/ATOM.svg', + coinGeckoId: 'injective-protocol', +}; + +export const NATIVE_TOKENS = { + LUNA, + INJ, + NEUTRON, +}; + type Explorer = { address: string; tx: string; From b47ff5b31b1679686031ef03025bd495cfd55bf1 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 25 Sep 2023 13:40:51 +0200 Subject: [PATCH 02/44] add controller asset and nft transfers on createAccount if funds are provided --- src/modules/tx.ts | 38 +++++++++++++++++++++++++++++---- src/sdk.ts | 49 ++++++++++++++++++++++++++++++++++++------- src/types/job.ts | 7 +++++++ src/utils/contract.ts | 7 +++++++ 4 files changed, 89 insertions(+), 12 deletions(-) diff --git a/src/modules/tx.ts b/src/modules/tx.ts index fee5ae1..515c6dc 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -1,11 +1,12 @@ import { warp_account, warp_controller, warp_resolver, warp_templates } from '../types/contracts'; -import { base64encode, nativeTokenDenom, Token, TransferMsg } from '../utils'; +import { base64encode, nativeTokenDenom, Token, TransferMsg, TransferNftMsg } from '../utils'; import { CreateTxOptions } from '@terra-money/feather.js'; import { TxBuilder } from '../tx'; import Big from 'big.js'; import { JobSequenceMsgComposer } from '../composers'; import { resolveExternalInputs } from '../variables'; import { WarpSdk } from '../sdk'; +import { Fund } from '../types/job'; export class TxModule { private warpSdk: WarpSdk; @@ -256,8 +257,36 @@ export class TxModule { .build(); } - public async createAccount(sender: string, funds?: warp_controller.Fund[]): Promise { - return TxBuilder.new(this.warpSdk.chain.config) + public async createAccount(sender: string, funds?: Fund[]): Promise { + let txBuilder = TxBuilder.new(this.warpSdk.chain.config); + + if (funds) { + for (let fund of funds) { + if ('cw20' in fund) { + const { amount, contract_addr } = fund.cw20; + + txBuilder = txBuilder.execute(sender, contract_addr, { + transfer: { + amount, + recipient: this.warpSdk.chain.contracts.controller, + }, + }); + } else if ('cw721' in fund) { + const { contract_addr, token_id } = fund.cw721; + + txBuilder = txBuilder.execute(sender, contract_addr, { + transfer_nft: { + token_id, + recipient: this.warpSdk.chain.contracts.controller, + }, + }); + } + } + } + + const nativeFunds = funds?.filter((fund) => 'native' in fund).map((fund) => fund.native) || []; + + return txBuilder .execute>( sender, this.warpSdk.chain.contracts.controller, @@ -265,7 +294,8 @@ export class TxModule { create_account: { funds, }, - } + }, + nativeFunds.reduce((acc, curr) => ({ ...acc, [curr.denom]: curr.amount }), {}) ) .build(); } diff --git a/src/sdk.ts b/src/sdk.ts index aa85c5a..0a48573 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,7 +1,7 @@ import { warp_account, warp_controller, warp_resolver } from './types/contracts'; import { WalletLike, Wallet, wallet } from './wallet'; import { Condition } from './condition'; -import { base64encode, contractQuery, nativeTokenDenom, Token, TransferMsg } from './utils'; +import { base64encode, contractQuery, nativeTokenDenom, Token, TransferMsg, TransferNftMsg } from './utils'; import { CreateTxOptions, TxInfo, LCDClientConfig, LCDClient } from '@terra-money/feather.js'; import { TxBuilder } from './tx'; import Big from 'big.js'; @@ -10,7 +10,7 @@ import { resolveExternalInputs } from './variables'; import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; import { warp_templates } from './types/contracts/warp_templates'; -import { Job, parseJob } from './types/job'; +import { Fund, Job, parseJob } from './types/job'; const FEE_ADJUSTMENT_FACTOR = 3; @@ -414,13 +414,46 @@ export class WarpSdk { return this.wallet.tx(txPayload); } - public async createAccount(sender: string, funds?: warp_controller.Fund[]): Promise { - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.controller, { - create_account: { - funds, + public async createAccount(sender: string, funds?: Fund[]): Promise { + let txBuilder = TxBuilder.new(this.chain.config); + + if (funds) { + for (let fund of funds) { + if ('cw20' in fund) { + const { amount, contract_addr } = fund.cw20; + + txBuilder = txBuilder.execute(sender, contract_addr, { + transfer: { + amount, + recipient: this.chain.contracts.controller, + }, + }); + } else if ('cw721' in fund) { + const { contract_addr, token_id } = fund.cw721; + + txBuilder = txBuilder.execute(sender, contract_addr, { + transfer_nft: { + token_id, + recipient: this.chain.contracts.controller, + }, + }); + } + } + } + + const nativeFunds = funds?.filter((fund) => 'native' in fund).map((fund) => fund.native) || []; + + const txPayload = txBuilder + .execute>( + sender, + this.chain.contracts.controller, + { + create_account: { + funds, + }, }, - }) + nativeFunds.reduce((acc, curr) => ({ ...acc, [curr.denom]: curr.amount }), {}) + ) .build(); return this.wallet.tx(txPayload); diff --git a/src/types/job.ts b/src/types/job.ts index a19d8ae..db8ea2e 100644 --- a/src/types/job.ts +++ b/src/types/job.ts @@ -36,3 +36,10 @@ export const parseJobsResponse = (resp: warp_controller.JobsResponse): JobsRespo jobs: resp.jobs.map(parseJob), }; }; + +export type Fund = warp_controller.Fund & { + native: { + denom: string; + amount: string; + }; +}; diff --git a/src/utils/contract.ts b/src/utils/contract.ts index e91ac91..a1a5563 100644 --- a/src/utils/contract.ts +++ b/src/utils/contract.ts @@ -15,6 +15,13 @@ export type TransferMsg = { }; }; +export type TransferNftMsg = { + transfer_nft: { + recipient: string; + token_id: string; + }; +}; + export const base64encode = (input: any): string => { return Buffer.from(JSON.stringify(JSON.parse(JSON.stringify(input)))).toString('base64'); }; From 1e9e1825c2a2986c0c6ae853f785e82048cf837d Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 25 Sep 2023 15:07:37 +0200 Subject: [PATCH 03/44] create giga create_job method that includes account creation with funding --- src/modules/tx.ts | 5 ++- src/sdk.ts | 98 ++++++++++++----------------------------------- src/tx.ts | 8 +++- src/types/job.ts | 63 +++++++++++++++++++++++++++--- src/utils/fee.ts | 1 + 5 files changed, 91 insertions(+), 84 deletions(-) diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 515c6dc..1fc037b 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -284,7 +284,8 @@ export class TxModule { } } - const nativeFunds = funds?.filter((fund) => 'native' in fund).map((fund) => fund.native) || []; + const nativeFunds = funds?.filter((fund) => 'native' in fund).map((fund) => 'native' in fund && fund.native) ?? []; + const cwFunds = (funds?.filter((fund) => !('native' in fund)) as warp_controller.Fund[]) ?? []; return txBuilder .execute>( @@ -292,7 +293,7 @@ export class TxModule { this.warpSdk.chain.contracts.controller, { create_account: { - funds, + funds: cwFunds, }, }, nativeFunds.reduce((acc, curr) => ({ ...acc, [curr.denom]: curr.amount }), {}) diff --git a/src/sdk.ts b/src/sdk.ts index 11fc204..30c41e7 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -21,7 +21,7 @@ import { resolveExternalInputs } from './variables'; import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; import { warp_templates } from './types/contracts/warp_templates'; -import { Fund, Job, parseJob } from './types/job'; +import { Fund, Job, mergeFunds, parseJob } from './types/job'; const FEE_ADJUSTMENT_FACTOR = 3; @@ -290,22 +290,21 @@ export class WarpSdk { return nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); } - public async createJob(sender: string, msg: warp_controller.CreateJobMsg): Promise { - await this.createAccountIfNotExists(sender); + public async createJob(sender: string, msg: warp_controller.CreateJobMsg, funds?: Fund[]): Promise { + const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); - const account = await this.account(sender); - const config = await this.config(); + const rewardFund: Fund = { native: { denom: nativeDenom, amount: msg.reward } }; + const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; - const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); + const createAccountTx = await this.tx.createAccount(sender, totalFunds); - const txPayload = TxBuilder.new(this.chain.config) - .send(account.owner, account.account, { - [nativeDenom]: Big(msg.reward).mul(Big(config.creation_fee_percentage).add(100).div(100)).toString(), - }) + const txBuilder = TxBuilder.new(this.chain.config) + .tx(createAccountTx) .execute>(sender, this.chain.contracts.controller, { create_job: msg, - }) - .build(); + }); + + const txPayload = txBuilder.build(); return this.wallet.tx(txPayload); } @@ -324,28 +323,29 @@ export class WarpSdk { * when cond3 active * then execute job3 */ - public async createJobSequence(sender: string, sequence: warp_controller.CreateJobMsg[]): Promise { - await this.createAccountIfNotExists(sender); + public async createJobSequence( + sender: string, + sequence: warp_controller.CreateJobMsg[], + funds?: Fund[] + ): Promise { + const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); - const account = await this.account(sender); - const config = await this.config(); + const totalReward = sequence.reduce((acc, msg) => acc.add(Big(msg.reward)), Big(0)); + const rewardFund: Fund = { native: { denom: nativeDenom, amount: totalReward.toString() } }; + const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; + + const createAccountTx = await this.tx.createAccount(sender, totalFunds); let jobSequenceMsgComposer = JobSequenceMsgComposer.new(); - let totalReward = Big(0); sequence.forEach((msg) => { - totalReward = totalReward.add(Big(msg.reward)); jobSequenceMsgComposer = jobSequenceMsgComposer.chain(msg); }); const jobSequenceMsg = jobSequenceMsgComposer.compose(); - const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); - const txPayload = TxBuilder.new(this.chain.config) - .send(account.owner, account.account, { - [nativeDenom]: Big(totalReward).mul(Big(config.creation_fee_percentage).add(100).div(100)).toString(), - }) + .tx(createAccountTx) .execute>(sender, this.chain.contracts.controller, { create_job: jobSequenceMsg, }) @@ -354,17 +354,6 @@ export class WarpSdk { return this.wallet.tx(txPayload); } - public async createAccountIfNotExists(sender: string): Promise { - try { - const account = await this.account(sender); - return account; - } catch (err) { - // account not exists - await this.createAccount(sender); - return this.account(sender); - } - } - public async deleteJob(sender: string, jobId: string): Promise { const txPayload = TxBuilder.new(this.chain.config) .execute>(sender, this.chain.contracts.controller, { @@ -453,46 +442,7 @@ export class WarpSdk { } public async createAccount(sender: string, funds?: Fund[]): Promise { - let txBuilder = TxBuilder.new(this.chain.config); - - if (funds) { - for (let fund of funds) { - if ('cw20' in fund) { - const { amount, contract_addr } = fund.cw20; - - txBuilder = txBuilder.execute(sender, contract_addr, { - transfer: { - amount, - recipient: this.chain.contracts.controller, - }, - }); - } else if ('cw721' in fund) { - const { contract_addr, token_id } = fund.cw721; - - txBuilder = txBuilder.execute(sender, contract_addr, { - transfer_nft: { - token_id, - recipient: this.chain.contracts.controller, - }, - }); - } - } - } - - const nativeFunds = funds?.filter((fund) => 'native' in fund).map((fund) => fund.native) || []; - - const txPayload = txBuilder - .execute>( - sender, - this.chain.contracts.controller, - { - create_account: { - funds, - }, - }, - nativeFunds.reduce((acc, curr) => ({ ...acc, [curr.denom]: curr.amount }), {}) - ) - .build(); + const txPayload = await this.tx.createAccount(sender, funds); return this.wallet.tx(txPayload); } diff --git a/src/tx.ts b/src/tx.ts index dbc251b..659b927 100644 --- a/src/tx.ts +++ b/src/tx.ts @@ -2,6 +2,7 @@ import { Coins, ExecuteContractProposal, MsgExecuteContract, + Msg, MsgSend, MsgSubmitProposal, MsgVote, @@ -9,8 +10,6 @@ import { CreateTxOptions, } from '@terra-money/feather.js'; -type Msg = MsgExecuteContract | MsgSubmitProposal | MsgVote | MsgSend; - export enum VoteOption { /** VOTE_OPTION_UNSPECIFIED - VOTE_OPTION_UNSPECIFIED defines a no-op vote option. */ VOTE_OPTION_UNSPECIFIED = 0, @@ -37,6 +36,11 @@ export class TxBuilder { this.chainConfig = chainConfig; } + tx(createTx: CreateTxOptions) { + this.msgs = [...this.msgs, ...createTx.msgs]; + return this; + } + execute(sender: string, contract: string, msg: T, coins?: Coins.Input) { this.msgs = [...this.msgs, new MsgExecuteContract(sender, contract, msg, coins)]; return this; diff --git a/src/types/job.ts b/src/types/job.ts index db8ea2e..a91fb09 100644 --- a/src/types/job.ts +++ b/src/types/job.ts @@ -1,3 +1,4 @@ +import Big from 'big.js'; import { warp_controller, warp_resolver } from './contracts'; export type Job = Omit & { @@ -37,9 +38,59 @@ export const parseJobsResponse = (resp: warp_controller.JobsResponse): JobsRespo }; }; -export type Fund = warp_controller.Fund & { - native: { - denom: string; - amount: string; - }; -}; +export type Fund = + | warp_controller.Fund + | { + native: { + denom: string; + amount: string; + }; + }; + +export function mergeFunds(funds: Fund[], fund: Fund): Fund[] { + const mergedFunds = [...funds]; + let fundMerged = false; + + for (let i = 0; i < mergedFunds.length; i++) { + const existingFund = mergedFunds[i]; + + if ('native' in fund && 'native' in existingFund) { + if (fund.native.denom === existingFund.native.denom) { + mergedFunds[i] = { + native: { + denom: fund.native.denom, + amount: Big(existingFund.native.amount).add(fund.native.amount).toString(), + }, + }; + fundMerged = true; + break; + } + } else if ('cw20' in fund && 'cw20' in existingFund) { + if (fund.cw20.contract_addr === existingFund.cw20.contract_addr) { + mergedFunds[i] = { + cw20: { + contract_addr: fund.cw20.contract_addr, + amount: Big(existingFund.cw20.amount).add(fund.cw20.amount).toString(), + }, + }; + fundMerged = true; + break; + } + } else if ('cw721' in fund && 'cw721' in existingFund) { + if ( + fund.cw721.contract_addr === existingFund.cw721.contract_addr && + fund.cw721.token_id === existingFund.cw721.token_id + ) { + // cw721 tokens are non-fungible, so we don't merge them based on amount, but check for duplicates based on token_id + fundMerged = true; + break; + } + } + } + + if (!fundMerged) { + mergedFunds.push(fund); + } + + return mergedFunds; +} diff --git a/src/utils/fee.ts b/src/utils/fee.ts index b3630c0..a4e3aba 100644 --- a/src/utils/fee.ts +++ b/src/utils/fee.ts @@ -105,5 +105,6 @@ export function computeMaintenanceFee(duration_days: number, feeConfig: FeeConfi } export function computeBurnFee(jobReward: Big, feeConfig: FeeConfig): Big { + // config.create_fee_percentage return max(Big(feeConfig.burnFeeMin), jobReward.mul(0.25)); } From 318480d4394a75e120a1fa61d97d8996e2fec744 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 25 Sep 2023 15:37:14 +0200 Subject: [PATCH 04/44] move create job + sequence to tx module --- src/modules/tx.ts | 39 +++++++++++++++++++++------------------ src/sdk.ts | 38 ++------------------------------------ 2 files changed, 23 insertions(+), 54 deletions(-) diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 1fc037b..eedbed5 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -6,7 +6,7 @@ import Big from 'big.js'; import { JobSequenceMsgComposer } from '../composers'; import { resolveExternalInputs } from '../variables'; import { WarpSdk } from '../sdk'; -import { Fund } from '../types/job'; +import { Fund, mergeFunds } from '../types/job'; export class TxModule { private warpSdk: WarpSdk; @@ -15,16 +15,16 @@ export class TxModule { this.warpSdk = warpSdk; } - public async createJob(sender: string, msg: warp_controller.CreateJobMsg): Promise { - const account = await this.warpSdk.account(sender); - const config = await this.warpSdk.config(); - + public async createJob(sender: string, msg: warp_controller.CreateJobMsg, funds?: Fund[]): Promise { const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); + const rewardFund: Fund = { native: { denom: nativeDenom, amount: msg.reward } }; + const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; + + const createAccountTx = await this.createAccount(sender, totalFunds); + return TxBuilder.new(this.warpSdk.chain.config) - .send(account.owner, account.account, { - [nativeDenom]: Big(msg.reward).mul(Big(config.creation_fee_percentage).add(100).div(100)).toString(), - }) + .tx(createAccountTx) .execute>( sender, this.warpSdk.chain.contracts.controller, @@ -35,26 +35,29 @@ export class TxModule { .build(); } - public async createJobSequence(sender: string, sequence: warp_controller.CreateJobMsg[]): Promise { - const account = await this.warpSdk.account(sender); - const config = await this.warpSdk.config(); + public async createJobSequence( + sender: string, + sequence: warp_controller.CreateJobMsg[], + funds?: Fund[] + ): Promise { + const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); + + const totalReward = sequence.reduce((acc, msg) => acc.add(Big(msg.reward)), Big(0)); + const rewardFund: Fund = { native: { denom: nativeDenom, amount: totalReward.toString() } }; + const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; + + const createAccountTx = await this.createAccount(sender, totalFunds); let jobSequenceMsgComposer = JobSequenceMsgComposer.new(); - let totalReward = Big(0); sequence.forEach((msg) => { - totalReward = totalReward.add(Big(msg.reward)); jobSequenceMsgComposer = jobSequenceMsgComposer.chain(msg); }); const jobSequenceMsg = jobSequenceMsgComposer.compose(); - const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); - return TxBuilder.new(this.warpSdk.chain.config) - .send(account.owner, account.account, { - [nativeDenom]: Big(totalReward).mul(Big(config.creation_fee_percentage).add(100).div(100)).toString(), - }) + .tx(createAccountTx) .execute>( sender, this.warpSdk.chain.contracts.controller, diff --git a/src/sdk.ts b/src/sdk.ts index 30c41e7..cb67b91 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -291,20 +291,7 @@ export class WarpSdk { } public async createJob(sender: string, msg: warp_controller.CreateJobMsg, funds?: Fund[]): Promise { - const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); - - const rewardFund: Fund = { native: { denom: nativeDenom, amount: msg.reward } }; - const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; - - const createAccountTx = await this.tx.createAccount(sender, totalFunds); - - const txBuilder = TxBuilder.new(this.chain.config) - .tx(createAccountTx) - .execute>(sender, this.chain.contracts.controller, { - create_job: msg, - }); - - const txPayload = txBuilder.build(); + const txPayload = await this.tx.createJob(sender, msg, funds); return this.wallet.tx(txPayload); } @@ -328,28 +315,7 @@ export class WarpSdk { sequence: warp_controller.CreateJobMsg[], funds?: Fund[] ): Promise { - const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); - - const totalReward = sequence.reduce((acc, msg) => acc.add(Big(msg.reward)), Big(0)); - const rewardFund: Fund = { native: { denom: nativeDenom, amount: totalReward.toString() } }; - const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; - - const createAccountTx = await this.tx.createAccount(sender, totalFunds); - - let jobSequenceMsgComposer = JobSequenceMsgComposer.new(); - - sequence.forEach((msg) => { - jobSequenceMsgComposer = jobSequenceMsgComposer.chain(msg); - }); - - const jobSequenceMsg = jobSequenceMsgComposer.compose(); - - const txPayload = TxBuilder.new(this.chain.config) - .tx(createAccountTx) - .execute>(sender, this.chain.contracts.controller, { - create_job: jobSequenceMsg, - }) - .build(); + const txPayload = await this.tx.createJobSequence(sender, sequence, funds); return this.wallet.tx(txPayload); } From 30a3851e680848676ec5d65c1729edc7b5ea6d93 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 25 Sep 2023 15:39:07 +0200 Subject: [PATCH 05/44] move update job + evict job to tx module --- src/modules/tx.ts | 3 +-- src/sdk.ts | 14 ++------------ 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/src/modules/tx.ts b/src/modules/tx.ts index eedbed5..501397d 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -82,14 +82,13 @@ export class TxModule { public async updateJob(sender: string, msg: warp_controller.UpdateJobMsg): Promise { const account = await this.warpSdk.account(sender); - const config = await this.warpSdk.config(); const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); let txBuilder = TxBuilder.new(this.warpSdk.chain.config); if (msg.added_reward) { txBuilder = txBuilder.send(account.owner, account.account, { - [nativeDenom]: Big(msg.added_reward).mul(Big(config.creation_fee_percentage).add(100).div(100)).toString(), + [nativeDenom]: Big(msg.added_reward).toString(), }); } diff --git a/src/sdk.ts b/src/sdk.ts index cb67b91..fe564ba 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -331,23 +331,13 @@ export class WarpSdk { } public async updateJob(sender: string, msg: warp_controller.UpdateJobMsg): Promise { - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.controller, { - update_job: msg, - }) - .build(); + const txPayload = await this.tx.updateJob(sender, msg); return this.wallet.tx(txPayload); } public async evictJob(sender: string, jobId: string): Promise { - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.controller, { - evict_job: { - id: jobId, - }, - }) - .build(); + const txPayload = await this.tx.evictJob(sender, jobId); return this.wallet.tx(txPayload); } From b8d281a0ee39a3c5c2e97128f24506d858c3acba Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 25 Sep 2023 15:43:29 +0200 Subject: [PATCH 06/44] move rest of methods to tx module --- src/sdk.ts | 121 ++++------------------------------------------------- 1 file changed, 9 insertions(+), 112 deletions(-) diff --git a/src/sdk.ts b/src/sdk.ts index fe564ba..7daec7c 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -321,11 +321,7 @@ export class WarpSdk { } public async deleteJob(sender: string, jobId: string): Promise { - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.controller, { - delete_job: { id: jobId }, - }) - .build(); + const txPayload = await this.tx.deleteJob(sender, jobId); return this.wallet.tx(txPayload); } @@ -343,56 +339,25 @@ export class WarpSdk { } public async executeJob(sender: string, jobId: string): Promise { - const job = await this.job(jobId); - - const externalInputs = await resolveExternalInputs(job.vars); - - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.controller, { - execute_job: { id: job.id, external_inputs: externalInputs }, - }) - .build(); + const txPayload = await this.tx.executeJob(sender, jobId); return this.wallet.tx(txPayload); } public async submitTemplate(sender: string, msg: warp_templates.SubmitTemplateMsg): Promise { - const config = await this.config(); - - const nativeDenom = await nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); - - const txPayload = TxBuilder.new(this.chain.config) - .execute>( - sender, - this.chain.contracts.templates, - { - submit_template: msg, - }, - { - [nativeDenom]: config.template_fee, - } - ) - .build(); + const txPayload = await this.tx.submitTemplate(sender, msg); return this.wallet.tx(txPayload); } public async deleteTemplate(sender: string, templateId: string): Promise { - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.templates, { - delete_template: { id: templateId }, - }) - .build(); + const txPayload = await this.tx.deleteTemplate(sender, templateId); return this.wallet.tx(txPayload); } public async editTemplate(sender: string, msg: warp_templates.EditTemplateMsg): Promise { - const txPayload = TxBuilder.new(this.chain.config) - .execute>(sender, this.chain.contracts.templates, { - edit_template: msg, - }) - .build(); + const txPayload = await this.tx.editTemplate(sender, msg); return this.wallet.tx(txPayload); } @@ -404,87 +369,19 @@ export class WarpSdk { } public async withdrawAssets(sender: string, msg: warp_account.WithdrawAssetsMsg): Promise { - const { account } = await this.account(sender); + const txPayload = await this.tx.withdrawAssets(sender, msg); - const tx = TxBuilder.new(this.chain.config) - .execute>(sender, account, { - withdraw_assets: msg, - }) - .build(); - - return this.wallet.tx(tx); + return this.wallet.tx(txPayload); } - // deposit token (supports native, ibc and cw20 token type) from sender to warp account - // warp account can be owned by anyone public async depositToAccount(sender: string, account: string, token: Token, amount: string): Promise { - let txPayload: CreateTxOptions; - if (token.type === 'cw20') { - txPayload = TxBuilder.new(this.chain.config) - .execute(sender, token.token, { - transfer: { - amount, - recipient: account, - }, - }) - .build(); - } else { - txPayload = TxBuilder.new(this.chain.config) - .send(sender, account, { [token.denom]: amount }) - .build(); - } + const txPayload = await this.tx.depositToAccount(sender, account, token, amount); return this.wallet.tx(txPayload); } - // withdraw token (supports native, ibc and cw20 token type) from sender's warp account to receiver - // receiver can be anyone public async withdrawFromAccount(sender: string, receiver: string, token: Token, amount: string): Promise { - const { account } = await this.account(sender); - let txPayload: CreateTxOptions; - if (token.type === 'cw20') { - const transferMsg = { - transfer: { - amount, - recipient: receiver, - }, - }; - - txPayload = TxBuilder.new(this.chain.config) - .execute(sender, account, { - generic: { - msgs: [ - { - wasm: { - execute: { - contract_addr: token.token, - msg: base64encode(transferMsg), - funds: [], - }, - }, - }, - ], - }, - }) - .build(); - } else { - txPayload = TxBuilder.new(this.chain.config) - .execute(sender, account, { - generic: { - msgs: [ - { - bank: { - send: { - amount: [{ amount, denom: token.denom }], - to_address: receiver, - }, - }, - }, - ], - }, - }) - .build(); - } + const txPayload = await this.tx.withdrawFromAccount(sender, receiver, token, amount); return this.wallet.tx(txPayload); } From ef3d9b1bfd0f22c5d3e4bae4e1e033c4d8cb8371 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Thu, 2 Nov 2023 17:16:56 +0100 Subject: [PATCH 07/44] add new fee code and types --- src/sdk.ts | 69 +++---- src/types/contracts/warp_account.ts | 27 ++- src/types/contracts/warp_controller.ts | 241 ++++++++++++++++++++++++- src/types/contracts/warp_resolver.ts | 45 +++-- src/types/contracts/warp_templates.ts | 29 ++- src/utils/fee.ts | 127 ++++--------- 6 files changed, 382 insertions(+), 156 deletions(-) diff --git a/src/sdk.ts b/src/sdk.ts index 83ba30d..bf8ad1b 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -2,31 +2,27 @@ import { warp_account, warp_controller, warp_resolver } from './types/contracts' import { WalletLike, Wallet, wallet } from './wallet'; import { Condition } from './condition'; import { - base64encode, contractQuery, nativeTokenDenom, Token, - TransferMsg, - TransferNftMsg, computeBurnFee, computeCreationFee, computeMaintenanceFee, - feeConfigByChainId, } from './utils'; -import { CreateTxOptions, TxInfo, LCDClientConfig, LCDClient } from '@terra-money/feather.js'; -import { TxBuilder } from './tx'; +import { TxInfo, LCDClientConfig, LCDClient } from '@terra-money/feather.js'; import Big from 'big.js'; -import { JobSequenceMsgComposer } from './composers'; -import { resolveExternalInputs } from './variables'; import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; import { warp_templates } from './types/contracts/warp_templates'; -import { Fund, Job, mergeFunds, parseJob } from './types/job'; +import { Fund, Job, parseJob } from './types/job'; const FEE_ADJUSTMENT_FACTOR = 3; -export type EstimateJobMsg = Omit & { - duration_days: number; +export type EstimateJobMsg = { + vars: string; + recurring: boolean; + executions: warp_controller.Execution[]; + duration_days: string; }; export class WarpSdk { @@ -198,14 +194,42 @@ export class WarpSdk { return { ...controllerState }; } + public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg): Promise { + const state = await this.state(); + const config = await this.config(); + const jobReward = await this.estimateJobReward(sender, estimateJobMsg); + + const burnFee = computeBurnFee(jobReward, config); + const maintenanceFee = computeMaintenanceFee(Big(estimateJobMsg.duration_days), config); + const creationFee = computeCreationFee(Big(state.q), config); + + const totalFee = jobReward.add(burnFee).add(creationFee).add(maintenanceFee); + + return totalFee; + } + public async estimateJobReward(sender: string, estimateJobMsg: EstimateJobMsg): Promise { + let estimatedReward = Big(0); + + for (let execution of estimateJobMsg.executions) { + estimatedReward = estimatedReward.add(await this.estimateJobExecutionReward(sender, estimateJobMsg, execution)); + } + + return estimatedReward; + } + + public async estimateJobExecutionReward( + sender: string, + estimateJobMsg: EstimateJobMsg, + execution: warp_controller.Execution + ): Promise { const account = await this.account(sender); const hydratedVars = await this.hydrateVars({ vars: estimateJobMsg.vars }); const hydratedMsgs = await this.hydrateMsgs({ vars: hydratedVars, - msgs: estimateJobMsg.msgs, + msgs: execution.msgs, }); const msgs = []; @@ -222,7 +246,7 @@ export class WarpSdk { ...( await this.tx.executeHydrateMsgs(account.account, { vars: hydratedVars, - msgs: estimateJobMsg.msgs, + msgs: execution.msgs, }) ).msgs ); @@ -230,7 +254,7 @@ export class WarpSdk { msgs.push( ...( await this.tx.executeResolveCondition(account.account, { - condition: estimateJobMsg.condition, + condition: execution.condition, vars: hydratedVars, }) ).msgs @@ -269,23 +293,6 @@ export class WarpSdk { return Big(fee.amount.get(denom).amount.toString()).mul(FEE_ADJUSTMENT_FACTOR); } - public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg): Promise { - const state = await this.state(); - const feeConfig = feeConfigByChainId[this.chain.config.chainID]; - - const jobRewardMicro = await this.estimateJobReward(sender, estimateJobMsg); - const jobRewardUnmicro = jobRewardMicro.div(Big(10).pow(feeConfig.nativeToken.decimals)); - - const burnFeeUnmicro = computeBurnFee(jobRewardUnmicro, feeConfig); - const maintenanceFeeUnmicro = computeMaintenanceFee(estimateJobMsg.duration_days, feeConfig); - const creationFeeUnmicro = computeCreationFee(Number(state.q), feeConfig); - - const totalFeeUnmicro = jobRewardUnmicro.add(burnFeeUnmicro).add(creationFeeUnmicro).add(maintenanceFeeUnmicro); - const totalFeeMicro = totalFeeUnmicro.mul(Big(10).pow(feeConfig.nativeToken.decimals)); - - return totalFeeMicro; - } - public async nativeTokenDenom(): Promise { return nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); } diff --git a/src/types/contracts/warp_account.ts b/src/types/contracts/warp_account.ts index c91b0dc..b2531f8 100644 --- a/src/types/contracts/warp_account.ts +++ b/src/types/contracts/warp_account.ts @@ -11,6 +11,8 @@ export module warp_account { accounts: Account[]; } export interface Config { + is_sub_account: boolean; + main_account_addr: Addr; owner: Addr; warp_addr: Addr; } @@ -23,6 +25,12 @@ export module warp_account { } | { ibc_transfer: IbcTransferMsg; + } + | { + occupy_sub_account: OccupySubAccountMsg; + } + | { + free_sub_account: FreeSubAccountMsg; }; export type CosmosMsgFor_Empty = | { @@ -261,6 +269,13 @@ export module warp_account { revision_height?: number | null; revision_number?: number | null; } + export interface OccupySubAccountMsg { + job_id: Uint64; + sub_account_addr: string; + } + export interface FreeSubAccountMsg { + sub_account_addr: string; + } export type Fund = | { cw20: Cw20Fund; @@ -270,6 +285,9 @@ export module warp_account { }; export interface InstantiateMsg { funds?: Fund[] | null; + is_sub_account?: boolean | null; + main_account_addr?: string | null; + msgs?: CosmosMsgFor_Empty[] | null; owner: string; } export interface Cw20Fund { @@ -285,15 +303,16 @@ export module warp_account { job: Job; } export interface Job { + account: Addr; assets_to_withdraw: AssetInfo[]; - condition: string; description: string; + executions: Execution[]; id: Uint64; labels: string[]; last_update_time: Uint64; - msgs: string; name: string; owner: Addr; + prev_id?: Uint64 | null; recurring: boolean; requeue_on_evict: boolean; reward: Uint128; @@ -301,6 +320,10 @@ export module warp_account { terminate_condition?: string | null; vars: string; } + export interface Execution { + condition: string; + msgs: string; + } export interface JobsResponse { jobs: Job[]; total_count: number; diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 8b949d1..2b98a95 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -15,13 +15,23 @@ export module warp_controller { export interface Config { a_max: Uint128; a_min: Uint128; + burn_fee_min: Uint128; + burn_fee_rate: Uint128; cancellation_fee_percentage: Uint64; + creation_fee_max: Uint128; + creation_fee_min: Uint128; creation_fee_percentage: Uint64; + duration_days_left: Uint128; + duration_days_right: Uint128; fee_collector: Addr; fee_denom: string; + maintenance_fee_max: Uint128; + maintenance_fee_min: Uint128; minimum_reward: Uint128; owner: Addr; q_max: Uint64; + queue_size_left: Uint128; + queue_size_right: Uint128; resolver_address: Addr; t_max: Uint64; t_min: Uint64; @@ -61,6 +71,183 @@ export module warp_controller { | { migrate_finished_jobs: MigrateJobsMsg; }; + export type CosmosMsgFor_Empty = + | { + bank: BankMsg; + } + | { + custom: Empty; + } + | { + staking: StakingMsg; + } + | { + distribution: DistributionMsg; + } + | { + stargate: { + type_url: string; + value: Binary; + }; + } + | { + ibc: IbcMsg; + } + | { + wasm: WasmMsg; + } + | { + gov: GovMsg; + }; + export type BankMsg = + | { + send: { + amount: Coin[]; + to_address: string; + }; + } + | { + burn: { + amount: Coin[]; + }; + }; + export type StakingMsg = + | { + delegate: { + amount: Coin; + validator: string; + }; + } + | { + undelegate: { + amount: Coin; + validator: string; + }; + } + | { + redelegate: { + amount: Coin; + dst_validator: string; + src_validator: string; + }; + }; + export type DistributionMsg = + | { + set_withdraw_address: { + /** + * The `withdraw_address` + */ + address: string; + }; + } + | { + withdraw_delegator_reward: { + /** + * The `validator_address` + */ + validator: string; + }; + }; + export type Binary = string; + export type IbcMsg = + | { + transfer: { + /** + * packet data only supports one coin https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/ibc/applications/transfer/v1/transfer.proto#L11-L20 + */ + amount: Coin; + /** + * exisiting channel to send the tokens over + */ + channel_id: string; + /** + * when packet times out, measured on remote chain + */ + timeout: IbcTimeout; + /** + * address on the remote chain to receive these tokens + */ + to_address: string; + }; + } + | { + send_packet: { + channel_id: string; + data: Binary; + /** + * when packet times out, measured on remote chain + */ + timeout: IbcTimeout; + }; + } + | { + close_channel: { + channel_id: string; + }; + }; + export type Timestamp = Uint64; + export type WasmMsg = + | { + execute: { + contract_addr: string; + funds: Coin[]; + /** + * msg is the json-encoded ExecuteMsg struct (as raw Binary) + */ + msg: Binary; + }; + } + | { + instantiate: { + admin?: string | null; + code_id: number; + funds: Coin[]; + /** + * A human-readbale label for the contract + */ + label: string; + /** + * msg is the JSON-encoded InstantiateMsg struct (as raw Binary) + */ + msg: Binary; + }; + } + | { + migrate: { + contract_addr: string; + /** + * msg is the json-encoded MigrateMsg struct that will be passed to the new code + */ + msg: Binary; + /** + * the code_id of the new logic to place in the given contract + */ + new_code_id: number; + }; + } + | { + update_admin: { + admin: string; + contract_addr: string; + }; + } + | { + clear_admin: { + contract_addr: string; + }; + }; + export type GovMsg = { + vote: { + proposal_id: number; + /** + * The vote option. + * + * This should be called "option" for consistency with Cosmos SDK. Sorry for that. See . + */ + vote: VoteOption; + }; + }; + export type VoteOption = 'yes' | 'no' | 'abstain' | 'no_with_veto'; export type AssetInfo = | { native: string; @@ -83,11 +270,12 @@ export module warp_controller { cw721: Cw721Fund; }; export interface CreateJobMsg { + account_msgs?: CosmosMsgFor_Empty[] | null; assets_to_withdraw?: AssetInfo[] | null; - condition: string; description: string; + duration_days: Uint128; + executions: Execution[]; labels: string[]; - msgs: string; name: string; recurring: boolean; requeue_on_evict: boolean; @@ -95,6 +283,29 @@ export module warp_controller { terminate_condition?: string | null; vars: string; } + export interface Coin { + amount: Uint128; + denom: string; + } + export interface Empty {} + export interface IbcTimeout { + block?: IbcTimeoutBlock | null; + timestamp?: Timestamp | null; + } + export interface IbcTimeoutBlock { + /** + * block height after which the packet times out. the height within the given revision + */ + height: number; + /** + * the version that the client is currently on (eg. after reseting the chain this could increment 1 as height drops to 0) + */ + revision: number; + } + export interface Execution { + condition: string; + msgs: string; + } export interface DeleteJobMsg { id: Uint64; } @@ -118,6 +329,7 @@ export module warp_controller { } export interface CreateAccountMsg { funds?: Fund[] | null; + msgs?: CosmosMsgFor_Empty[] | null; } export interface Cw20Fund { amount: Uint128; @@ -130,12 +342,22 @@ export module warp_controller { export interface UpdateConfigMsg { a_max?: Uint128 | null; a_min?: Uint128 | null; + burn_fee_min?: Uint128 | null; + burn_fee_rate?: Uint128 | null; cancellation_fee_percentage?: Uint64 | null; + creation_fee_max?: Uint128 | null; + creation_fee_min?: Uint128 | null; creation_fee_percentage?: Uint64 | null; + duration_days_left?: Uint128 | null; + duration_days_right?: Uint128 | null; fee_collector?: string | null; + maintenance_fee_max?: Uint128 | null; + maintenance_fee_min?: Uint128 | null; minimum_reward?: Uint128 | null; owner?: string | null; q_max?: Uint64 | null; + queue_size_left?: Uint128 | null; + queue_size_right?: Uint128 | null; t_max?: Uint64 | null; t_min?: Uint64 | null; } @@ -151,13 +373,23 @@ export module warp_controller { export interface InstantiateMsg { a_max: Uint128; a_min: Uint128; + burn_fee_min: Uint128; + burn_fee_rate: Uint128; cancellation_fee: Uint64; creation_fee: Uint64; + creation_fee_max: Uint128; + creation_fee_min: Uint128; + duration_days_left: Uint128; + duration_days_right: Uint128; fee_collector?: string | null; fee_denom: string; + maintenance_fee_max: Uint128; + maintenance_fee_min: Uint128; minimum_reward: Uint128; owner?: string | null; q_max: Uint64; + queue_size_left: Uint128; + queue_size_right: Uint128; resolver_address: string; t_max: Uint64; t_min: Uint64; @@ -168,15 +400,16 @@ export module warp_controller { job: Job; } export interface Job { + account: Addr; assets_to_withdraw: AssetInfo[]; - condition: string; description: string; + executions: Execution[]; id: Uint64; labels: string[]; last_update_time: Uint64; - msgs: string; name: string; owner: Addr; + prev_id?: Uint64 | null; recurring: boolean; requeue_on_evict: boolean; reward: Uint128; diff --git a/src/types/contracts/warp_resolver.ts b/src/types/contracts/warp_resolver.ts index a70d28a..b373130 100644 --- a/src/types/contracts/warp_resolver.ts +++ b/src/types/contracts/warp_resolver.ts @@ -27,7 +27,7 @@ export module warp_resolver { }; export type Expr = | { - string: GenExprFor_ValueFor_StringAnd_StringOp; + string: GenExprFor_StringValueFor_StringAnd_StringOp; } | { uint: GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp; @@ -47,13 +47,17 @@ export module warp_resolver { | { bool: string; }; - export type ValueFor_String = + export type StringValueFor_String = | { simple: string; } | { ref: string; + } + | { + env: StringEnvValue; }; + export type StringEnvValue = 'warp_account_addr'; export type StringOp = 'starts_with' | 'ends_with' | 'contains' | 'eq' | 'neq'; export type NumValueFor_Uint256And_NumExprOpAnd_IntFnOp = | { @@ -112,10 +116,10 @@ export module warp_resolver { export type DecimalFnOp = 'abs' | 'neg' | 'floor' | 'sqrt' | 'ceil'; export type Uint64 = string; export type TimeOp = 'lt' | 'gt'; - export interface GenExprFor_ValueFor_StringAnd_StringOp { - left: ValueFor_String; + export interface GenExprFor_StringValueFor_StringAnd_StringOp { + left: StringValueFor_String; op: StringOp; - right: ValueFor_String; + right: StringValueFor_String; } export interface GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp { left: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; @@ -493,14 +497,18 @@ export module warp_resolver { query: QueryRequestFor_String; } export interface ExecuteValidateJobCreationMsg { - condition: string; - msgs: string; + executions: Execution[]; terminate_condition?: string | null; vars: string; } + export interface Execution { + condition: string; + msgs: string; + } export interface ExecuteHydrateVarsMsg { external_inputs?: ExternalInput[] | null; vars: string; + warp_account_addr?: string | null; } export interface ExternalInput { input: string; @@ -509,10 +517,12 @@ export module warp_resolver { export interface ExecuteResolveConditionMsg { condition: string; vars: string; + warp_account_addr?: string | null; } export interface ExecuteApplyVarFnMsg { status: JobStatus; vars: string; + warp_account_addr?: string | null; } export interface ExecuteHydrateMsgsMsg { msgs: string; @@ -542,22 +552,24 @@ export module warp_resolver { query: QueryRequestFor_String; } export interface QueryValidateJobCreationMsg { - condition: string; - msgs: string; + executions: Execution[]; terminate_condition?: string | null; vars: string; } export interface QueryHydrateVarsMsg { external_inputs?: ExternalInput[] | null; vars: string; + warp_account_addr?: string | null; } export interface QueryResolveConditionMsg { condition: string; vars: string; + warp_account_addr?: string | null; } export interface QueryApplyVarFnMsg { status: JobStatus; vars: string; + warp_account_addr?: string | null; } export interface QueryHydrateMsgsMsg { msgs: string; @@ -576,8 +588,7 @@ export module warp_resolver { | { query: QueryVariable; }; - export type VariableKind = 'string' | 'uint' | 'int' | 'decimal' | 'timestamp' | 'bool' | 'amount' | 'asset' | 'json'; - export type UpdateFnValue = + export type FnValue = | { uint: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; } @@ -595,18 +606,24 @@ export module warp_resolver { } | { bool: string; + } + | { + string: StringValueFor_String; }; + export type VariableKind = 'string' | 'uint' | 'int' | 'decimal' | 'timestamp' | 'bool' | 'amount' | 'asset' | 'json'; export type Method = 'get' | 'post' | 'put' | 'patch' | 'delete'; export interface StaticVariable { encode: boolean; + init_fn: FnValue; kind: VariableKind; name: string; + reinitialize: boolean; update_fn?: UpdateFn | null; - value: string; + value?: string | null; } export interface UpdateFn { - on_error?: UpdateFnValue | null; - on_success?: UpdateFnValue | null; + on_error?: FnValue | null; + on_success?: FnValue | null; } export interface ExternalVariable { encode: boolean; diff --git a/src/types/contracts/warp_templates.ts b/src/types/contracts/warp_templates.ts index fc84e88..3b6a701 100644 --- a/src/types/contracts/warp_templates.ts +++ b/src/types/contracts/warp_templates.ts @@ -38,7 +38,7 @@ export module warp_templates { }; export type Expr = | { - string: GenExprFor_ValueFor_StringAnd_StringOp; + string: GenExprFor_StringValueFor_StringAnd_StringOp; } | { uint: GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp; @@ -58,13 +58,17 @@ export module warp_templates { | { bool: string; }; - export type ValueFor_String = + export type StringValueFor_String = | { simple: string; } | { ref: string; + } + | { + env: StringEnvValue; }; + export type StringEnvValue = 'warp_account_addr'; export type StringOp = 'starts_with' | 'ends_with' | 'contains' | 'eq' | 'neq'; export type NumValueFor_Uint256And_NumExprOpAnd_IntFnOp = | { @@ -133,8 +137,7 @@ export module warp_templates { | { query: QueryVariable; }; - export type VariableKind = 'string' | 'uint' | 'int' | 'decimal' | 'timestamp' | 'bool' | 'amount' | 'asset' | 'json'; - export type UpdateFnValue = + export type FnValue = | { uint: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; } @@ -152,7 +155,11 @@ export module warp_templates { } | { bool: string; + } + | { + string: StringValueFor_String; }; + export type VariableKind = 'string' | 'uint' | 'int' | 'decimal' | 'timestamp' | 'bool' | 'amount' | 'asset' | 'json'; export type Method = 'get' | 'post' | 'put' | 'patch' | 'delete'; export type QueryRequestFor_String = | { @@ -267,10 +274,10 @@ export module warp_templates { name: string; vars: Variable[]; } - export interface GenExprFor_ValueFor_StringAnd_StringOp { - left: ValueFor_String; + export interface GenExprFor_StringValueFor_StringAnd_StringOp { + left: StringValueFor_String; op: StringOp; - right: ValueFor_String; + right: StringValueFor_String; } export interface GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp { left: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; @@ -324,14 +331,16 @@ export module warp_templates { } export interface StaticVariable { encode: boolean; + init_fn: FnValue; kind: VariableKind; name: string; + reinitialize: boolean; update_fn?: UpdateFn | null; - value: string; + value?: string | null; } export interface UpdateFn { - on_error?: UpdateFnValue | null; - on_success?: UpdateFnValue | null; + on_error?: FnValue | null; + on_success?: FnValue | null; } export interface ExternalVariable { encode: boolean; diff --git a/src/utils/fee.ts b/src/utils/fee.ts index a4e3aba..34d3a44 100644 --- a/src/utils/fee.ts +++ b/src/utils/fee.ts @@ -1,110 +1,47 @@ import Big from 'big.js'; -import { max } from './big'; -import { NativeToken, NATIVE_TOKENS } from './token'; +import { warp_controller } from 'types'; -type FeeConfig = { - creationFeeMin: number; - creationFeeMax: number; - burnFeeMin: number; - maintenanceFeeMin: number; - maintenanceFeeMax: number; - nativeToken: NativeToken; -}; +export function computeCreationFee(queueSize: Big, config: warp_controller.Config): Big { + const x1 = Big(config.queue_size_left); + const y1 = Big(config.creation_fee_min); + const x2 = Big(config.queue_size_right); + const y2 = Big(config.creation_fee_max); -export const feeConfigByChainId: Record = { - 'pisco-1': { - creationFeeMin: 0.5, - creationFeeMax: 100, - burnFeeMin: 0.1, - maintenanceFeeMin: 0.05, - maintenanceFeeMax: 10, - nativeToken: NATIVE_TOKENS.LUNA, - }, - 'phoenix-1': { - creationFeeMin: 0.5, - creationFeeMax: 100, - burnFeeMin: 0.1, - maintenanceFeeMin: 0.05, - maintenanceFeeMax: 10, - nativeToken: NATIVE_TOKENS.LUNA, - }, - 'pion-1': { - creationFeeMin: 1, - creationFeeMax: 200, - burnFeeMin: 0.5, - maintenanceFeeMin: 0.1, - maintenanceFeeMax: 20, - nativeToken: NATIVE_TOKENS.NEUTRON, - }, - 'neutron-1': { - creationFeeMin: 1, - creationFeeMax: 200, - burnFeeMin: 0.5, - maintenanceFeeMin: 0.1, - maintenanceFeeMax: 20, - nativeToken: NATIVE_TOKENS.NEUTRON, - }, - 'injective-1': { - creationFeeMin: 0.05, - creationFeeMax: 10, - burnFeeMin: 0.025, - maintenanceFeeMin: 0.005, - maintenanceFeeMax: 1, - nativeToken: NATIVE_TOKENS.INJ, - }, - 'injective-888': { - creationFeeMin: 0.05, - creationFeeMax: 10, - burnFeeMin: 0.025, - maintenanceFeeMin: 0.005, - maintenanceFeeMax: 1, - nativeToken: NATIVE_TOKENS.INJ, - }, -}; + const slope = y2.minus(y1).div(x2.minus(x1)); -export function computeCreationFee(queue_size: number, feeConfig: FeeConfig): Big { - const x1 = 5000; - const y1 = feeConfig.creationFeeMin; - const x2 = 50000; - const y2 = feeConfig.creationFeeMax; - - const slope = (y2 - y1) / (x2 - x1); - const y_intercept = y1 - slope * x1; - - if (queue_size < x1) { - return Big(feeConfig.creationFeeMin); - } else if (queue_size < x2) { - return Big(slope * queue_size + y_intercept); + if (queueSize.lt(x1)) { + return y1; + } else if (queueSize.lt(x2)) { + return slope.times(queueSize).plus(y1.minus(slope.times(x1))); } else { - return Big(feeConfig.creationFeeMax); + return y2; } } -function sigmoid(x: number): number { - return 1 / (1 + Math.exp(-x)); -} +export function computeMaintenanceFee(durationDays: Big, config: warp_controller.Config): Big { + const x1 = Big(config.duration_days_left); + const y1 = Big(config.maintenance_fee_min); + const x2 = Big(config.duration_days_right); + const y2 = Big(config.maintenance_fee_max); -function smoothTransition(x: number, min: number, max: number, k: number = 0.2): number { - const a = min; - const b = max; - const c = (max + min) / 2; + const slope = y2.minus(y1).div(x2.minus(x1)); - const sigmoid_val = sigmoid(k * (x - c)); - - return a + (b - a) * sigmoid_val; -} - -export function computeMaintenanceFee(duration_days: number, feeConfig: FeeConfig, k: number = 0.2): Big { - if (duration_days < 10) { - return Big(feeConfig.maintenanceFeeMin); - } else if (duration_days <= 100) { - return Big(smoothTransition(duration_days, feeConfig.maintenanceFeeMin, feeConfig.maintenanceFeeMax, k)); + if (durationDays.lt(x1)) { + return y1; + } else if (durationDays.lt(x2)) { + return slope.times(durationDays).plus(y1.minus(slope.times(x1))); } else { - return Big(feeConfig.maintenanceFeeMax); + return y2; } } -export function computeBurnFee(jobReward: Big, feeConfig: FeeConfig): Big { - // config.create_fee_percentage - return max(Big(feeConfig.burnFeeMin), jobReward.mul(0.25)); +export function computeBurnFee(jobReward: Big, config: warp_controller.Config): Big { + const minFee: Big = Big(config.burn_fee_min); + const calculatedFee = jobReward.times(config.burn_fee_rate).div(100); + + if (calculatedFee.gt(minFee)) { + return calculatedFee; + } else { + return minFee; + } } From 5b1d3f9d7dfe96033870f90b80f62a77f215ed78 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Thu, 2 Nov 2023 17:51:49 +0100 Subject: [PATCH 08/44] port composers --- src/composers/condition.ts | 22 +++++++++++----------- src/composers/job.ts | 30 ++++++++++++++---------------- src/composers/variable.ts | 28 +++++++++++++++++++--------- src/types/job.ts | 18 ++++++++++++++---- 4 files changed, 58 insertions(+), 40 deletions(-) diff --git a/src/composers/condition.ts b/src/composers/condition.ts index e80af2e..5955c49 100644 --- a/src/composers/condition.ts +++ b/src/composers/condition.ts @@ -19,11 +19,11 @@ export class ConditionComposer { } public string( - left: warp_resolver.ValueFor_String, + left: warp_resolver.StringValueFor_String, op: warp_resolver.StringOp, - right: warp_resolver.ValueFor_String + right: warp_resolver.StringValueFor_String ): warp_resolver.Condition { - const expr: warp_resolver.GenExprFor_ValueFor_StringAnd_StringOp = { left, op, right }; + const expr: warp_resolver.GenExprFor_StringValueFor_StringAnd_StringOp = { left, op, right }; return this.expr({ string: expr }); } @@ -161,37 +161,37 @@ export class DecimalValueComposer { } export class StringValueComposer { - public simple(value: string): warp_resolver.ValueFor_String { + public simple(value: string): warp_resolver.StringValueFor_String { return { simple: value }; } - public ref(ref: warp_resolver.Variable): warp_resolver.ValueFor_String { + public ref(ref: warp_resolver.Variable): warp_resolver.StringValueFor_String { return { ref: `$warp.variable.${variableName(ref)}` }; } } export class UpdateFnComposer { - public uint(value: warp_resolver.NumValueFor_Uint256And_NumExprOpAnd_IntFnOp): warp_resolver.UpdateFnValue { + public uint(value: warp_resolver.NumValueFor_Uint256And_NumExprOpAnd_IntFnOp): warp_resolver.FnValue { return { uint: value }; } - public int(value: warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp): warp_resolver.UpdateFnValue { + public int(value: warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp): warp_resolver.FnValue { return { int: value }; } - public decimal(value: warp_resolver.NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp): warp_resolver.UpdateFnValue { + public decimal(value: warp_resolver.NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp): warp_resolver.FnValue { return { decimal: value }; } - public timestamp(value: warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp): warp_resolver.UpdateFnValue { + public timestamp(value: warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp): warp_resolver.FnValue { return { timestamp: value }; } - public block_height(value: warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp): warp_resolver.UpdateFnValue { + public block_height(value: warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp): warp_resolver.FnValue { return { block_height: value }; } - public bool(value: warp_resolver.Variable): warp_resolver.UpdateFnValue { + public bool(value: warp_resolver.Variable): warp_resolver.FnValue { return { bool: `$warp.variable.${variableName(value)}` }; } } diff --git a/src/composers/job.ts b/src/composers/job.ts index 8c7dbd0..d63ce71 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -1,5 +1,7 @@ import { warp_controller, warp_resolver } from '../types/contracts'; +type Execution = [warp_resolver.Condition, warp_resolver.CosmosMsgFor_Empty[]]; + export class JobSequenceMsgComposer { static new() { return new JobSequenceMsgComposer(); @@ -44,9 +46,9 @@ export class CreateJobMsgComposer { private _description: string; private _labels: string[]; private _assetsToWithdraw: warp_controller.AssetInfo[] | undefined; - private _msgs: warp_resolver.CosmosMsgFor_Empty[] = []; private _vars: warp_resolver.Variable[] = []; - private _condition: warp_resolver.Condition | undefined; + private _executions: Execution[] = []; + private _durationDays: string; static new(): CreateJobMsgComposer { return new CreateJobMsgComposer(); @@ -82,23 +84,23 @@ export class CreateJobMsgComposer { return this; } - assetsToWithdraw(assetsToWithdraw: warp_controller.AssetInfo[]): CreateJobMsgComposer { - this._assetsToWithdraw = assetsToWithdraw; + durationDays(durationDays: string): CreateJobMsgComposer { + this._durationDays = durationDays; return this; } - msg(msg: warp_resolver.CosmosMsgFor_Empty): CreateJobMsgComposer { - this._msgs.push(msg); + assetsToWithdraw(assetsToWithdraw: warp_controller.AssetInfo[]): CreateJobMsgComposer { + this._assetsToWithdraw = assetsToWithdraw; return this; } - cond(condition: warp_resolver.Condition): CreateJobMsgComposer { - this._condition = condition; + executions(executions: Execution[]): CreateJobMsgComposer { + this._executions = executions; return this; } - var(variable: warp_resolver.Variable): CreateJobMsgComposer { - this._vars.push(variable); + vars(vars: warp_resolver.Variable[]): CreateJobMsgComposer { + this._vars = vars; return this; } @@ -114,10 +116,6 @@ export class CreateJobMsgComposer { throw new Error('All required fields must be provided'); } - if (this._condition === undefined) { - throw new Error('Condition must be provided'); - } - const createJobMsg: warp_controller.CreateJobMsg = { name: this._name, recurring: this._recurring, @@ -125,8 +123,8 @@ export class CreateJobMsgComposer { reward: this._reward, description: this._description, labels: this._labels, - condition: JSON.stringify(this._condition), - msgs: JSON.stringify(this._msgs), + executions: this._executions.map((e) => ({ condition: JSON.stringify(e[0]), msgs: JSON.stringify(e[1]) })), + duration_days: this._durationDays, vars: JSON.stringify(this._vars), assets_to_withdraw: this._assetsToWithdraw, }; diff --git a/src/composers/variable.ts b/src/composers/variable.ts index d667143..7ed9619 100644 --- a/src/composers/variable.ts +++ b/src/composers/variable.ts @@ -5,7 +5,7 @@ class StaticVariableComposer { private variable: warp_resolver.StaticVariable; constructor() { - this.variable = { kind: 'string', name: '', value: '', encode: false }; + this.variable = { kind: 'string', name: '', value: '', encode: false, init_fn: null, reinitialize: false }; } kind(kind: warp_resolver.VariableKind): StaticVariableComposer { @@ -28,7 +28,17 @@ class StaticVariableComposer { return this; } - onSuccess(fn: warp_resolver.UpdateFnValue): StaticVariableComposer { + reinitialize(value: boolean): StaticVariableComposer { + this.variable.reinitialize = value; + return this; + } + + onInit(value: warp_resolver.FnValue): StaticVariableComposer { + this.variable.init_fn = value; + return this; + } + + onSuccess(fn: warp_resolver.FnValue): StaticVariableComposer { this.variable.update_fn = { ...(this.variable.update_fn ?? {}), on_success: fn, @@ -37,7 +47,7 @@ class StaticVariableComposer { return this; } - onError(fn: warp_resolver.UpdateFnValue): StaticVariableComposer { + onError(fn: warp_resolver.FnValue): StaticVariableComposer { this.variable.update_fn = { ...(this.variable.update_fn ?? {}), on_error: fn, @@ -59,7 +69,7 @@ class ExternalVariableComposer { kind: 'string', name: '', reinitialize: false, - init_fn: {} as warp_resolver.ExternalExpr, + init_fn: null, encode: false, }; } @@ -94,7 +104,7 @@ class ExternalVariableComposer { return this; } - onSuccess(fn: warp_resolver.UpdateFnValue): ExternalVariableComposer { + onSuccess(fn: warp_resolver.FnValue): ExternalVariableComposer { this.variable.update_fn = { ...(this.variable.update_fn ?? {}), on_success: fn, @@ -103,7 +113,7 @@ class ExternalVariableComposer { return this; } - onError(fn: warp_resolver.UpdateFnValue): ExternalVariableComposer { + onError(fn: warp_resolver.FnValue): ExternalVariableComposer { this.variable.update_fn = { ...(this.variable.update_fn ?? {}), on_error: fn, @@ -125,7 +135,7 @@ class QueryVariableComposer { kind: 'string', name: '', reinitialize: false, - init_fn: {} as warp_resolver.QueryExpr, + init_fn: null, encode: false, }; } @@ -160,7 +170,7 @@ class QueryVariableComposer { return this; } - onSuccess(fn: warp_resolver.UpdateFnValue): QueryVariableComposer { + onSuccess(fn: warp_resolver.FnValue): QueryVariableComposer { this.variable.update_fn = { ...(this.variable.update_fn ?? {}), on_success: fn, @@ -169,7 +179,7 @@ class QueryVariableComposer { return this; } - onError(fn: warp_resolver.UpdateFnValue): QueryVariableComposer { + onError(fn: warp_resolver.FnValue): QueryVariableComposer { this.variable.update_fn = { ...(this.variable.update_fn ?? {}), on_error: fn, diff --git a/src/types/job.ts b/src/types/job.ts index a91fb09..2d55dc9 100644 --- a/src/types/job.ts +++ b/src/types/job.ts @@ -1,12 +1,16 @@ import Big from 'big.js'; import { warp_controller, warp_resolver } from './contracts'; -export type Job = Omit & { - vars: warp_resolver.Variable[]; +export type Execution = { condition: warp_resolver.Condition; msgs: warp_resolver.CosmosMsgFor_Empty[]; }; +export type Job = Omit & { + executions: Execution[]; + vars: warp_resolver.Variable[]; +}; + export type JobResponse = { job: Job; }; @@ -16,12 +20,18 @@ export type JobsResponse = { jobs: Job[]; }; +export const parseExecution = (execution: warp_controller.Execution): Execution => { + return { + msgs: JSON.parse(execution.msgs) as warp_resolver.CosmosMsgFor_Empty[], + condition: JSON.parse(execution.condition) as warp_resolver.Condition, + }; +}; + export const parseJob = (job: warp_controller.Job): Job => { return { ...job, vars: JSON.parse(job.vars) as warp_resolver.Variable[], - condition: JSON.parse(job.condition) as warp_resolver.Condition, - msgs: JSON.parse(job.msgs) as warp_resolver.CosmosMsgFor_Empty[], + executions: job.executions.map(parseExecution), }; }; From b4146c96d580fd425755f845ff403c31fe222e2f Mon Sep 17 00:00:00 2001 From: simke9445 Date: Thu, 2 Nov 2023 17:52:05 +0100 Subject: [PATCH 09/44] port conditions and sdk --- src/condition.ts | 82 ++++++++++++++++++++++++++---------------------- src/sdk.ts | 13 ++++++-- 2 files changed, 56 insertions(+), 39 deletions(-) diff --git a/src/condition.ts b/src/condition.ts index a4705be..34451ea 100644 --- a/src/condition.ts +++ b/src/condition.ts @@ -6,49 +6,53 @@ import { Big } from 'big.js'; import { Wallet } from './wallet'; import { extractVariableName, resolveExternalVariable, variableName } from './variables'; import { ContractAddresses } from 'modules/chain'; +import { Job } from './types'; +import { WarpSdk } from 'sdk'; export class Condition { public wallet: Wallet; public contracts: ContractAddresses; + public sdk: WarpSdk; - constructor(wallet: Wallet, contracts: ContractAddresses) { + constructor(wallet: Wallet, contracts: ContractAddresses, sdk: WarpSdk) { this.wallet = wallet; this.contracts = contracts; + this.sdk = sdk; } - public resolveCond = async (cond: warp_resolver.Condition, vars: warp_resolver.Variable[]): Promise => { + public resolveCond = async (cond: warp_resolver.Condition, job: Job): Promise => { if ('and' in cond) { - const all = await Promise.all(cond.and.map((c) => this.resolveCond(c, vars))); + const all = await Promise.all(cond.and.map((c) => this.resolveCond(c, job))); return every(all); } if ('or' in cond) { - const all = await Promise.all(cond.or.map((c) => this.resolveCond(c, vars))); + const all = await Promise.all(cond.or.map((c) => this.resolveCond(c, job))); return some(all); } if ('not' in cond) { - return !this.resolveCond(cond.not, vars); + return !this.resolveCond(cond.not, job); } - return this.resolveExpr(cond.expr, vars); + return this.resolveExpr(cond.expr, job); }; - public resolveExpr = async (expr: warp_resolver.Expr, vars: warp_resolver.Variable[]): Promise => { + public resolveExpr = async (expr: warp_resolver.Expr, job: Job): Promise => { if ('string' in expr) { - return this.resolveExprString(expr.string, vars); + return this.resolveExprString(expr.string, job); } if ('int' in expr) { - return this.resolveExprNum(expr.int, vars); + return this.resolveExprNum(expr.int, job); } if ('uint' in expr) { - return this.resolveExprNum(expr.uint, vars); + return this.resolveExprNum(expr.uint, job); } if ('decimal' in expr) { - return this.resolveExprNum(expr.decimal, vars); + return this.resolveExprNum(expr.decimal, job); } if ('timestamp' in expr) { @@ -60,7 +64,7 @@ export class Condition { } if ('bool' in expr) { - return this.resolveExprBool(expr.bool, vars); + return this.resolveExprBool(expr.bool, job); } return false; @@ -83,25 +87,29 @@ export class Condition { }; public resolveExprString = async ( - expr: warp_resolver.GenExprFor_ValueFor_StringAnd_StringOp, - vars: warp_resolver.Variable[] + expr: warp_resolver.GenExprFor_StringValueFor_StringAnd_StringOp, + job: Job ): Promise => { - const left = await this.resolveStringValue(expr.left, vars); - const right = await this.resolveStringValue(expr.right, vars); + const left = await this.resolveStringValue(expr.left, job); + const right = await this.resolveStringValue(expr.right, job); return this.resolveStringOp(left, right, expr.op); }; - public resolveStringValue = async ( - value: warp_resolver.ValueFor_String, - vars: warp_resolver.Variable[] - ): Promise => { + public resolveStringValue = async (value: warp_resolver.StringValueFor_String, job: Job): Promise => { if ('simple' in value) { return String(value.simple); } + if ('env' in value) { + if (value.env === 'warp_account_addr') { + const account = await this.sdk.account(job.owner); + return account.account; + } + } + if ('ref' in value) { - return this.resolveVariable(this.variable(value.ref, vars), (v) => String(v)); + return this.resolveVariable(this.variable(value.ref, job), (v) => String(v)); } }; @@ -110,10 +118,10 @@ export class Condition { | warp_resolver.GenExprFor_NumValueForInt128And_NumExprOpAnd_IntFnOpAnd_NumOp | warp_resolver.GenExprFor_NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOpAnd_NumOp | warp_resolver.GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp, - vars: warp_resolver.Variable[] + job: Job ): Promise => { - const left = await this.resolveNumValue(expr.left, vars); - const right = await this.resolveNumValue(expr.right, vars); + const left = await this.resolveNumValue(expr.left, job); + const right = await this.resolveNumValue(expr.right, job); return this.resolveNumOp(left, right, expr.op); }; @@ -123,22 +131,22 @@ export class Condition { | warp_resolver.NumValueForInt128And_NumExprOpAnd_IntFnOp | warp_resolver.NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp | warp_resolver.NumValueFor_Uint256And_NumExprOpAnd_IntFnOp, - vars: warp_resolver.Variable[] + job: Job ): Promise => { if ('simple' in value) { return Big(value.simple); } if ('expr' in value) { - return this.resolveNumExpr(value.expr, vars); + return this.resolveNumExpr(value.expr, job); } if ('fn' in value) { - return this.resolveNumFn(value.fn, vars); + return this.resolveNumFn(value.fn, job); } if ('ref' in value) { - return this.resolveVariable(this.variable(value.ref, vars), (v) => Big(v)); + return this.resolveVariable(this.variable(value.ref, job), (v) => Big(v)); } if ('env' in value) { @@ -159,9 +167,9 @@ export class Condition { | warp_resolver.NumFnValueForInt128And_NumExprOpAnd_IntFnOp | warp_resolver.NumFnValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp | warp_resolver.NumFnValueFor_Uint256And_NumExprOpAnd_IntFnOp, - vars: warp_resolver.Variable[] + job: Job ): Promise { - const val = await this.resolveNumValue(fn.right, vars); + const val = await this.resolveNumValue(fn.right, job); switch (fn.op) { case 'abs': return val.abs(); @@ -181,10 +189,10 @@ export class Condition { | warp_resolver.NumExprValueForInt128And_NumExprOpAnd_IntFnOp | warp_resolver.NumExprValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp | warp_resolver.NumExprValueFor_Uint256And_NumExprOpAnd_IntFnOp, - vars: warp_resolver.Variable[] + job: Job ): Promise { - const left = await this.resolveNumValue(expr.left, vars); - const right = await this.resolveNumValue(expr.right, vars); + const left = await this.resolveNumValue(expr.left, job); + const right = await this.resolveNumValue(expr.right, job); switch (expr.op) { case 'add': @@ -200,9 +208,9 @@ export class Condition { } } - public variable(ref: string, vars: warp_resolver.Variable[]): warp_resolver.Variable { + public variable(ref: string, job: Job): warp_resolver.Variable { const name = extractVariableName(ref); - const v = vars.find((v) => variableName(v) === name); + const v = job.vars.find((v) => variableName(v) === name); if (!v) { throw Error(`Unknown variable reference: ${name}.`); @@ -211,8 +219,8 @@ export class Condition { return v; } - public resolveExprBool(ref: string, vars: warp_resolver.Variable[]): Promise { - const v = this.variable(ref, vars); + public resolveExprBool(ref: string, job: Job): Promise { + const v = this.variable(ref, job); return this.resolveVariable(v, (val) => Boolean(val)); } diff --git a/src/sdk.ts b/src/sdk.ts index bf8ad1b..cc5e88a 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -35,7 +35,7 @@ export class WarpSdk { this.wallet = wallet(walletLike, chainConfig); this.tx = new TxModule(this); this.chain = new ChainModule(chainConfig); - this.condition = new Condition(this.wallet, this.chain.contracts); + this.condition = new Condition(this.wallet, this.chain.contracts, this); } public static lcdClientConfig( @@ -56,7 +56,16 @@ export class WarpSdk { public async isJobActive(jobId: string): Promise { const job = await this.job(jobId); - return this.condition.resolveCond(job.condition, job.vars); + + for (let execution of job.executions) { + const isCondActive = this.condition.resolveCond(execution.condition, job); + + if (isCondActive) { + return true; + } + } + + return false; } public async jobs(opts: warp_controller.QueryJobsMsg = {}): Promise { From 3f5dd462a39c4ebcfbcfb1420a59866a45431d14 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Thu, 2 Nov 2023 17:52:13 +0100 Subject: [PATCH 10/44] port examples --- src/examples/example_astro.ts | 59 +++++---- src/examples/example_cross_chain.ts | 188 ++++++++++++++++++++++++++++ src/examples/example_eris.ts | 7 +- 3 files changed, 224 insertions(+), 30 deletions(-) create mode 100644 src/examples/example_cross_chain.ts diff --git a/src/examples/example_astro.ts b/src/examples/example_astro.ts index 37ba7be..c19df1d 100644 --- a/src/examples/example_astro.ts +++ b/src/examples/example_astro.ts @@ -73,36 +73,41 @@ const createJobMsg = job .description('This job creates an astroport limit order.') .labels([]) .reward('50000') - .cond(condition) - .var(astroReceived) - .msg( - msg.execute( - astroportContract, - { - execute_swap_operations: { - max_spread: limitOrder.maxSpread, - minimum_receive: limitOrder.astroPurchaseAmount, - operations: [ - { - astro_swap: { - ask_asset_info: { - token: { - contract_addr: limitOrder.astroTokenContract, - }, - }, - offer_asset_info: { - native_token: { - denom: 'uluna', + .vars([astroReceived]) + .durationDays('30') + .executions([ + [ + condition, + [ + msg.execute( + astroportContract, + { + execute_swap_operations: { + max_spread: limitOrder.maxSpread, + minimum_receive: limitOrder.astroPurchaseAmount, + operations: [ + { + astro_swap: { + ask_asset_info: { + token: { + contract_addr: limitOrder.astroTokenContract, + }, + }, + offer_asset_info: { + native_token: { + denom: 'uluna', + }, + }, }, }, - }, + ], }, - ], - }, - }, - [{ denom: 'uluna', amount: limitOrder.lunaOfferAmount }] - ) - ) + }, + [{ denom: 'uluna', amount: limitOrder.lunaOfferAmount }] + ), + ], + ], + ]) .compose(); sdk.createJob(sender, createJobMsg).then((response) => { diff --git a/src/examples/example_cross_chain.ts b/src/examples/example_cross_chain.ts new file mode 100644 index 0000000..a579b60 --- /dev/null +++ b/src/examples/example_cross_chain.ts @@ -0,0 +1,188 @@ +export { TerraTxError } from '../wallet/utils'; +import dotenv from 'dotenv'; +import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; +import { WarpSdk } from '../sdk'; +import { uint, cond, msg, variable, job, query, account } from '../composers'; +import { addYears } from 'date-fns'; + +dotenv.config(); + +const piscoLcdClientConfig: LCDClientConfig = { + lcd: 'https://pisco-lcd.terra.dev', + chainID: 'pisco-1', + gasAdjustment: 1.75, + gasPrices: { uluna: 0.15 }, + prefix: 'terra', +}; + +const lcd = new LCDClient({ + 'pisco-1': piscoLcdClientConfig, +}); + +const wallet = new Wallet(lcd, new MnemonicKey({ mnemonic: '...' })); + +const sdk = new WarpSdk(wallet, piscoLcdClientConfig); +const sender = wallet.key.accAddress(piscoLcdClientConfig.prefix); + +const neutronRouter = 'neutron12jm24l9lr9cupufqjuxpdjnnweana4h66tsx5cl800mke26td26sq7m05p'; +const neutronBurnAccount = 'neutron109ylcvevv96f48jp6slzyuq8tu85g7u4xvmz3lq4ngw7d7r4smsq5q6ap4'; //todo +const terraRecipient = 'terra10e3392r94esu5dcwcuj9tt3mw5sq48uazarhpl77hfvcplfed04qhsrfn7'; //todo +const transferChannel = 'channel-3'; +const usdt = 'neutron1h6pztc3fn7h22jm60xx90tk7hln7xg8x0nazef58gqv0n4uw9vqq9khy43'; +const astro = 'ibc/EFB00E728F98F0C4BBE8CA362123ACAB466EDA2826DC6837E49F4C1902F21BBA'; + +let swapMsg = { + execute_swap_operations: { + operations: [ + { + astro_swap: { + offer_asset_info: { + native_token: { + denom: 'untrn', + }, + }, + ask_asset_info: { + token: { + contract_addr: usdt, + }, + }, + }, + }, + { + astro_swap: { + offer_asset_info: { + token: { + contract_addr: usdt, + }, + }, + ask_asset_info: { + native_token: { + denom: astro, + }, + }, + }, + }, + ], + minimum_receive: '$warp.variable.simulate_astro_amount', + }, +}; + +const swapVariable = variable + .static() + .kind('string') + .name('swap_msg') + .value(JSON.stringify(swapMsg)) + .encode(true) + .compose(); + +const routedSwapMsg = account.generic([ + msg.execute(neutronRouter, variable.ref(swapVariable), [ + { denom: 'untrn', amount: '$warp.variable.neutron_balance' }, + ]), +]); + +const transferMsg = account.generic([ + msg.transfer({ denom: astro, amount: '1' }, transferChannel, { timestamp: '1692915449102000000' }, terraRecipient), +]); + +let simulateAstroQuery = { + simulate_swap_operations: { + offer_amount: '$warp.variable.neutron_balance', + operations: [ + { + astro_swap: { + offer_asset_info: { + native_token: { + denom: 'untrn', + }, + }, + ask_asset_info: { + token: { + contract_addr: 'neutron1h6pztc3fn7h22jm60xx90tk7hln7xg8x0nazef58gqv0n4uw9vqq9khy43', + }, + }, + }, + }, + { + astro_swap: { + offer_asset_info: { + token: { + contract_addr: 'neutron1h6pztc3fn7h22jm60xx90tk7hln7xg8x0nazef58gqv0n4uw9vqq9khy43', + }, + }, + ask_asset_info: { + native_token: { + denom: 'ibc/EFB00E728F98F0C4BBE8CA362123ACAB466EDA2826DC6837E49F4C1902F21BBA', + }, + }, + }, + }, + ], + }, +}; + +const simulateAstroAmount = variable + .query() + .kind('uint') + .name('simulate_astro_amount') + .onInit({ query: query.smart(neutronRouter, simulateAstroQuery), selector: '$.amount' }) + .encode(false) + .compose(); + +const timeoutTimestamp = variable + .static() + .kind('uint') + .name('timeout_timestamp') + .encode(false) + .value(addYears(new Date(), 1).getTime() * 1000000 + '') + .compose(); + +const untrnAmount = variable + .query() + .kind('uint') + .name('neutron_balance') + .onInit({ query: query.balance(neutronBurnAccount, 'untrn'), selector: '$.amount.amount' }) //todo: create and get burn account on neutron + .encode(false) + .compose(); + +const routedSwapVariable = variable + .static() + .kind('string') + .name('routed_swap_msg') + .value(JSON.stringify(routedSwapMsg)) + .encode(true) + .compose(); + +const transferVariable = variable + .static() + .kind('string') + .name('transfer_msg') + .value(JSON.stringify(transferMsg)) + .encode(true) + .compose(); + +const condition = cond.uint(uint.ref(untrnAmount), 'gt', uint.simple('10000')); + +const createJobMsg = job + .create() + .name('swap-and-send') + .description('') + .recurring(true) + .requeueOnEvict(true) + .reward('1000') + .vars([untrnAmount, timeoutTimestamp, simulateAstroAmount, transferVariable, swapVariable, routedSwapVariable]) + .executions([ + [ + condition, + [ + msg.execute(neutronBurnAccount, variable.ref(routedSwapVariable)), + msg.execute(neutronBurnAccount, variable.ref(transferVariable)), + ], + ], + ]) + .labels([]) + .compose(); + +sdk.createJob(sender, createJobMsg).then((response) => { + console.log(response); +}); diff --git a/src/examples/example_eris.ts b/src/examples/example_eris.ts index 81dc3bc..99a2946 100644 --- a/src/examples/example_eris.ts +++ b/src/examples/example_eris.ts @@ -38,9 +38,10 @@ const createJobMsg = job .recurring(true) .requeueOnEvict(true) .reward('50000') - .cond(condition) - .var(nextExecution) - .msg(msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })) + .vars([nextExecution]) + .executions([ + [condition, [msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })]], + ]) .compose(); sdk.createJob(sender, createJobMsg).then((response) => { From 07700ce3be60fb589881381d1cce6affef78421d Mon Sep 17 00:00:00 2001 From: simke9445 Date: Fri, 3 Nov 2023 15:27:40 +0100 Subject: [PATCH 11/44] api updates --- src/modules/tx.ts | 7 +------ src/sdk.ts | 5 +++-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 501397d..148de45 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -16,12 +16,7 @@ export class TxModule { } public async createJob(sender: string, msg: warp_controller.CreateJobMsg, funds?: Fund[]): Promise { - const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); - - const rewardFund: Fund = { native: { denom: nativeDenom, amount: msg.reward } }; - const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; - - const createAccountTx = await this.createAccount(sender, totalFunds); + const createAccountTx = await this.createAccount(sender, funds); return TxBuilder.new(this.warpSdk.chain.config) .tx(createAccountTx) diff --git a/src/sdk.ts b/src/sdk.ts index cc5e88a..4a42756 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -203,10 +203,11 @@ export class WarpSdk { return { ...controllerState }; } - public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg): Promise { + // if reward is not provided, reward estimate is used + public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg, reward?: string): Promise { const state = await this.state(); const config = await this.config(); - const jobReward = await this.estimateJobReward(sender, estimateJobMsg); + const jobReward = reward ? Big(reward) : await this.estimateJobReward(sender, estimateJobMsg); const burnFee = computeBurnFee(jobReward, config); const maintenanceFee = computeMaintenanceFee(Big(estimateJobMsg.duration_days), config); From db7f66704f124015a01e171d514aeba26a5fce10 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Fri, 3 Nov 2023 16:14:24 +0100 Subject: [PATCH 12/44] add migrate scripts + commands --- package.json | 2 + src/migrate/migrate_finished_jobs.ts | 94 ++++++++++++++++++++++++++++ src/migrate/migrate_pending_jobs.ts | 93 +++++++++++++++++++++++++++ 3 files changed, 189 insertions(+) create mode 100644 src/migrate/migrate_finished_jobs.ts create mode 100644 src/migrate/migrate_pending_jobs.ts diff --git a/package.json b/package.json index 2bb2bcc..25194ca 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,8 @@ "build:browser": "BUILD_TARGET=browser node build.js", "start": "yarn bot-terra", "bot-terra": "esbuild src/bot.ts --bundle --platform=node --outdir=dist --outbase=src && node ./dist/bot.js ./config.terra.json", + "migrate-pending-jobs-terra": "esbuild src/migrate/migrate_pending_jobs.ts --bundle --platform=node --outdir=dist --outbase=src && node ./dist/migrate/migrate_pending_jobs.js ./config.terra.json", + "migrate-finished-jobs-terra": "esbuild src/migrate/migrate_finished_jobs.ts --bundle --platform=node --outdir=dist --outbase=src && node ./dist/migrate/migrate_finished_jobs.js ./config.terra.json", "bot-neutron": "esbuild src/bot.ts --bundle --platform=node --outdir=dist --outbase=src && node ./dist/bot.js ./config.neutron.json", "bot-injective": "esbuild src/bot.ts --bundle --platform=node --outdir=dist --outbase=src && node ./dist/bot.js ./config.injective.json", "bot-nibiru": "esbuild src/bot.ts --bundle --platform=node --outdir=dist --outbase=src && node ./dist/bot.js ./config.nibiru.json", diff --git a/src/migrate/migrate_finished_jobs.ts b/src/migrate/migrate_finished_jobs.ts new file mode 100644 index 0000000..6368391 --- /dev/null +++ b/src/migrate/migrate_finished_jobs.ts @@ -0,0 +1,94 @@ +import axios from 'axios'; +import dotenv from 'dotenv'; +import { + Coins, + CreateTxOptions, + MnemonicKey, + MsgExecuteContract, + WaitTxBroadcastResult, + Wallet, +} from '@terra-money/feather.js'; +import { WarpSdk } from '../sdk'; +import { warp_controller } from '../types/contracts'; +import { ChainName, NetworkName } from 'modules'; +import fs from 'fs'; + +dotenv.config(); + +const configPath = process.argv[2]; +const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + +const lcd = WarpSdk.lcdClient({ networks: [config.NETWORK as NetworkName], chains: [config.CHAIN as ChainName] }); +const lcdClientConfig = Object.values(lcd.config)[0]; +const wallet = new Wallet(lcd, new MnemonicKey({ mnemonic: config.MNEMONIC_KEY, coinType: Number(config.COIN_TYPE) })); +const sdk = new WarpSdk(wallet, lcdClientConfig); + +export const tryExecute = async ( + wallet: Wallet, + msgs: MsgExecuteContract[] +): Promise => { + const txOptions: CreateTxOptions = { + msgs: msgs, + chainID: lcdClientConfig.chainID, + }; + + try { + const tx = await wallet.createAndSignTx(txOptions); + + return await wallet.lcd.tx.broadcast(tx, lcdClientConfig.chainID); + } catch (error) { + console.log({ error }); + + if (axios.isAxiosError(error) && Boolean(error.response?.data)) { + return `Code=${error.response.data['code']} Message=${error.response.data['message']}`; + } + + return error.message; + } +}; + +function executeMsg(sender: string, contract: string, msg: T, coins?: Coins.Input) { + return new MsgExecuteContract(sender, contract, msg, coins); +} + +const createMigrateJobsMsg = (startAfter: string, limit: number) => { + return executeMsg>( + wallet.key.accAddress(lcdClientConfig.prefix), + sdk.chain.contracts.controller, + { + migrate_finished_jobs: { + start_after: startAfter, + limit: limit, + }, + } + ); +}; + +const loop = async () => { + let startAfter = 0; + const limit = 50; + + // TODO: Update to current max job id on testnet/mainnet + const maxJobId = 1000; + + while (startAfter <= maxJobId) { + try { + const batchLimit = startAfter + limit > maxJobId ? maxJobId - startAfter + 1 : limit; + const migrateMsg = createMigrateJobsMsg(startAfter.toString(), batchLimit); + const result = await tryExecute(wallet, [migrateMsg]); + console.log(`Migrated jobs starting from ID ${startAfter} with limit ${batchLimit}:`, result); + + startAfter += limit; + } catch (error) { + console.error(`Failed to migrate jobs starting from ID ${startAfter}:`, error); + break; // Stop the loop if there is an error + } + + console.log('Sleeping for 1 second...'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + + console.log('Migration process has completed.'); +}; + +loop(); diff --git a/src/migrate/migrate_pending_jobs.ts b/src/migrate/migrate_pending_jobs.ts new file mode 100644 index 0000000..234cc04 --- /dev/null +++ b/src/migrate/migrate_pending_jobs.ts @@ -0,0 +1,93 @@ +import axios from 'axios'; +import dotenv from 'dotenv'; +import { + Coins, + CreateTxOptions, + MnemonicKey, + MsgExecuteContract, + WaitTxBroadcastResult, + Wallet, +} from '@terra-money/feather.js'; +import { WarpSdk } from '../sdk'; +import { warp_controller } from '../types/contracts'; +import { ChainName, NetworkName } from 'modules'; +import fs from 'fs'; + +dotenv.config(); + +const configPath = process.argv[2]; +const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + +const lcd = WarpSdk.lcdClient({ networks: [config.NETWORK as NetworkName], chains: [config.CHAIN as ChainName] }); +const lcdClientConfig = Object.values(lcd.config)[0]; +const wallet = new Wallet(lcd, new MnemonicKey({ mnemonic: config.MNEMONIC_KEY, coinType: Number(config.COIN_TYPE) })); +const sdk = new WarpSdk(wallet, lcdClientConfig); + +export const tryExecute = async ( + wallet: Wallet, + msgs: MsgExecuteContract[] +): Promise => { + const txOptions: CreateTxOptions = { + msgs: msgs, + chainID: lcdClientConfig.chainID, + }; + + try { + const tx = await wallet.createAndSignTx(txOptions); + + return await wallet.lcd.tx.broadcast(tx, lcdClientConfig.chainID); + } catch (error) { + console.log({ error }); + + if (axios.isAxiosError(error) && Boolean(error.response?.data)) { + return `Code=${error.response.data['code']} Message=${error.response.data['message']}`; + } + + return error.message; + } +}; + +function executeMsg(sender: string, contract: string, msg: T, coins?: Coins.Input) { + return new MsgExecuteContract(sender, contract, msg, coins); +} + +const createMigrateJobsMsg = (startAfter: string, limit: number) => { + return executeMsg>( + wallet.key.accAddress(lcdClientConfig.prefix), + sdk.chain.contracts.controller, + { + migrate_pending_jobs: { + start_after: startAfter, + limit: limit, + }, + } + ); +}; + +const loop = async () => { + let startAfter = 0; + const limit = 50; + // TODO: Update to current max job id on testnet/mainnet + const maxJobId = 1000; + + while (startAfter <= maxJobId) { + try { + const batchLimit = startAfter + limit > maxJobId ? maxJobId - startAfter + 1 : limit; + const migrateMsg = createMigrateJobsMsg(startAfter.toString(), batchLimit); + const result = await tryExecute(wallet, [migrateMsg]); + console.log(`Migrated jobs starting from ID ${startAfter} with limit ${batchLimit}:`, result); + + startAfter += limit; + } catch (error) { + console.error(`Failed to migrate jobs starting from ID ${startAfter}:`, error); + break; // Stop the loop if there is an error + } + + console.log('Sleeping for 1 second...'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + + console.log('Migration process has completed.'); +}; + +loop(); From f1ea31fe3b9ba5c925fc36e78b0777c6f4ea8c75 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Sat, 11 Nov 2023 17:33:30 +0100 Subject: [PATCH 13/44] refactor sdk to new contracts --- package.json | 6 +- src/composers/account.ts | 4 +- src/composers/job.ts | 8 - src/condition.ts | 3 +- src/examples/example_astro.ts | 1 - src/examples/example_cross_chain.ts | 1 - src/examples/example_eris.ts | 1 - src/migrate/migrate_finished_jobs.ts | 2 +- src/migrate/migrate_pending_jobs.ts | 2 +- src/modules/chain.ts | 6 +- src/modules/tx.ts | 151 +++++----- src/refs.injective.json | 8 + src/refs.neutron.json | 8 + src/refs.nibiru.json | 8 + src/refs.terra.json | 18 +- src/sdk.ts | 99 +++++-- src/types/contracts/index.ts | 4 +- src/types/contracts/warp_controller.ts | 97 +++--- src/types/contracts/warp_job_account.ts | 280 ++++++++++++++++++ .../contracts/warp_job_account_tracker.ts | 70 +++++ ...warp_account.ts => warp_legacy_account.ts} | 65 +--- src/types/job.ts | 58 ---- 22 files changed, 605 insertions(+), 295 deletions(-) create mode 100644 src/types/contracts/warp_job_account.ts create mode 100644 src/types/contracts/warp_job_account_tracker.ts rename src/types/contracts/{warp_account.ts => warp_legacy_account.ts} (80%) diff --git a/package.json b/package.json index 25194ca..61b20d6 100644 --- a/package.json +++ b/package.json @@ -42,9 +42,11 @@ "generate-types": { "contracts": [ "warp-controller", - "warp-account", + "warp-legacy-account", "warp-resolver", - "warp-templates" + "warp-templates", + "warp-job-account", + "warp-job-account-tracker" ], "output": "src/types/contracts" }, diff --git a/src/composers/account.ts b/src/composers/account.ts index 5ffab94..96051bf 100644 --- a/src/composers/account.ts +++ b/src/composers/account.ts @@ -1,6 +1,6 @@ -import { warp_account, warp_resolver } from '../types'; +import { warp_job_account, warp_resolver } from '../types'; -type GenericMsg = Extract; +type GenericMsg = Extract; export class AccountComposer { generic(msgs: warp_resolver.CosmosMsgFor_Empty[]): GenericMsg { diff --git a/src/composers/job.ts b/src/composers/job.ts index d63ce71..72b58a7 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -41,7 +41,6 @@ export class JobSequenceMsgComposer { export class CreateJobMsgComposer { private _name: string | undefined; private _recurring: boolean | undefined; - private _requeue_on_evict: boolean | undefined; private _reward: warp_controller.Uint128 | undefined; private _description: string; private _labels: string[]; @@ -64,11 +63,6 @@ export class CreateJobMsgComposer { return this; } - requeueOnEvict(requeue_on_evict: boolean): CreateJobMsgComposer { - this._requeue_on_evict = requeue_on_evict; - return this; - } - reward(reward: warp_controller.Uint128): CreateJobMsgComposer { this._reward = reward; return this; @@ -108,7 +102,6 @@ export class CreateJobMsgComposer { if ( this._name === undefined || this._recurring === undefined || - this._requeue_on_evict === undefined || this._reward === undefined || this._description === undefined || this._labels === undefined @@ -119,7 +112,6 @@ export class CreateJobMsgComposer { const createJobMsg: warp_controller.CreateJobMsg = { name: this._name, recurring: this._recurring, - requeue_on_evict: this._requeue_on_evict, reward: this._reward, description: this._description, labels: this._labels, diff --git a/src/condition.ts b/src/condition.ts index 34451ea..01616eb 100644 --- a/src/condition.ts +++ b/src/condition.ts @@ -103,8 +103,7 @@ export class Condition { if ('env' in value) { if (value.env === 'warp_account_addr') { - const account = await this.sdk.account(job.owner); - return account.account; + return job.account; } } diff --git a/src/examples/example_astro.ts b/src/examples/example_astro.ts index c19df1d..550ef12 100644 --- a/src/examples/example_astro.ts +++ b/src/examples/example_astro.ts @@ -67,7 +67,6 @@ const condition = cond.uint(uint.ref(astroReceived), 'gte', uint.simple(limitOrd const createJobMsg = job .create() .name('astroport-limit-order') - .requeueOnEvict(true) .reward('50000') .recurring(false) .description('This job creates an astroport limit order.') diff --git a/src/examples/example_cross_chain.ts b/src/examples/example_cross_chain.ts index a579b60..31955ad 100644 --- a/src/examples/example_cross_chain.ts +++ b/src/examples/example_cross_chain.ts @@ -168,7 +168,6 @@ const createJobMsg = job .name('swap-and-send') .description('') .recurring(true) - .requeueOnEvict(true) .reward('1000') .vars([untrnAmount, timeoutTimestamp, simulateAstroAmount, transferVariable, swapVariable, routedSwapVariable]) .executions([ diff --git a/src/examples/example_eris.ts b/src/examples/example_eris.ts index 99a2946..aa716f6 100644 --- a/src/examples/example_eris.ts +++ b/src/examples/example_eris.ts @@ -36,7 +36,6 @@ const createJobMsg = job .description('This job harvests rewards for eris protoocl vaults each day.') .labels([]) .recurring(true) - .requeueOnEvict(true) .reward('50000') .vars([nextExecution]) .executions([ diff --git a/src/migrate/migrate_finished_jobs.ts b/src/migrate/migrate_finished_jobs.ts index 6368391..e818d5d 100644 --- a/src/migrate/migrate_finished_jobs.ts +++ b/src/migrate/migrate_finished_jobs.ts @@ -69,7 +69,7 @@ const loop = async () => { const limit = 50; // TODO: Update to current max job id on testnet/mainnet - const maxJobId = 1000; + const maxJobId = 1500; while (startAfter <= maxJobId) { try { diff --git a/src/migrate/migrate_pending_jobs.ts b/src/migrate/migrate_pending_jobs.ts index 234cc04..6d97fae 100644 --- a/src/migrate/migrate_pending_jobs.ts +++ b/src/migrate/migrate_pending_jobs.ts @@ -68,7 +68,7 @@ const loop = async () => { let startAfter = 0; const limit = 50; // TODO: Update to current max job id on testnet/mainnet - const maxJobId = 1000; + const maxJobId = 1500; while (startAfter <= maxJobId) { try { diff --git a/src/modules/chain.ts b/src/modules/chain.ts index fd0a47b..b8ebda8 100644 --- a/src/modules/chain.ts +++ b/src/modules/chain.ts @@ -12,7 +12,7 @@ interface ContractDefinition { address: string; } -type ContractNames = 'warp-controller' | 'warp-resolver' | 'warp-templates'; +type ContractNames = 'warp-controller' | 'warp-resolver' | 'warp-templates' | 'warp-job-account-tracker'; type NetworkConfig = { [contract in ContractNames]: ContractDefinition; @@ -148,6 +148,7 @@ export interface ContractAddresses { controller: string; resolver: string; templates: string; + jobAccountTracker: string; } export class ChainModule { @@ -165,6 +166,7 @@ export class ChainModule { controller: contractsConfig['warp-controller'].address, resolver: contractsConfig['warp-resolver'].address, templates: contractsConfig['warp-templates'].address, + jobAccountTracker: contractsConfig['warp-job-account-tracker'].address, }; } @@ -244,6 +246,8 @@ export class ChainModule { return contractDefs['warp-resolver'].address; case 'templates': return contractDefs['warp-templates'].address; + case 'jobAccountTracker': + return contractDefs['warp-job-account-tracker'].address; } } } diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 148de45..beda7ca 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -1,12 +1,16 @@ -import { warp_account, warp_controller, warp_resolver, warp_templates } from '../types/contracts'; +import { + warp_controller, + warp_job_account, + warp_legacy_account, + warp_resolver, + warp_templates, +} from '../types/contracts'; import { base64encode, nativeTokenDenom, Token, TransferMsg, TransferNftMsg } from '../utils'; -import { CreateTxOptions } from '@terra-money/feather.js'; +import { Coins, CreateTxOptions } from '@terra-money/feather.js'; import { TxBuilder } from '../tx'; -import Big from 'big.js'; import { JobSequenceMsgComposer } from '../composers'; import { resolveExternalInputs } from '../variables'; import { WarpSdk } from '../sdk'; -import { Fund, mergeFunds } from '../types/job'; export class TxModule { private warpSdk: WarpSdk; @@ -15,17 +19,22 @@ export class TxModule { this.warpSdk = warpSdk; } - public async createJob(sender: string, msg: warp_controller.CreateJobMsg, funds?: Fund[]): Promise { - const createAccountTx = await this.createAccount(sender, funds); + public async createJob( + sender: string, + msg: warp_controller.CreateJobMsg, + coins?: Coins.Input + ): Promise { + const transferCwToControllerTx = await this.transferCwToController(sender, msg.cw_funds ?? []); return TxBuilder.new(this.warpSdk.chain.config) - .tx(createAccountTx) + .tx(transferCwToControllerTx) .execute>( sender, this.warpSdk.chain.contracts.controller, { create_job: msg, - } + }, + coins ) .build(); } @@ -33,32 +42,26 @@ export class TxModule { public async createJobSequence( sender: string, sequence: warp_controller.CreateJobMsg[], - funds?: Fund[] + coins?: Coins.Input ): Promise { - const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); - - const totalReward = sequence.reduce((acc, msg) => acc.add(Big(msg.reward)), Big(0)); - const rewardFund: Fund = { native: { denom: nativeDenom, amount: totalReward.toString() } }; - const totalFunds = funds ? mergeFunds(funds, rewardFund) : [rewardFund]; - - const createAccountTx = await this.createAccount(sender, totalFunds); - + let txBuilder = TxBuilder.new(this.warpSdk.chain.config); let jobSequenceMsgComposer = JobSequenceMsgComposer.new(); - sequence.forEach((msg) => { + sequence.forEach(async (msg) => { jobSequenceMsgComposer = jobSequenceMsgComposer.chain(msg); + txBuilder = txBuilder.tx(await this.transferCwToController(sender, msg.cw_funds ?? [])); }); const jobSequenceMsg = jobSequenceMsgComposer.compose(); - return TxBuilder.new(this.warpSdk.chain.config) - .tx(createAccountTx) + return txBuilder .execute>( sender, this.warpSdk.chain.contracts.controller, { create_job: jobSequenceMsg, - } + }, + coins ) .build(); } @@ -76,25 +79,14 @@ export class TxModule { } public async updateJob(sender: string, msg: warp_controller.UpdateJobMsg): Promise { - const account = await this.warpSdk.account(sender); - const nativeDenom = await nativeTokenDenom(this.warpSdk.wallet.lcd, this.warpSdk.chain.config.chainID); - let txBuilder = TxBuilder.new(this.warpSdk.chain.config); - if (msg.added_reward) { - txBuilder = txBuilder.send(account.owner, account.account, { - [nativeDenom]: Big(msg.added_reward).toString(), - }); - } - return txBuilder .execute>( sender, this.warpSdk.chain.contracts.controller, { - update_job: { - ...msg, - }, + update_job: msg, } ) .build(); @@ -254,51 +246,35 @@ export class TxModule { .build(); } - public async createAccount(sender: string, funds?: Fund[]): Promise { + public async transferCwToController(sender: string, funds: warp_controller.CwFund[]): Promise { let txBuilder = TxBuilder.new(this.warpSdk.chain.config); - if (funds) { - for (let fund of funds) { - if ('cw20' in fund) { - const { amount, contract_addr } = fund.cw20; - - txBuilder = txBuilder.execute(sender, contract_addr, { - transfer: { - amount, - recipient: this.warpSdk.chain.contracts.controller, - }, - }); - } else if ('cw721' in fund) { - const { contract_addr, token_id } = fund.cw721; - - txBuilder = txBuilder.execute(sender, contract_addr, { - transfer_nft: { - token_id, - recipient: this.warpSdk.chain.contracts.controller, - }, - }); - } + for (let fund of funds) { + if ('cw20' in fund) { + const { amount, contract_addr } = fund.cw20; + + txBuilder = txBuilder.execute(sender, contract_addr, { + transfer: { + amount, + recipient: this.warpSdk.chain.contracts.controller, + }, + }); + } else if ('cw721' in fund) { + const { contract_addr, token_id } = fund.cw721; + + txBuilder = txBuilder.execute(sender, contract_addr, { + transfer_nft: { + token_id, + recipient: this.warpSdk.chain.contracts.controller, + }, + }); } } - const nativeFunds = funds?.filter((fund) => 'native' in fund).map((fund) => 'native' in fund && fund.native) ?? []; - const cwFunds = (funds?.filter((fund) => !('native' in fund)) as warp_controller.Fund[]) ?? []; - - return txBuilder - .execute>( - sender, - this.warpSdk.chain.contracts.controller, - { - create_account: { - funds: cwFunds, - }, - }, - nativeFunds.reduce((acc, curr) => ({ ...acc, [curr.denom]: curr.amount }), {}) - ) - .build(); + return txBuilder.build(); } - public async depositToAccount( + public async legacyDepositToAccount( sender: string, account: string, token: Token, @@ -324,11 +300,30 @@ export class TxModule { return txPayload; } - public async withdrawAssets(sender: string, msg: warp_account.WithdrawAssetsMsg): Promise { - const { account } = await this.warpSdk.account(sender); + public async legacyWithdrawAssets( + sender: string, + msg: warp_legacy_account.WithdrawAssetsMsg + ): Promise { + const { account } = await this.warpSdk.legacyAccount(sender); + + const txPayload = TxBuilder.new(this.warpSdk.chain.config) + .execute>(sender, account, { + withdraw_assets: msg, + }) + .build(); + + return txPayload; + } + + public async withdrawAssets( + sender: string, + job_id: string, + msg: warp_job_account.WithdrawAssetsMsg + ): Promise { + const job = await this.warpSdk.job(job_id); const txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute>(sender, account, { + .execute>(sender, job.account, { withdraw_assets: msg, }) .build(); @@ -336,13 +331,13 @@ export class TxModule { return txPayload; } - public async withdrawFromAccount( + public async legacyWithdrawFromAccount( sender: string, receiver: string, token: Token, amount: string ): Promise { - const { account } = await this.warpSdk.account(sender); + const { account } = await this.warpSdk.legacyAccount(sender); let txPayload: CreateTxOptions; if (token.type === 'cw20') { @@ -354,7 +349,7 @@ export class TxModule { }; txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute(sender, account, { + .execute(sender, account, { generic: { msgs: [ { @@ -372,7 +367,7 @@ export class TxModule { .build(); } else { txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute(sender, account, { + .execute(sender, account, { generic: { msgs: [ { diff --git a/src/refs.injective.json b/src/refs.injective.json index 6cb9092..4ae7580 100644 --- a/src/refs.injective.json +++ b/src/refs.injective.json @@ -11,6 +11,10 @@ "warp-templates": { "codeId": "2530", "address": "inj1lqe55634npthzavxd9stfpz0snr5hh0qxhhsgp" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "inj1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } }, "mainnet": { @@ -25,6 +29,10 @@ "warp-templates": { "codeId": "82", "address": "inj1nxp6uvz0506u32hf438uqy3cqs023k9wq6kxp8" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "inj1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } } } diff --git a/src/refs.neutron.json b/src/refs.neutron.json index a80f14c..9451ec2 100644 --- a/src/refs.neutron.json +++ b/src/refs.neutron.json @@ -11,6 +11,10 @@ "warp-templates": { "codeId": "1475", "address": "neutron1a29vd6lltycyr2cfku0w4km3axeexcxut53t3wx397dw8jndfq4swlxw9d" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "neutron1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } }, "mainnet": { @@ -25,6 +29,10 @@ "warp-templates": { "codeId": "202", "address": "neutron1hn43q3v92y4dgdgtc5p7g684zx9dn6ejr74gchntdnppsljd89usxqs2s9" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "neutron1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } } } diff --git a/src/refs.nibiru.json b/src/refs.nibiru.json index c7ccd0a..182bf86 100644 --- a/src/refs.nibiru.json +++ b/src/refs.nibiru.json @@ -11,6 +11,10 @@ "warp-templates": { "codeId": "15", "address": "nibi1cyd63pk2wuvjkqmhlvp9884z4h89rqtn8w8xgz9m28hjd2kzj2cq0q8fv4" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "nibi1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } }, "mainnet": { @@ -25,6 +29,10 @@ "warp-templates": { "codeId": "15", "address": "nibi1cyd63pk2wuvjkqmhlvp9884z4h89rqtn8w8xgz9m28hjd2kzj2cq0q8fv4" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "nibi1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } } } diff --git a/src/refs.terra.json b/src/refs.terra.json index b3cdf1e..bc929c6 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,16 +1,26 @@ { "testnet": { + "warp-account": { + "codeId": "9626" + }, "warp-controller": { - "codeId": "9264", + "codeId": "11634", "address": "terra1fqcfh8vpqsl7l5yjjtq5wwu6sv989txncq5fa756tv7lywqexraq5vnjvt" }, "warp-resolver": { - "codeId": "9263", + "codeId": "11521", "address": "terra1lxfx6n792aw3hg47tchmyuhv5t30f334gus67pc250qx5zljadws65elnf" }, "warp-templates": { "codeId": "9263", "address": "terra17xm2ewyg60y7eypnwav33fwm23hxs3qyd8qk9tnntj4d0rp2vvhsgkpwwp" + }, + "warp-job-account": { + "codeId": "11522" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } }, "mainnet": { @@ -25,6 +35,10 @@ "warp-templates": { "codeId": "1787", "address": "terra1mcfu3tkd5h9zdwuserl3v6uzetv9xke8wyaaf9vx07p7shk6xlws3styfk" + }, + "warp-job-account-tracker": { + "codeId": "11630", + "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } } } \ No newline at end of file diff --git a/src/sdk.ts b/src/sdk.ts index 4a42756..9b380b4 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,4 +1,4 @@ -import { warp_account, warp_controller, warp_resolver } from './types/contracts'; +import { warp_legacy_account, warp_controller, warp_resolver, warp_job_account } from './types/contracts'; import { WalletLike, Wallet, wallet } from './wallet'; import { Condition } from './condition'; import { @@ -9,12 +9,13 @@ import { computeCreationFee, computeMaintenanceFee, } from './utils'; -import { TxInfo, LCDClientConfig, LCDClient } from '@terra-money/feather.js'; +import { TxInfo, LCDClientConfig, LCDClient, Coins } from '@terra-money/feather.js'; import Big from 'big.js'; import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; import { warp_templates } from './types/contracts/warp_templates'; -import { Fund, Job, parseJob } from './types/job'; +import { Job, parseJob } from './types/job'; +import { warp_job_account_tracker } from 'types/contracts'; const FEE_ADJUSTMENT_FACTOR = 3; @@ -162,20 +163,44 @@ export class WarpSdk { return response; } - public async account(owner: string): Promise { + public async takenJobAccounts( + msg: warp_job_account_tracker.QueryTakenAccountsMsg + ): Promise { + const response = await contractQuery< + Extract, + warp_job_account_tracker.AccountsResponse + >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_taken_accounts: msg }); + + return response; + } + + public async freeJobAccounts( + msg: warp_job_account_tracker.QueryFreeAccountsMsg + ): Promise { + const response = await contractQuery< + Extract, + warp_job_account_tracker.AccountsResponse + >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_free_accounts: msg }); + + return response; + } + + // Legacy account support + + public async legacyAccount(owner: string): Promise { const { account } = await contractQuery< - Extract, - warp_controller.AccountResponse - >(this.wallet.lcd, this.chain.contracts.controller, { query_account: { owner } }); + Extract, + warp_controller.LegacyAccountResponse + >(this.wallet.lcd, this.chain.contracts.controller, { query_legacy_account: { owner } }); return account; } - public async accounts(opts: warp_controller.QueryAccountsMsg): Promise { + public async legacyAccounts(opts: warp_controller.QueryLegacyAccountsMsg): Promise { const { accounts } = await contractQuery< - Extract, - warp_controller.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.controller, { query_accounts: opts }); + Extract, + warp_controller.LegacyAccountsResponse + >(this.wallet.lcd, this.chain.contracts.controller, { query_legacy_accounts: opts }); return accounts; } @@ -233,7 +258,10 @@ export class WarpSdk { estimateJobMsg: EstimateJobMsg, execution: warp_controller.Execution ): Promise { - const account = await this.account(sender); + // const account = await this.account(sender); + // TODO: check if this works, as before first job is created, no account is assigned to free job accounts + const response = await this.freeJobAccounts({ account_owner_addr: sender }); + const account = response.accounts[0].addr; const hydratedVars = await this.hydrateVars({ vars: estimateJobMsg.vars }); @@ -246,7 +274,7 @@ export class WarpSdk { msgs.push( ...( - await this.tx.executeHydrateVars(account.account, { + await this.tx.executeHydrateVars(account, { vars: hydratedVars, }) ).msgs @@ -254,7 +282,7 @@ export class WarpSdk { msgs.push( ...( - await this.tx.executeHydrateMsgs(account.account, { + await this.tx.executeHydrateMsgs(account, { vars: hydratedVars, msgs: execution.msgs, }) @@ -263,7 +291,7 @@ export class WarpSdk { msgs.push( ...( - await this.tx.executeResolveCondition(account.account, { + await this.tx.executeResolveCondition(account, { condition: execution.condition, vars: hydratedVars, }) @@ -273,7 +301,7 @@ export class WarpSdk { if (estimateJobMsg.recurring) { msgs.push( ...( - await this.tx.executeApplyVarFn(account.account, { + await this.tx.executeApplyVarFn(account, { vars: hydratedVars, status: 'Executed', }) @@ -281,9 +309,9 @@ export class WarpSdk { ); } - msgs.push(...hydratedMsgs.map((msg) => cosmosMsgToCreateTxMsg(account.account, msg))); + msgs.push(...hydratedMsgs.map((msg) => cosmosMsgToCreateTxMsg(account, msg))); - const accountInfo = await this.wallet.lcd.auth.accountInfo(account.account); + const accountInfo = await this.wallet.lcd.auth.accountInfo(account); const fee = await this.wallet.lcd.tx.estimateFee( [ @@ -307,8 +335,8 @@ export class WarpSdk { return nativeTokenDenom(this.wallet.lcd, this.chain.config.chainID); } - public async createJob(sender: string, msg: warp_controller.CreateJobMsg, funds?: Fund[]): Promise { - const txPayload = await this.tx.createJob(sender, msg, funds); + public async createJob(sender: string, msg: warp_controller.CreateJobMsg, coins?: Coins.Input): Promise { + const txPayload = await this.tx.createJob(sender, msg, coins); return this.wallet.tx(txPayload); } @@ -330,9 +358,9 @@ export class WarpSdk { public async createJobSequence( sender: string, sequence: warp_controller.CreateJobMsg[], - funds?: Fund[] + coins?: Coins.Input ): Promise { - const txPayload = await this.tx.createJobSequence(sender, sequence, funds); + const txPayload = await this.tx.createJobSequence(sender, sequence, coins); return this.wallet.tx(txPayload); } @@ -379,26 +407,37 @@ export class WarpSdk { return this.wallet.tx(txPayload); } - public async createAccount(sender: string, funds?: Fund[]): Promise { - const txPayload = await this.tx.createAccount(sender, funds); + public async withdrawAssets( + sender: string, + job_id: string, + msg: warp_job_account.WithdrawAssetsMsg + ): Promise { + const txPayload = await this.tx.withdrawAssets(sender, job_id, msg); return this.wallet.tx(txPayload); } - public async withdrawAssets(sender: string, msg: warp_account.WithdrawAssetsMsg): Promise { - const txPayload = await this.tx.withdrawAssets(sender, msg); + // legacy account support + + public async legacyWithdrawAssets(sender: string, msg: warp_legacy_account.WithdrawAssetsMsg): Promise { + const txPayload = await this.tx.legacyWithdrawAssets(sender, msg); return this.wallet.tx(txPayload); } - public async depositToAccount(sender: string, account: string, token: Token, amount: string): Promise { - const txPayload = await this.tx.depositToAccount(sender, account, token, amount); + public async legacyDepositToAccount(sender: string, account: string, token: Token, amount: string): Promise { + const txPayload = await this.tx.legacyDepositToAccount(sender, account, token, amount); return this.wallet.tx(txPayload); } - public async withdrawFromAccount(sender: string, receiver: string, token: Token, amount: string): Promise { - const txPayload = await this.tx.withdrawFromAccount(sender, receiver, token, amount); + public async legacyWithdrawFromAccount( + sender: string, + receiver: string, + token: Token, + amount: string + ): Promise { + const txPayload = await this.tx.legacyWithdrawFromAccount(sender, receiver, token, amount); return this.wallet.tx(txPayload); } diff --git a/src/types/contracts/index.ts b/src/types/contracts/index.ts index ec91606..50150a5 100644 --- a/src/types/contracts/index.ts +++ b/src/types/contracts/index.ts @@ -1,4 +1,6 @@ -export * from './warp_account'; export * from './warp_controller'; +export * from './warp_job_account'; +export * from './warp_job_account_tracker'; +export * from './warp_legacy_account'; export * from './warp_resolver'; export * from './warp_templates'; diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 2b98a95..0aaaeaf 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -1,17 +1,7 @@ export module warp_controller { - export type Addr = string; - export interface AccountResponse { - account: Account; - } - export interface Account { - account: Addr; - owner: Addr; - } - export interface AccountsResponse { - accounts: Account[]; - } export type Uint128 = string; export type Uint64 = string; + export type Addr = string; export interface Config { a_max: Uint128; a_min: Uint128; @@ -21,17 +11,18 @@ export module warp_controller { creation_fee_max: Uint128; creation_fee_min: Uint128; creation_fee_percentage: Uint64; - duration_days_left: Uint128; - duration_days_right: Uint128; + duration_days_left: Uint64; + duration_days_right: Uint64; fee_collector: Addr; fee_denom: string; + job_account_tracker_address: Addr; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; owner: Addr; q_max: Uint64; - queue_size_left: Uint128; - queue_size_right: Uint128; + queue_size_left: Uint64; + queue_size_right: Uint64; resolver_address: Addr; t_max: Uint64; t_min: Uint64; @@ -57,13 +48,16 @@ export module warp_controller { evict_job: EvictJobMsg; } | { - create_account: CreateAccountMsg; + update_config: UpdateConfigMsg; } | { - update_config: UpdateConfigMsg; + migrate_legacy_accounts: MigrateLegacyAccountsMsg; } | { - migrate_accounts: MigrateAccountsMsg; + migrate_free_job_accounts: MigrateJobAccountsMsg; + } + | { + migrate_taken_job_accounts: MigrateJobAccountsMsg; } | { migrate_pending_jobs: MigrateJobsMsg; @@ -262,7 +256,7 @@ export module warp_controller { */ cw721: [Addr, string]; }; - export type Fund = + export type CwFund = | { cw20: Cw20Fund; } @@ -272,13 +266,13 @@ export module warp_controller { export interface CreateJobMsg { account_msgs?: CosmosMsgFor_Empty[] | null; assets_to_withdraw?: AssetInfo[] | null; + cw_funds?: CwFund[] | null; description: string; - duration_days: Uint128; + duration_days: Uint64; executions: Execution[]; labels: string[]; name: string; recurring: boolean; - requeue_on_evict: boolean; reward: Uint128; terminate_condition?: string | null; vars: string; @@ -302,6 +296,14 @@ export module warp_controller { */ revision: number; } + export interface Cw20Fund { + amount: Uint128; + contract_addr: string; + } + export interface Cw721Fund { + contract_addr: string; + token_id: string; + } export interface Execution { condition: string; msgs: string; @@ -310,7 +312,6 @@ export module warp_controller { id: Uint64; } export interface UpdateJobMsg { - added_reward?: Uint128 | null; description?: string | null; id: Uint64; labels?: string[] | null; @@ -327,18 +328,6 @@ export module warp_controller { export interface EvictJobMsg { id: Uint64; } - export interface CreateAccountMsg { - funds?: Fund[] | null; - msgs?: CosmosMsgFor_Empty[] | null; - } - export interface Cw20Fund { - amount: Uint128; - contract_addr: string; - } - export interface Cw721Fund { - contract_addr: string; - token_id: string; - } export interface UpdateConfigMsg { a_max?: Uint128 | null; a_min?: Uint128 | null; @@ -361,10 +350,16 @@ export module warp_controller { t_max?: Uint64 | null; t_min?: Uint64 | null; } - export interface MigrateAccountsMsg { + export interface MigrateLegacyAccountsMsg { limit: number; start_after?: string | null; - warp_account_code_id: Uint64; + warp_legacy_account_code_id: Uint64; + } + export interface MigrateJobAccountsMsg { + account_owner_addr: string; + limit: number; + start_after?: string | null; + warp_job_account_code_id: Uint64; } export interface MigrateJobsMsg { limit: number; @@ -379,17 +374,18 @@ export module warp_controller { creation_fee: Uint64; creation_fee_max: Uint128; creation_fee_min: Uint128; - duration_days_left: Uint128; - duration_days_right: Uint128; + duration_days_left: Uint64; + duration_days_right: Uint64; fee_collector?: string | null; fee_denom: string; + job_account_tracker_address: string; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; owner?: string | null; q_max: Uint64; - queue_size_left: Uint128; - queue_size_right: Uint128; + queue_size_left: Uint64; + queue_size_right: Uint64; resolver_address: string; t_max: Uint64; t_min: Uint64; @@ -402,7 +398,9 @@ export module warp_controller { export interface Job { account: Addr; assets_to_withdraw: AssetInfo[]; + created_at_time: Uint64; description: string; + duration_days: Uint64; executions: Execution[]; id: Uint64; labels: string[]; @@ -411,7 +409,6 @@ export module warp_controller { owner: Addr; prev_id?: Uint64 | null; recurring: boolean; - requeue_on_evict: boolean; reward: Uint128; status: JobStatus; terminate_condition?: string | null; @@ -421,6 +418,16 @@ export module warp_controller { jobs: Job[]; total_count: number; } + export interface LegacyAccountResponse { + account: LegacyAccount; + } + export interface LegacyAccount { + account: Addr; + owner: Addr; + } + export interface LegacyAccountsResponse { + accounts: LegacyAccount[]; + } export type QueryMsg = | { query_job: QueryJobMsg; @@ -429,10 +436,10 @@ export module warp_controller { query_jobs: QueryJobsMsg; } | { - query_account: QueryAccountMsg; + query_legacy_account: QueryLegacyAccountMsg; } | { - query_accounts: QueryAccountsMsg; + query_legacy_accounts: QueryLegacyAccountsMsg; } | { query_config: QueryConfigMsg; @@ -457,10 +464,10 @@ export module warp_controller { _0: Uint128; _1: Uint64; } - export interface QueryAccountMsg { + export interface QueryLegacyAccountMsg { owner: string; } - export interface QueryAccountsMsg { + export interface QueryLegacyAccountsMsg { limit?: number | null; start_after?: string | null; } diff --git a/src/types/contracts/warp_job_account.ts b/src/types/contracts/warp_job_account.ts new file mode 100644 index 0000000..d9e22f4 --- /dev/null +++ b/src/types/contracts/warp_job_account.ts @@ -0,0 +1,280 @@ +export module warp_job_account { + export type Addr = string; + export interface Config { + creator_addr: Addr; + owner: Addr; + } + export type ExecuteMsg = + | { + generic: GenericMsg; + } + | { + withdraw_assets: WithdrawAssetsMsg; + } + | { + ibc_transfer: IbcTransferMsg; + }; + export type CosmosMsgFor_Empty = + | { + bank: BankMsg; + } + | { + custom: Empty; + } + | { + staking: StakingMsg; + } + | { + distribution: DistributionMsg; + } + | { + stargate: { + type_url: string; + value: Binary; + }; + } + | { + ibc: IbcMsg; + } + | { + wasm: WasmMsg; + } + | { + gov: GovMsg; + }; + export type BankMsg = + | { + send: { + amount: Coin[]; + to_address: string; + }; + } + | { + burn: { + amount: Coin[]; + }; + }; + export type Uint128 = string; + export type StakingMsg = + | { + delegate: { + amount: Coin; + validator: string; + }; + } + | { + undelegate: { + amount: Coin; + validator: string; + }; + } + | { + redelegate: { + amount: Coin; + dst_validator: string; + src_validator: string; + }; + }; + export type DistributionMsg = + | { + set_withdraw_address: { + /** + * The `withdraw_address` + */ + address: string; + }; + } + | { + withdraw_delegator_reward: { + /** + * The `validator_address` + */ + validator: string; + }; + }; + export type Binary = string; + export type IbcMsg = + | { + transfer: { + /** + * packet data only supports one coin https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/ibc/applications/transfer/v1/transfer.proto#L11-L20 + */ + amount: Coin; + /** + * exisiting channel to send the tokens over + */ + channel_id: string; + /** + * when packet times out, measured on remote chain + */ + timeout: IbcTimeout; + /** + * address on the remote chain to receive these tokens + */ + to_address: string; + }; + } + | { + send_packet: { + channel_id: string; + data: Binary; + /** + * when packet times out, measured on remote chain + */ + timeout: IbcTimeout; + }; + } + | { + close_channel: { + channel_id: string; + }; + }; + export type Timestamp = Uint64; + export type Uint64 = string; + export type WasmMsg = + | { + execute: { + contract_addr: string; + funds: Coin[]; + /** + * msg is the json-encoded ExecuteMsg struct (as raw Binary) + */ + msg: Binary; + }; + } + | { + instantiate: { + admin?: string | null; + code_id: number; + funds: Coin[]; + /** + * A human-readbale label for the contract + */ + label: string; + /** + * msg is the JSON-encoded InstantiateMsg struct (as raw Binary) + */ + msg: Binary; + }; + } + | { + migrate: { + contract_addr: string; + /** + * msg is the json-encoded MigrateMsg struct that will be passed to the new code + */ + msg: Binary; + /** + * the code_id of the new logic to place in the given contract + */ + new_code_id: number; + }; + } + | { + update_admin: { + admin: string; + contract_addr: string; + }; + } + | { + clear_admin: { + contract_addr: string; + }; + }; + export type GovMsg = { + vote: { + proposal_id: number; + /** + * The vote option. + * + * This should be called "option" for consistency with Cosmos SDK. Sorry for that. See . + */ + vote: VoteOption; + }; + }; + export type VoteOption = 'yes' | 'no' | 'abstain' | 'no_with_veto'; + export type AssetInfo = + | { + native: string; + } + | { + cw20: Addr; + } + | { + /** + * @minItems 2 + * @maxItems 2 + */ + cw721: [Addr, string]; + }; + export interface GenericMsg { + msgs: CosmosMsgFor_Empty[]; + } + export interface Coin { + amount: Uint128; + denom: string; + } + export interface Empty {} + export interface IbcTimeout { + block?: IbcTimeoutBlock | null; + timestamp?: Timestamp | null; + } + export interface IbcTimeoutBlock { + /** + * block height after which the packet times out. the height within the given revision + */ + height: number; + /** + * the version that the client is currently on (eg. after reseting the chain this could increment 1 as height drops to 0) + */ + revision: number; + } + export interface WithdrawAssetsMsg { + asset_infos: AssetInfo[]; + } + export interface IbcTransferMsg { + timeout_block_delta?: number | null; + timeout_timestamp_seconds_delta?: number | null; + transfer_msg: TransferMsg; + } + export interface TransferMsg { + memo: string; + receiver: string; + sender: string; + source_channel: string; + source_port: string; + timeout_block?: TimeoutBlock | null; + timeout_timestamp?: number | null; + token?: Coin | null; + } + export interface TimeoutBlock { + revision_height?: number | null; + revision_number?: number | null; + } + export type CwFund = + | { + cw20: Cw20Fund; + } + | { + cw721: Cw721Fund; + }; + export interface InstantiateMsg { + cw_funds: CwFund[]; + job_id: Uint64; + msgs: CosmosMsgFor_Empty[]; + native_funds: Coin[]; + owner: string; + } + export interface Cw20Fund { + amount: Uint128; + contract_addr: string; + } + export interface Cw721Fund { + contract_addr: string; + token_id: string; + } + export type QueryMsg = { + query_config: QueryConfigMsg; + }; + export interface QueryConfigMsg {} +} diff --git a/src/types/contracts/warp_job_account_tracker.ts b/src/types/contracts/warp_job_account_tracker.ts new file mode 100644 index 0000000..5259be6 --- /dev/null +++ b/src/types/contracts/warp_job_account_tracker.ts @@ -0,0 +1,70 @@ +export module warp_job_account_tracker { + export type Addr = string; + export type Uint64 = string; + export interface AccountsResponse { + accounts: Account[]; + total_count: number; + } + export interface Account { + addr: Addr; + taken_by_job_id?: Uint64 | null; + } + export interface Config { + admin: Addr; + warp_addr: Addr; + } + export interface ConfigResponse { + config: Config; + } + export type ExecuteMsg = + | { + take_account: TakeAccountMsg; + } + | { + free_account: FreeAccountMsg; + }; + export interface TakeAccountMsg { + account_addr: string; + account_owner_addr: string; + job_id: Uint64; + } + export interface FreeAccountMsg { + account_addr: string; + account_owner_addr: string; + last_job_id: Uint64; + } + export interface FirstFreeAccountResponse { + account?: Account | null; + } + export interface InstantiateMsg { + admin: string; + warp_addr: string; + } + export type QueryMsg = + | { + query_config: QueryConfigMsg; + } + | { + query_taken_accounts: QueryTakenAccountsMsg; + } + | { + query_free_accounts: QueryFreeAccountsMsg; + } + | { + query_first_free_account: QueryFirstFreeAccountMsg; + }; + export interface QueryConfigMsg {} + export interface QueryTakenAccountsMsg { + account_owner_addr: string; + limit?: number | null; + start_after?: string | null; + } + export interface QueryFreeAccountsMsg { + account_owner_addr: string; + limit?: number | null; + start_after?: string | null; + } + export interface QueryFirstFreeAccountMsg { + account_owner_addr: string; + } +} diff --git a/src/types/contracts/warp_account.ts b/src/types/contracts/warp_legacy_account.ts similarity index 80% rename from src/types/contracts/warp_account.ts rename to src/types/contracts/warp_legacy_account.ts index b2531f8..62d99a6 100644 --- a/src/types/contracts/warp_account.ts +++ b/src/types/contracts/warp_legacy_account.ts @@ -1,18 +1,6 @@ -export module warp_account { +export module warp_legacy_account { export type Addr = string; - export interface AccountResponse { - account: Account; - } - export interface Account { - account: Addr; - owner: Addr; - } - export interface AccountsResponse { - accounts: Account[]; - } export interface Config { - is_sub_account: boolean; - main_account_addr: Addr; owner: Addr; warp_addr: Addr; } @@ -25,12 +13,6 @@ export module warp_account { } | { ibc_transfer: IbcTransferMsg; - } - | { - occupy_sub_account: OccupySubAccountMsg; - } - | { - free_sub_account: FreeSubAccountMsg; }; export type CosmosMsgFor_Empty = | { @@ -269,14 +251,7 @@ export module warp_account { revision_height?: number | null; revision_number?: number | null; } - export interface OccupySubAccountMsg { - job_id: Uint64; - sub_account_addr: string; - } - export interface FreeSubAccountMsg { - sub_account_addr: string; - } - export type Fund = + export type CwFund = | { cw20: Cw20Fund; } @@ -284,10 +259,7 @@ export module warp_account { cw721: Cw721Fund; }; export interface InstantiateMsg { - funds?: Fund[] | null; - is_sub_account?: boolean | null; - main_account_addr?: string | null; - msgs?: CosmosMsgFor_Empty[] | null; + funds?: CwFund[] | null; owner: string; } export interface Cw20Fund { @@ -298,34 +270,5 @@ export module warp_account { contract_addr: string; token_id: string; } - export type JobStatus = 'Pending' | 'Executed' | 'Failed' | 'Cancelled' | 'Evicted'; - export interface JobResponse { - job: Job; - } - export interface Job { - account: Addr; - assets_to_withdraw: AssetInfo[]; - description: string; - executions: Execution[]; - id: Uint64; - labels: string[]; - last_update_time: Uint64; - name: string; - owner: Addr; - prev_id?: Uint64 | null; - recurring: boolean; - requeue_on_evict: boolean; - reward: Uint128; - status: JobStatus; - terminate_condition?: string | null; - vars: string; - } - export interface Execution { - condition: string; - msgs: string; - } - export interface JobsResponse { - jobs: Job[]; - total_count: number; - } + export type QueryMsg = 'config'; } diff --git a/src/types/job.ts b/src/types/job.ts index 2d55dc9..2aa11ca 100644 --- a/src/types/job.ts +++ b/src/types/job.ts @@ -1,4 +1,3 @@ -import Big from 'big.js'; import { warp_controller, warp_resolver } from './contracts'; export type Execution = { @@ -47,60 +46,3 @@ export const parseJobsResponse = (resp: warp_controller.JobsResponse): JobsRespo jobs: resp.jobs.map(parseJob), }; }; - -export type Fund = - | warp_controller.Fund - | { - native: { - denom: string; - amount: string; - }; - }; - -export function mergeFunds(funds: Fund[], fund: Fund): Fund[] { - const mergedFunds = [...funds]; - let fundMerged = false; - - for (let i = 0; i < mergedFunds.length; i++) { - const existingFund = mergedFunds[i]; - - if ('native' in fund && 'native' in existingFund) { - if (fund.native.denom === existingFund.native.denom) { - mergedFunds[i] = { - native: { - denom: fund.native.denom, - amount: Big(existingFund.native.amount).add(fund.native.amount).toString(), - }, - }; - fundMerged = true; - break; - } - } else if ('cw20' in fund && 'cw20' in existingFund) { - if (fund.cw20.contract_addr === existingFund.cw20.contract_addr) { - mergedFunds[i] = { - cw20: { - contract_addr: fund.cw20.contract_addr, - amount: Big(existingFund.cw20.amount).add(fund.cw20.amount).toString(), - }, - }; - fundMerged = true; - break; - } - } else if ('cw721' in fund && 'cw721' in existingFund) { - if ( - fund.cw721.contract_addr === existingFund.cw721.contract_addr && - fund.cw721.token_id === existingFund.cw721.token_id - ) { - // cw721 tokens are non-fungible, so we don't merge them based on amount, but check for duplicates based on token_id - fundMerged = true; - break; - } - } - } - - if (!fundMerged) { - mergedFunds.push(fund); - } - - return mergedFunds; -} From 34d9d88bcf23b534ef962a45f0d56ced8d7af9b4 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Sat, 11 Nov 2023 17:51:56 +0100 Subject: [PATCH 14/44] refactor fee to coin --- src/sdk.ts | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/sdk.ts b/src/sdk.ts index 9b380b4..0777dd0 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -9,7 +9,7 @@ import { computeCreationFee, computeMaintenanceFee, } from './utils'; -import { TxInfo, LCDClientConfig, LCDClient, Coins } from '@terra-money/feather.js'; +import { TxInfo, LCDClientConfig, LCDClient, Coins, Coin } from '@terra-money/feather.js'; import Big from 'big.js'; import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; @@ -229,22 +229,25 @@ export class WarpSdk { } // if reward is not provided, reward estimate is used - public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg, reward?: string): Promise { + public async estimateJobFee(sender: string, estimateJobMsg: EstimateJobMsg, reward?: string): Promise { const state = await this.state(); const config = await this.config(); - const jobReward = reward ? Big(reward) : await this.estimateJobReward(sender, estimateJobMsg); + const denom = await this.nativeTokenDenom(); + const jobReward: Coin = reward ? new Coin(denom, reward) : await this.estimateJobReward(sender, estimateJobMsg); - const burnFee = computeBurnFee(jobReward, config); + const jobRewardAmount = Big(jobReward.amount.toString()); + const burnFee = computeBurnFee(jobRewardAmount, config); const maintenanceFee = computeMaintenanceFee(Big(estimateJobMsg.duration_days), config); const creationFee = computeCreationFee(Big(state.q), config); - const totalFee = jobReward.add(burnFee).add(creationFee).add(maintenanceFee); + const totalFee = jobRewardAmount.add(burnFee).add(creationFee).add(maintenanceFee); - return totalFee; + return new Coin(denom, totalFee.toString()); } - public async estimateJobReward(sender: string, estimateJobMsg: EstimateJobMsg): Promise { - let estimatedReward = Big(0); + public async estimateJobReward(sender: string, estimateJobMsg: EstimateJobMsg): Promise { + const denom = await this.nativeTokenDenom(); + let estimatedReward = new Coin(denom, 0); for (let execution of estimateJobMsg.executions) { estimatedReward = estimatedReward.add(await this.estimateJobExecutionReward(sender, estimateJobMsg, execution)); @@ -257,7 +260,7 @@ export class WarpSdk { sender: string, estimateJobMsg: EstimateJobMsg, execution: warp_controller.Execution - ): Promise { + ): Promise { // const account = await this.account(sender); // TODO: check if this works, as before first job is created, no account is assigned to free job accounts const response = await this.freeJobAccounts({ account_owner_addr: sender }); @@ -328,7 +331,7 @@ export class WarpSdk { const denom = await this.nativeTokenDenom(); - return Big(fee.amount.get(denom).amount.toString()).mul(FEE_ADJUSTMENT_FACTOR); + return new Coin(denom, Big(fee.amount.get(denom).amount.toString()).mul(FEE_ADJUSTMENT_FACTOR).toString()); } public async nativeTokenDenom(): Promise { From 293534cebf386c8e2d8ce6bdc045d21314eaf03e Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 13 Nov 2023 14:05:06 +0100 Subject: [PATCH 15/44] minor --- src/types/contracts/warp_job_account_tracker.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/types/contracts/warp_job_account_tracker.ts b/src/types/contracts/warp_job_account_tracker.ts index 5259be6..450dd80 100644 --- a/src/types/contracts/warp_job_account_tracker.ts +++ b/src/types/contracts/warp_job_account_tracker.ts @@ -1,14 +1,14 @@ export module warp_job_account_tracker { export type Addr = string; export type Uint64 = string; - export interface AccountsResponse { - accounts: Account[]; - total_count: number; - } export interface Account { addr: Addr; taken_by_job_id?: Uint64 | null; } + export interface AccountsResponse { + accounts: Account[]; + total_count: number; + } export interface Config { admin: Addr; warp_addr: Addr; From 17f95de34af86079f6746ae080e39982672a8438 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 13 Nov 2023 18:50:03 +0100 Subject: [PATCH 16/44] new warp-msg updates --- src/composers/account.ts | 10 ++- src/composers/index.ts | 2 +- src/composers/job.ts | 2 +- src/composers/msg.ts | 84 ++++++++++++++----------- src/examples/example_cross_chain.ts | 4 +- src/sdk.ts | 17 ++++- src/types/contracts/warp_controller.ts | 34 +++++++++- src/types/contracts/warp_job_account.ts | 28 +++++++-- src/types/contracts/warp_resolver.ts | 47 ++++++++++++++ src/types/job.ts | 4 +- 10 files changed, 179 insertions(+), 53 deletions(-) diff --git a/src/composers/account.ts b/src/composers/account.ts index 96051bf..bc7ce3a 100644 --- a/src/composers/account.ts +++ b/src/composers/account.ts @@ -3,11 +3,19 @@ import { warp_job_account, warp_resolver } from '../types'; type GenericMsg = Extract; export class AccountComposer { - generic(msgs: warp_resolver.CosmosMsgFor_Empty[]): GenericMsg { + generic(msgs: warp_resolver.CosmosMsgFor_Empty[]): Extract { return { generic: { msgs, }, }; } + + msgs(msgs: warp_resolver.WarpMsg[]): Extract { + return { + warp_msgs: { + msgs, + }, + }; + } } diff --git a/src/composers/index.ts b/src/composers/index.ts index 442cd00..4d8d7a0 100644 --- a/src/composers/index.ts +++ b/src/composers/index.ts @@ -41,7 +41,7 @@ export const composers = { string, cond, fn, - msg, + msg: {}, template, job, variable, diff --git a/src/composers/job.ts b/src/composers/job.ts index 72b58a7..5379988 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -1,6 +1,6 @@ import { warp_controller, warp_resolver } from '../types/contracts'; -type Execution = [warp_resolver.Condition, warp_resolver.CosmosMsgFor_Empty[]]; +type Execution = [warp_resolver.Condition, warp_resolver.WarpMsg[]]; export class JobSequenceMsgComposer { static new() { diff --git a/src/composers/msg.ts b/src/composers/msg.ts index 5a0bd97..70b5079 100644 --- a/src/composers/msg.ts +++ b/src/composers/msg.ts @@ -3,36 +3,32 @@ import { warp_resolver } from '../types'; import { base64encode } from '../utils'; export class MessageComposer { - send(amount: warp_resolver.Coin[], to_address: string): warp_resolver.CosmosMsgFor_Empty { - return { bank: { send: { amount, to_address } } }; + send(amount: warp_resolver.Coin[], to_address: string): warp_resolver.WarpMsg { + return { generic: { bank: { send: { amount, to_address } } } }; } - burn(amount: warp_resolver.Coin[]): warp_resolver.CosmosMsgFor_Empty { - return { bank: { burn: { amount } } }; + burn(amount: warp_resolver.Coin[]): warp_resolver.WarpMsg { + return { generic: { bank: { burn: { amount } } } }; } - delegate(amount: warp_resolver.Coin, validator: string): warp_resolver.CosmosMsgFor_Empty { - return { staking: { delegate: { amount, validator } } }; + delegate(amount: warp_resolver.Coin, validator: string): warp_resolver.WarpMsg { + return { generic: { staking: { delegate: { amount, validator } } } }; } - undelegate(amount: warp_resolver.Coin, validator: string): warp_resolver.CosmosMsgFor_Empty { - return { staking: { undelegate: { amount, validator } } }; + undelegate(amount: warp_resolver.Coin, validator: string): warp_resolver.WarpMsg { + return { generic: { staking: { undelegate: { amount, validator } } } }; } - redelegate( - amount: warp_resolver.Coin, - dst_validator: string, - src_validator: string - ): warp_resolver.CosmosMsgFor_Empty { - return { staking: { redelegate: { amount, dst_validator, src_validator } } }; + redelegate(amount: warp_resolver.Coin, dst_validator: string, src_validator: string): warp_resolver.WarpMsg { + return { generic: { staking: { redelegate: { amount, dst_validator, src_validator } } } }; } - setWithdrawAddress(address: string): warp_resolver.CosmosMsgFor_Empty { - return { distribution: { set_withdraw_address: { address } } }; + setWithdrawAddress(address: string): warp_resolver.WarpMsg { + return { generic: { distribution: { set_withdraw_address: { address } } } }; } - withdrawDelegatorReward(validator: string): warp_resolver.CosmosMsgFor_Empty { - return { distribution: { withdraw_delegator_reward: { validator } } }; + withdrawDelegatorReward(validator: string): warp_resolver.WarpMsg { + return { generic: { distribution: { withdraw_delegator_reward: { validator } } } }; } transfer( @@ -40,23 +36,27 @@ export class MessageComposer { channel_id: string, timeout: warp_resolver.IbcTimeout, to_address: string - ): warp_resolver.CosmosMsgFor_Empty { - return { ibc: { transfer: { amount, channel_id, timeout, to_address } } }; + ): warp_resolver.WarpMsg { + return { generic: { ibc: { transfer: { amount, channel_id, timeout, to_address } } } }; } - sendPacket(channel_id: string, data: T, timeout: warp_resolver.IbcTimeout): warp_resolver.CosmosMsgFor_Empty { + sendPacket(channel_id: string, data: T, timeout: warp_resolver.IbcTimeout): warp_resolver.WarpMsg { return { - ibc: { send_packet: { channel_id, data: variableRefOrEncode(data), timeout } }, + generic: { + ibc: { send_packet: { channel_id, data: variableRefOrEncode(data), timeout } }, + }, }; } - closeChannel(channel_id: string): warp_resolver.CosmosMsgFor_Empty { - return { ibc: { close_channel: { channel_id } } }; + closeChannel(channel_id: string): warp_resolver.WarpMsg { + return { generic: { ibc: { close_channel: { channel_id } } } }; } - execute(contract_addr: string, msg: T, funds: warp_resolver.Coin[] = []): warp_resolver.CosmosMsgFor_Empty { + execute(contract_addr: string, msg: T, funds: warp_resolver.Coin[] = []): warp_resolver.WarpMsg { return { - wasm: { execute: { contract_addr, funds, msg: variableRefOrEncode(msg) } }, + generic: { + wasm: { execute: { contract_addr, funds, msg: variableRefOrEncode(msg) } }, + }, }; } @@ -66,24 +66,36 @@ export class MessageComposer { label: string, msg: T, funds: warp_resolver.Coin[] = [] - ): warp_resolver.CosmosMsgFor_Empty { - return { wasm: { instantiate: { admin, code_id, funds, label, msg: variableRefOrEncode(msg) } } }; + ): warp_resolver.WarpMsg { + return { generic: { wasm: { instantiate: { admin, code_id, funds, label, msg: variableRefOrEncode(msg) } } } }; + } + + migrate(contract_addr: string, msg: T, new_code_id: number): warp_resolver.WarpMsg { + return { generic: { wasm: { migrate: { contract_addr, msg: variableRefOrEncode(msg), new_code_id } } } }; } - migrate(contract_addr: string, msg: T, new_code_id: number): warp_resolver.CosmosMsgFor_Empty { - return { wasm: { migrate: { contract_addr, msg: variableRefOrEncode(msg), new_code_id } } }; + update_admin(admin: string, contract_addr: string): warp_resolver.WarpMsg { + return { generic: { wasm: { update_admin: { admin, contract_addr } } } }; } - update_admin(admin: string, contract_addr: string): warp_resolver.CosmosMsgFor_Empty { - return { wasm: { update_admin: { admin, contract_addr } } }; + clear_admin(contract_addr: string): warp_resolver.WarpMsg { + return { generic: { wasm: { clear_admin: { contract_addr } } } }; } - clear_admin(contract_addr: string): warp_resolver.CosmosMsgFor_Empty { - return { wasm: { clear_admin: { contract_addr } } }; + vote(proposal_id: number, vote: warp_resolver.VoteOption): warp_resolver.WarpMsg { + return { generic: { gov: { vote: { proposal_id, vote } } } }; } - vote(proposal_id: number, vote: warp_resolver.VoteOption): warp_resolver.CosmosMsgFor_Empty { - return { gov: { vote: { proposal_id, vote } } }; + withdrawAssets(msg: warp_resolver.WithdrawAssetsMsg): warp_resolver.WarpMsg { + return { + withdraw_assets: msg, + }; + } + + ibcTransfer(msg: warp_resolver.IbcTransferMsg): warp_resolver.WarpMsg { + return { + ibc_transfer: msg, + }; } } diff --git a/src/examples/example_cross_chain.ts b/src/examples/example_cross_chain.ts index 31955ad..77416a6 100644 --- a/src/examples/example_cross_chain.ts +++ b/src/examples/example_cross_chain.ts @@ -75,13 +75,13 @@ const swapVariable = variable .encode(true) .compose(); -const routedSwapMsg = account.generic([ +const routedSwapMsg = account.msgs([ msg.execute(neutronRouter, variable.ref(swapVariable), [ { denom: 'untrn', amount: '$warp.variable.neutron_balance' }, ]), ]); -const transferMsg = account.generic([ +const transferMsg = account.msgs([ msg.transfer({ denom: astro, amount: '1' }, transferChannel, { timestamp: '1692915449102000000' }, terraRecipient), ]); diff --git a/src/sdk.ts b/src/sdk.ts index 0777dd0..101e260 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -154,10 +154,10 @@ export class WarpSdk { return response; } - public async hydrateMsgs(msg: warp_resolver.QueryHydrateMsgsMsg): Promise { + public async hydrateMsgs(msg: warp_resolver.QueryHydrateMsgsMsg): Promise { const response = await contractQuery< Extract, - warp_resolver.CosmosMsgFor_Empty[] + warp_resolver.WarpMsg[] >(this.wallet.lcd, this.chain.contracts.resolver, { query_hydrate_msgs: msg }); return response; @@ -312,7 +312,18 @@ export class WarpSdk { ); } - msgs.push(...hydratedMsgs.map((msg) => cosmosMsgToCreateTxMsg(account, msg))); + // TODO: query transformed msgs from contracts + let transformedMsgs: warp_resolver.CosmosMsgFor_Empty[] = hydratedMsgs + .map((m) => { + if ('generic' in m) { + return m.generic; + } + + return null; + }) + .filter(Boolean); + + msgs.push(...transformedMsgs.map((msg) => cosmosMsgToCreateTxMsg(account, msg))); const accountInfo = await this.wallet.lcd.auth.accountInfo(account); diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 0aaaeaf..ebff1d5 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -65,6 +65,16 @@ export module warp_controller { | { migrate_finished_jobs: MigrateJobsMsg; }; + export type WarpMsg = + | { + generic: CosmosMsgFor_Empty; + } + | { + ibc_transfer: IbcTransferMsg; + } + | { + withdraw_assets: WithdrawAssetsMsg; + }; export type CosmosMsgFor_Empty = | { bank: BankMsg; @@ -264,7 +274,7 @@ export module warp_controller { cw721: Cw721Fund; }; export interface CreateJobMsg { - account_msgs?: CosmosMsgFor_Empty[] | null; + account_msgs?: WarpMsg[] | null; assets_to_withdraw?: AssetInfo[] | null; cw_funds?: CwFund[] | null; description: string; @@ -296,6 +306,28 @@ export module warp_controller { */ revision: number; } + export interface IbcTransferMsg { + timeout_block_delta?: number | null; + timeout_timestamp_seconds_delta?: number | null; + transfer_msg: TransferMsg; + } + export interface TransferMsg { + memo: string; + receiver: string; + sender: string; + source_channel: string; + source_port: string; + timeout_block?: TimeoutBlock | null; + timeout_timestamp?: number | null; + token?: Coin | null; + } + export interface TimeoutBlock { + revision_height?: number | null; + revision_number?: number | null; + } + export interface WithdrawAssetsMsg { + asset_infos: AssetInfo[]; + } export interface Cw20Fund { amount: Uint128; contract_addr: string; diff --git a/src/types/contracts/warp_job_account.ts b/src/types/contracts/warp_job_account.ts index d9e22f4..e93043f 100644 --- a/src/types/contracts/warp_job_account.ts +++ b/src/types/contracts/warp_job_account.ts @@ -5,6 +5,9 @@ export module warp_job_account { owner: Addr; } export type ExecuteMsg = + | { + warp_msgs: WarpMsgs; + } | { generic: GenericMsg; } @@ -14,6 +17,16 @@ export module warp_job_account { | { ibc_transfer: IbcTransferMsg; }; + export type WarpMsg = + | { + generic: CosmosMsgFor_Empty; + } + | { + ibc_transfer: IbcTransferMsg; + } + | { + withdraw_assets: WithdrawAssetsMsg; + }; export type CosmosMsgFor_Empty = | { bank: BankMsg; @@ -207,8 +220,8 @@ export module warp_job_account { */ cw721: [Addr, string]; }; - export interface GenericMsg { - msgs: CosmosMsgFor_Empty[]; + export interface WarpMsgs { + msgs: WarpMsg[]; } export interface Coin { amount: Uint128; @@ -229,9 +242,6 @@ export module warp_job_account { */ revision: number; } - export interface WithdrawAssetsMsg { - asset_infos: AssetInfo[]; - } export interface IbcTransferMsg { timeout_block_delta?: number | null; timeout_timestamp_seconds_delta?: number | null; @@ -251,6 +261,12 @@ export module warp_job_account { revision_height?: number | null; revision_number?: number | null; } + export interface WithdrawAssetsMsg { + asset_infos: AssetInfo[]; + } + export interface GenericMsg { + msgs: CosmosMsgFor_Empty[]; + } export type CwFund = | { cw20: Cw20Fund; @@ -261,7 +277,7 @@ export module warp_job_account { export interface InstantiateMsg { cw_funds: CwFund[]; job_id: Uint64; - msgs: CosmosMsgFor_Empty[]; + msgs: WarpMsg[]; native_funds: Coin[]; owner: string; } diff --git a/src/types/contracts/warp_resolver.ts b/src/types/contracts/warp_resolver.ts index b373130..395268c 100644 --- a/src/types/contracts/warp_resolver.ts +++ b/src/types/contracts/warp_resolver.ts @@ -656,4 +656,51 @@ export module warp_resolver { query: QueryRequestFor_String; selector: string; } + export type WarpMsg = + | { + generic: CosmosMsgFor_Empty; + } + | { + ibc_transfer: IbcTransferMsg; + } + | { + withdraw_assets: WithdrawAssetsMsg; + }; + export type AssetInfo = + | { + native: string; + } + | { + cw20: Addr; + } + | { + /** + * @minItems 2 + * @maxItems 2 + */ + cw721: [Addr, string]; + }; + export type Addr = string; + export interface IbcTransferMsg { + timeout_block_delta?: number | null; + timeout_timestamp_seconds_delta?: number | null; + transfer_msg: TransferMsg; + } + export interface TransferMsg { + memo: string; + receiver: string; + sender: string; + source_channel: string; + source_port: string; + timeout_block?: TimeoutBlock | null; + timeout_timestamp?: number | null; + token?: Coin | null; + } + export interface TimeoutBlock { + revision_height?: number | null; + revision_number?: number | null; + } + export interface WithdrawAssetsMsg { + asset_infos: AssetInfo[]; + } } diff --git a/src/types/job.ts b/src/types/job.ts index 2aa11ca..32732b8 100644 --- a/src/types/job.ts +++ b/src/types/job.ts @@ -2,7 +2,7 @@ import { warp_controller, warp_resolver } from './contracts'; export type Execution = { condition: warp_resolver.Condition; - msgs: warp_resolver.CosmosMsgFor_Empty[]; + msgs: warp_resolver.WarpMsg[]; }; export type Job = Omit & { @@ -21,7 +21,7 @@ export type JobsResponse = { export const parseExecution = (execution: warp_controller.Execution): Execution => { return { - msgs: JSON.parse(execution.msgs) as warp_resolver.CosmosMsgFor_Empty[], + msgs: JSON.parse(execution.msgs) as warp_resolver.WarpMsg[], condition: JSON.parse(execution.condition) as warp_resolver.Condition, }; }; From d1b39a3763ad3d5d7e50ce4f698fc73fab2710c7 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 28 Nov 2023 17:32:57 +0100 Subject: [PATCH 17/44] new job account types and interface updates + funding accounts --- src/composers/account.ts | 10 --- src/modules/tx.ts | 18 +++++- src/sdk.ts | 21 ++++++- src/types/contracts/warp_controller.ts | 10 ++- src/types/contracts/warp_job_account.ts | 19 +----- .../contracts/warp_job_account_tracker.ts | 62 ++++++++++++++++++- 6 files changed, 107 insertions(+), 33 deletions(-) diff --git a/src/composers/account.ts b/src/composers/account.ts index bc7ce3a..814b2cf 100644 --- a/src/composers/account.ts +++ b/src/composers/account.ts @@ -1,16 +1,6 @@ import { warp_job_account, warp_resolver } from '../types'; -type GenericMsg = Extract; - export class AccountComposer { - generic(msgs: warp_resolver.CosmosMsgFor_Empty[]): Extract { - return { - generic: { - msgs, - }, - }; - } - msgs(msgs: warp_resolver.WarpMsg[]): Extract { return { warp_msgs: { diff --git a/src/modules/tx.ts b/src/modules/tx.ts index beda7ca..09b6326 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -122,6 +122,18 @@ export class TxModule { .build(); } + public async createFundingAccount(sender: string): Promise { + return TxBuilder.new(this.warpSdk.chain.config) + .execute>( + sender, + this.warpSdk.chain.contracts.controller, + { + create_funding_account: {}, + } + ) + .build(); + } + public async submitTemplate(sender: string, msg: warp_templates.SubmitTemplateMsg): Promise { const config = await this.warpSdk.config(); @@ -323,8 +335,10 @@ export class TxModule { const job = await this.warpSdk.job(job_id); const txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute>(sender, job.account, { - withdraw_assets: msg, + .execute>(sender, job.account, { + warp_msgs: { + msgs: [{ withdraw_assets: msg }], + }, }) .build(); diff --git a/src/sdk.ts b/src/sdk.ts index 101e260..2c9675c 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -15,7 +15,7 @@ import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; import { warp_templates } from './types/contracts/warp_templates'; import { Job, parseJob } from './types/job'; -import { warp_job_account_tracker } from 'types/contracts'; +import { warp_job_account_tracker } from './types/contracts'; const FEE_ADJUSTMENT_FACTOR = 3; @@ -185,6 +185,17 @@ export class WarpSdk { return response; } + public async fundingAccounts( + msg: warp_job_account_tracker.QueryFundingAccountsMsg + ): Promise { + const response = await contractQuery< + Extract, + warp_job_account_tracker.FundingAccountsResponse + >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_funding_accounts: msg }); + + return response; + } + // Legacy account support public async legacyAccount(owner: string): Promise { @@ -312,7 +323,7 @@ export class WarpSdk { ); } - // TODO: query transformed msgs from contracts + // check only cosmos msg for estimation let transformedMsgs: warp_resolver.CosmosMsgFor_Empty[] = hydratedMsgs .map((m) => { if ('generic' in m) { @@ -403,6 +414,12 @@ export class WarpSdk { return this.wallet.tx(txPayload); } + public async createFundingAccount(sender: string): Promise { + const txPayload = await this.tx.createFundingAccount(sender); + + return this.wallet.tx(txPayload); + } + public async submitTemplate(sender: string, msg: warp_templates.SubmitTemplateMsg): Promise { const txPayload = await this.tx.submitTemplate(sender, msg); diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index ebff1d5..8d850e4 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -64,6 +64,9 @@ export module warp_controller { } | { migrate_finished_jobs: MigrateJobsMsg; + } + | { + create_funding_account: CreateFundingAccountMsg; }; export type WarpMsg = | { @@ -280,8 +283,10 @@ export module warp_controller { description: string; duration_days: Uint64; executions: Execution[]; + funding_account?: Addr | null; labels: string[]; name: string; + operational_amount: Uint128; recurring: boolean; reward: Uint128; terminate_condition?: string | null; @@ -397,6 +402,7 @@ export module warp_controller { limit: number; start_after?: Uint64 | null; } + export interface CreateFundingAccountMsg {} export interface InstantiateMsg { a_max: Uint128; a_min: Uint128; @@ -410,7 +416,7 @@ export module warp_controller { duration_days_right: Uint64; fee_collector?: string | null; fee_denom: string; - job_account_tracker_address: string; + job_account_tracker_code_id: Uint64; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; @@ -434,10 +440,12 @@ export module warp_controller { description: string; duration_days: Uint64; executions: Execution[]; + funding_account?: Addr | null; id: Uint64; labels: string[]; last_update_time: Uint64; name: string; + operational_amount: Uint128; owner: Addr; prev_id?: Uint64 | null; recurring: boolean; diff --git a/src/types/contracts/warp_job_account.ts b/src/types/contracts/warp_job_account.ts index e93043f..f7d939a 100644 --- a/src/types/contracts/warp_job_account.ts +++ b/src/types/contracts/warp_job_account.ts @@ -4,19 +4,9 @@ export module warp_job_account { creator_addr: Addr; owner: Addr; } - export type ExecuteMsg = - | { - warp_msgs: WarpMsgs; - } - | { - generic: GenericMsg; - } - | { - withdraw_assets: WithdrawAssetsMsg; - } - | { - ibc_transfer: IbcTransferMsg; - }; + export type ExecuteMsg = { + warp_msgs: WarpMsgs; + }; export type WarpMsg = | { generic: CosmosMsgFor_Empty; @@ -264,9 +254,6 @@ export module warp_job_account { export interface WithdrawAssetsMsg { asset_infos: AssetInfo[]; } - export interface GenericMsg { - msgs: CosmosMsgFor_Empty[]; - } export type CwFund = | { cw20: Cw20Fund; diff --git a/src/types/contracts/warp_job_account_tracker.ts b/src/types/contracts/warp_job_account_tracker.ts index 450dd80..4436110 100644 --- a/src/types/contracts/warp_job_account_tracker.ts +++ b/src/types/contracts/warp_job_account_tracker.ts @@ -5,6 +5,9 @@ export module warp_job_account_tracker { addr: Addr; taken_by_job_id?: Uint64 | null; } + export interface AccountResponse { + account?: Account | null; + } export interface AccountsResponse { accounts: Account[]; total_count: number; @@ -22,6 +25,15 @@ export module warp_job_account_tracker { } | { free_account: FreeAccountMsg; + } + | { + take_funding_account: TakeFundingAccountMsg; + } + | { + free_funding_account: FreeFundingAccountMsg; + } + | { + add_funding_account: AddFundingAccountMsg; }; export interface TakeAccountMsg { account_addr: string; @@ -33,8 +45,29 @@ export module warp_job_account_tracker { account_owner_addr: string; last_job_id: Uint64; } - export interface FirstFreeAccountResponse { - account?: Account | null; + export interface TakeFundingAccountMsg { + account_addr: string; + account_owner_addr: string; + job_id: Uint64; + } + export interface FreeFundingAccountMsg { + account_addr: string; + account_owner_addr: string; + job_id: Uint64; + } + export interface AddFundingAccountMsg { + account_addr: string; + account_owner_addr: string; + } + export interface FundingAccountResponse { + funding_account?: FundingAccount | null; + } + export interface FundingAccount { + account_addr: Addr; + taken_by_job_ids: Uint64[]; + } + export interface FundingAccountsResponse { + funding_accounts: FundingAccount[]; } export interface InstantiateMsg { admin: string; @@ -52,6 +85,18 @@ export module warp_job_account_tracker { } | { query_first_free_account: QueryFirstFreeAccountMsg; + } + | { + query_free_account: QueryFreeAccountMsg; + } + | { + query_first_free_funding_account: QueryFirstFreeFundingAccountMsg; + } + | { + query_funding_accounts: QueryFundingAccountsMsg; + } + | { + query_funding_account: QueryFundingAccountMsg; }; export interface QueryConfigMsg {} export interface QueryTakenAccountsMsg { @@ -67,4 +112,17 @@ export module warp_job_account_tracker { export interface QueryFirstFreeAccountMsg { account_owner_addr: string; } + export interface QueryFreeAccountMsg { + account_addr: string; + } + export interface QueryFirstFreeFundingAccountMsg { + account_owner_addr: string; + } + export interface QueryFundingAccountsMsg { + account_owner_addr: string; + } + export interface QueryFundingAccountMsg { + account_addr: string; + account_owner_addr: string; + } } From d6deb872167a91519769429ad81153f57fe7da77 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 28 Nov 2023 17:33:32 +0100 Subject: [PATCH 18/44] new composer interface changes + update examples --- src/composers/job.ts | 67 ++++++++++++++++++-- src/examples/example_astro.ts | 94 +++++++++++++++++------------ src/examples/example_cross_chain.ts | 48 ++++++++++----- src/examples/example_eris.ts | 36 ++++++++--- 4 files changed, 181 insertions(+), 64 deletions(-) diff --git a/src/composers/job.ts b/src/composers/job.ts index 5379988..dddd586 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -1,6 +1,7 @@ +import { EstimateJobMsg } from 'sdk'; import { warp_controller, warp_resolver } from '../types/contracts'; -type Execution = [warp_resolver.Condition, warp_resolver.WarpMsg[]]; +export type ExecutionInput = [warp_resolver.Condition, warp_resolver.WarpMsg[]]; export class JobSequenceMsgComposer { static new() { @@ -46,8 +47,9 @@ export class CreateJobMsgComposer { private _labels: string[]; private _assetsToWithdraw: warp_controller.AssetInfo[] | undefined; private _vars: warp_resolver.Variable[] = []; - private _executions: Execution[] = []; + private _executions: ExecutionInput[] = []; private _durationDays: string; + private _operationalAmount: warp_controller.Uint128 | undefined; static new(): CreateJobMsgComposer { return new CreateJobMsgComposer(); @@ -83,12 +85,17 @@ export class CreateJobMsgComposer { return this; } + operationalAmount(operationalAmount: warp_controller.Uint128): CreateJobMsgComposer { + this._operationalAmount = operationalAmount; + return this; + } + assetsToWithdraw(assetsToWithdraw: warp_controller.AssetInfo[]): CreateJobMsgComposer { this._assetsToWithdraw = assetsToWithdraw; return this; } - executions(executions: Execution[]): CreateJobMsgComposer { + executions(executions: ExecutionInput[]): CreateJobMsgComposer { this._executions = executions; return this; } @@ -104,7 +111,8 @@ export class CreateJobMsgComposer { this._recurring === undefined || this._reward === undefined || this._description === undefined || - this._labels === undefined + this._labels === undefined || + this._operationalAmount == undefined ) { throw new Error('All required fields must be provided'); } @@ -119,14 +127,65 @@ export class CreateJobMsgComposer { duration_days: this._durationDays, vars: JSON.stringify(this._vars), assets_to_withdraw: this._assetsToWithdraw, + operational_amount: this._operationalAmount, }; return createJobMsg; } } +export class EstimateJobMsgComposer { + private _recurring: boolean | undefined; + private _vars: warp_resolver.Variable[] = []; + private _executions: ExecutionInput[] = []; + private _durationDays: string; + + static new(): EstimateJobMsgComposer { + return new EstimateJobMsgComposer(); + } + + recurring(recurring: boolean): EstimateJobMsgComposer { + this._recurring = recurring; + return this; + } + + durationDays(durationDays: string): EstimateJobMsgComposer { + this._durationDays = durationDays; + return this; + } + + executions(executions: ExecutionInput[]): EstimateJobMsgComposer { + this._executions = executions; + return this; + } + + vars(vars: warp_resolver.Variable[]): EstimateJobMsgComposer { + this._vars = vars; + return this; + } + + compose(): EstimateJobMsg { + if (this._recurring === undefined || this._durationDays === undefined) { + throw new Error('All required fields must be provided'); + } + + const estimateJobMsg: EstimateJobMsg = { + recurring: this._recurring, + executions: this._executions.map((e) => ({ condition: JSON.stringify(e[0]), msgs: JSON.stringify(e[1]) })), + duration_days: this._durationDays, + vars: JSON.stringify(this._vars), + }; + + return estimateJobMsg; + } +} + export class JobComposer { create(): CreateJobMsgComposer { return new CreateJobMsgComposer(); } + + estimate(): EstimateJobMsgComposer { + return new EstimateJobMsgComposer(); + } } diff --git a/src/examples/example_astro.ts b/src/examples/example_astro.ts index 550ef12..8176ae5 100644 --- a/src/examples/example_astro.ts +++ b/src/examples/example_astro.ts @@ -2,7 +2,7 @@ export { TerraTxError } from '../wallet/utils'; import dotenv from 'dotenv'; import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; import { WarpSdk } from '../sdk'; -import { uint, cond, msg, variable, job, query } from '../composers'; +import { uint, cond, msg, variable, job, query, ExecutionInput } from '../composers'; dotenv.config(); @@ -64,51 +64,69 @@ const astroReceived = variable const condition = cond.uint(uint.ref(astroReceived), 'gte', uint.simple(limitOrder.astroPurchaseAmount)); -const createJobMsg = job - .create() - .name('astroport-limit-order') - .reward('50000') - .recurring(false) - .description('This job creates an astroport limit order.') - .labels([]) - .reward('50000') - .vars([astroReceived]) - .durationDays('30') - .executions([ +const executions: ExecutionInput[] = [ + [ + condition, [ - condition, - [ - msg.execute( - astroportContract, - { - execute_swap_operations: { - max_spread: limitOrder.maxSpread, - minimum_receive: limitOrder.astroPurchaseAmount, - operations: [ - { - astro_swap: { - ask_asset_info: { - token: { - contract_addr: limitOrder.astroTokenContract, - }, + msg.execute( + astroportContract, + { + execute_swap_operations: { + max_spread: limitOrder.maxSpread, + minimum_receive: limitOrder.astroPurchaseAmount, + operations: [ + { + astro_swap: { + ask_asset_info: { + token: { + contract_addr: limitOrder.astroTokenContract, }, - offer_asset_info: { - native_token: { - denom: 'uluna', - }, + }, + offer_asset_info: { + native_token: { + denom: 'uluna', }, }, }, - ], - }, + }, + ], }, - [{ denom: 'uluna', amount: limitOrder.lunaOfferAmount }] - ), - ], + }, + [{ denom: 'uluna', amount: limitOrder.lunaOfferAmount }] + ), ], - ]) + ], +]; + +const recurring = false; +const durationDays = '30'; +const vars = [astroReceived]; + +const estimateJobRewardMsg = job + .estimate() + .recurring(recurring) + .durationDays(durationDays) + .vars(vars) + .executions(executions) + .compose(); + +const reward = await sdk.estimateJobReward(sender, estimateJobRewardMsg); + +const operationalAmount = await sdk.estimateJobFee(sender, estimateJobRewardMsg, reward.amount.toString()); + +const createJobMsg = job + .create() + .name('astroport-limit-order') + .reward(reward.amount.toString()) + .operationalAmount(operationalAmount.amount.toString()) + .recurring(recurring) + .description('This job creates an astroport limit order.') + .labels([]) + .vars(vars) + .durationDays(durationDays) + .executions(executions) .compose(); -sdk.createJob(sender, createJobMsg).then((response) => { +sdk.createJob(sender, createJobMsg, [operationalAmount]).then((response) => { console.log(response); }); diff --git a/src/examples/example_cross_chain.ts b/src/examples/example_cross_chain.ts index 77416a6..b638da2 100644 --- a/src/examples/example_cross_chain.ts +++ b/src/examples/example_cross_chain.ts @@ -2,7 +2,7 @@ export { TerraTxError } from '../wallet/utils'; import dotenv from 'dotenv'; import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; import { WarpSdk } from '../sdk'; -import { uint, cond, msg, variable, job, query, account } from '../composers'; +import { uint, cond, msg, variable, job, query, account, ExecutionInput } from '../composers'; import { addYears } from 'date-fns'; dotenv.config(); @@ -163,25 +163,45 @@ const transferVariable = variable const condition = cond.uint(uint.ref(untrnAmount), 'gt', uint.simple('10000')); +const executions: ExecutionInput[] = [ + [ + condition, + [ + msg.execute(neutronBurnAccount, variable.ref(routedSwapVariable)), + msg.execute(neutronBurnAccount, variable.ref(transferVariable)), + ], + ], +]; + +const recurring = true; +const durationDays = '30'; +const vars = [untrnAmount, timeoutTimestamp, simulateAstroAmount, transferVariable, swapVariable, routedSwapVariable]; + +const estimateJobRewardMsg = job + .estimate() + .recurring(recurring) + .durationDays(durationDays) + .vars(vars) + .executions(executions) + .compose(); + +const reward = await sdk.estimateJobReward(sender, estimateJobRewardMsg); + +const operationalAmount = await sdk.estimateJobFee(sender, estimateJobRewardMsg, reward.amount.toString()); + const createJobMsg = job .create() .name('swap-and-send') .description('') - .recurring(true) - .reward('1000') - .vars([untrnAmount, timeoutTimestamp, simulateAstroAmount, transferVariable, swapVariable, routedSwapVariable]) - .executions([ - [ - condition, - [ - msg.execute(neutronBurnAccount, variable.ref(routedSwapVariable)), - msg.execute(neutronBurnAccount, variable.ref(transferVariable)), - ], - ], - ]) + .recurring(recurring) + .reward(reward.amount.toString()) + .operationalAmount(operationalAmount.amount.toString()) + .vars(vars) + .executions(executions) + .durationDays(durationDays) .labels([]) .compose(); -sdk.createJob(sender, createJobMsg).then((response) => { +sdk.createJob(sender, createJobMsg, [operationalAmount]).then((response) => { console.log(response); }); diff --git a/src/examples/example_eris.ts b/src/examples/example_eris.ts index aa716f6..86116dc 100644 --- a/src/examples/example_eris.ts +++ b/src/examples/example_eris.ts @@ -1,6 +1,6 @@ import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; import { WarpSdk } from '../sdk'; -import { uint, cond, fn, msg, variable, job, ts } from '../composers'; +import { uint, cond, fn, msg, variable, job, ts, ExecutionInput } from '../composers'; const piscoLcdClientConfig: LCDClientConfig = { lcd: 'https://pisco-lcd.terra.dev', @@ -30,19 +30,39 @@ const nextExecution = variable const condition = cond.uint(uint.env('time'), 'gt', uint.ref(nextExecution)); +const executions: ExecutionInput[] = [ + [condition, [msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })]], +]; + +const recurring = true; +const durationDays = '30'; +const vars = [nextExecution]; + +const estimateJobRewardMsg = job + .estimate() + .recurring(recurring) + .durationDays(durationDays) + .vars(vars) + .executions(executions) + .compose(); + +const reward = await sdk.estimateJobReward(sender, estimateJobRewardMsg); + +const operationalAmount = await sdk.estimateJobFee(sender, estimateJobRewardMsg, reward.amount.toString()); + const createJobMsg = job .create() .name('eris-harvest') .description('This job harvests rewards for eris protoocl vaults each day.') .labels([]) - .recurring(true) - .reward('50000') - .vars([nextExecution]) - .executions([ - [condition, [msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })]], - ]) + .recurring(recurring) + .reward(reward.amount.toString()) + .operationalAmount(operationalAmount.amount.toString()) + .vars(vars) + .durationDays(durationDays) + .executions(executions) .compose(); -sdk.createJob(sender, createJobMsg).then((response) => { +sdk.createJob(sender, createJobMsg, [operationalAmount]).then((response) => { console.log(response); }); From f27808a63dc3c3ebb54965486b706814954fb58d Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 28 Nov 2023 17:45:11 +0100 Subject: [PATCH 19/44] update executions interface --- src/composers/job.ts | 21 +++++++++++++-------- src/examples/example_astro.ts | 10 +++++----- src/examples/example_cross_chain.ts | 10 +++++----- src/examples/example_eris.ts | 9 ++++++--- src/utils/fee.ts | 2 +- 5 files changed, 30 insertions(+), 22 deletions(-) diff --git a/src/composers/job.ts b/src/composers/job.ts index dddd586..df29bbe 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -1,8 +1,7 @@ import { EstimateJobMsg } from 'sdk'; +import { Execution } from '../types'; import { warp_controller, warp_resolver } from '../types/contracts'; -export type ExecutionInput = [warp_resolver.Condition, warp_resolver.WarpMsg[]]; - export class JobSequenceMsgComposer { static new() { return new JobSequenceMsgComposer(); @@ -47,7 +46,7 @@ export class CreateJobMsgComposer { private _labels: string[]; private _assetsToWithdraw: warp_controller.AssetInfo[] | undefined; private _vars: warp_resolver.Variable[] = []; - private _executions: ExecutionInput[] = []; + private _executions: Execution[] = []; private _durationDays: string; private _operationalAmount: warp_controller.Uint128 | undefined; @@ -95,7 +94,7 @@ export class CreateJobMsgComposer { return this; } - executions(executions: ExecutionInput[]): CreateJobMsgComposer { + executions(executions: Execution[]): CreateJobMsgComposer { this._executions = executions; return this; } @@ -123,7 +122,10 @@ export class CreateJobMsgComposer { reward: this._reward, description: this._description, labels: this._labels, - executions: this._executions.map((e) => ({ condition: JSON.stringify(e[0]), msgs: JSON.stringify(e[1]) })), + executions: this._executions.map((e) => ({ + condition: JSON.stringify(e.condition), + msgs: JSON.stringify(e.msgs), + })), duration_days: this._durationDays, vars: JSON.stringify(this._vars), assets_to_withdraw: this._assetsToWithdraw, @@ -137,7 +139,7 @@ export class CreateJobMsgComposer { export class EstimateJobMsgComposer { private _recurring: boolean | undefined; private _vars: warp_resolver.Variable[] = []; - private _executions: ExecutionInput[] = []; + private _executions: Execution[] = []; private _durationDays: string; static new(): EstimateJobMsgComposer { @@ -154,7 +156,7 @@ export class EstimateJobMsgComposer { return this; } - executions(executions: ExecutionInput[]): EstimateJobMsgComposer { + executions(executions: Execution[]): EstimateJobMsgComposer { this._executions = executions; return this; } @@ -171,7 +173,10 @@ export class EstimateJobMsgComposer { const estimateJobMsg: EstimateJobMsg = { recurring: this._recurring, - executions: this._executions.map((e) => ({ condition: JSON.stringify(e[0]), msgs: JSON.stringify(e[1]) })), + executions: this._executions.map((e) => ({ + condition: JSON.stringify(e.condition), + msgs: JSON.stringify(e.msgs), + })), duration_days: this._durationDays, vars: JSON.stringify(this._vars), }; diff --git a/src/examples/example_astro.ts b/src/examples/example_astro.ts index 8176ae5..d7a8dd5 100644 --- a/src/examples/example_astro.ts +++ b/src/examples/example_astro.ts @@ -2,7 +2,7 @@ export { TerraTxError } from '../wallet/utils'; import dotenv from 'dotenv'; import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; import { WarpSdk } from '../sdk'; -import { uint, cond, msg, variable, job, query, ExecutionInput } from '../composers'; +import { uint, cond, msg, variable, job, query } from '../composers'; dotenv.config(); @@ -64,10 +64,10 @@ const astroReceived = variable const condition = cond.uint(uint.ref(astroReceived), 'gte', uint.simple(limitOrder.astroPurchaseAmount)); -const executions: ExecutionInput[] = [ - [ +const executions = [ + { condition, - [ + msgs: [ msg.execute( astroportContract, { @@ -95,7 +95,7 @@ const executions: ExecutionInput[] = [ [{ denom: 'uluna', amount: limitOrder.lunaOfferAmount }] ), ], - ], + }, ]; const recurring = false; diff --git a/src/examples/example_cross_chain.ts b/src/examples/example_cross_chain.ts index b638da2..7159d13 100644 --- a/src/examples/example_cross_chain.ts +++ b/src/examples/example_cross_chain.ts @@ -2,7 +2,7 @@ export { TerraTxError } from '../wallet/utils'; import dotenv from 'dotenv'; import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; import { WarpSdk } from '../sdk'; -import { uint, cond, msg, variable, job, query, account, ExecutionInput } from '../composers'; +import { uint, cond, msg, variable, job, query, account } from '../composers'; import { addYears } from 'date-fns'; dotenv.config(); @@ -163,14 +163,14 @@ const transferVariable = variable const condition = cond.uint(uint.ref(untrnAmount), 'gt', uint.simple('10000')); -const executions: ExecutionInput[] = [ - [ +const executions = [ + { condition, - [ + msgs: [ msg.execute(neutronBurnAccount, variable.ref(routedSwapVariable)), msg.execute(neutronBurnAccount, variable.ref(transferVariable)), ], - ], + }, ]; const recurring = true; diff --git a/src/examples/example_eris.ts b/src/examples/example_eris.ts index 86116dc..2268bdb 100644 --- a/src/examples/example_eris.ts +++ b/src/examples/example_eris.ts @@ -1,6 +1,6 @@ import { LCDClient, LCDClientConfig, MnemonicKey, Wallet } from '@terra-money/feather.js'; import { WarpSdk } from '../sdk'; -import { uint, cond, fn, msg, variable, job, ts, ExecutionInput } from '../composers'; +import { uint, cond, fn, msg, variable, job, ts } from '../composers'; const piscoLcdClientConfig: LCDClientConfig = { lcd: 'https://pisco-lcd.terra.dev', @@ -30,8 +30,11 @@ const nextExecution = variable const condition = cond.uint(uint.env('time'), 'gt', uint.ref(nextExecution)); -const executions: ExecutionInput[] = [ - [condition, [msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })]], +const executions = [ + { + condition, + msgs: [msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })], + }, ]; const recurring = true; diff --git a/src/utils/fee.ts b/src/utils/fee.ts index 34d3a44..74ca8ff 100644 --- a/src/utils/fee.ts +++ b/src/utils/fee.ts @@ -1,5 +1,5 @@ import Big from 'big.js'; -import { warp_controller } from 'types'; +import { warp_controller } from '../types'; export function computeCreationFee(queueSize: Big, config: warp_controller.Config): Big { const x1 = Big(config.queue_size_left); From 43541df140319fcee65815b69783cde688a50bdf Mon Sep 17 00:00:00 2001 From: simke9445 Date: Sat, 9 Dec 2023 18:56:59 +0100 Subject: [PATCH 20/44] new contract code --- package.json | 5 +- src/composers/account.ts | 4 +- src/modules/chain.ts | 6 +- src/modules/tx.ts | 111 +------ src/refs.injective.json | 4 +- src/refs.neutron.json | 4 +- src/refs.nibiru.json | 4 +- src/refs.terra.json | 9 +- src/sdk.ts | 87 ++---- src/types/contracts/index.ts | 5 +- .../{warp_job_account.ts => warp_account.ts} | 5 +- ...unt_tracker.ts => warp_account_tracker.ts} | 8 +- src/types/contracts/warp_controller.ts | 45 +-- src/types/contracts/warp_legacy_account.ts | 274 ------------------ 14 files changed, 52 insertions(+), 519 deletions(-) rename src/types/contracts/{warp_job_account.ts => warp_account.ts} (99%) rename src/types/contracts/{warp_job_account_tracker.ts => warp_account_tracker.ts} (94%) delete mode 100644 src/types/contracts/warp_legacy_account.ts diff --git a/package.json b/package.json index 61b20d6..e1841ac 100644 --- a/package.json +++ b/package.json @@ -42,11 +42,10 @@ "generate-types": { "contracts": [ "warp-controller", - "warp-legacy-account", "warp-resolver", "warp-templates", - "warp-job-account", - "warp-job-account-tracker" + "warp-account", + "warp-account-tracker" ], "output": "src/types/contracts" }, diff --git a/src/composers/account.ts b/src/composers/account.ts index 814b2cf..7d1509e 100644 --- a/src/composers/account.ts +++ b/src/composers/account.ts @@ -1,7 +1,7 @@ -import { warp_job_account, warp_resolver } from '../types'; +import { warp_account, warp_resolver } from '../types'; export class AccountComposer { - msgs(msgs: warp_resolver.WarpMsg[]): Extract { + msgs(msgs: warp_resolver.WarpMsg[]): Extract { return { warp_msgs: { msgs, diff --git a/src/modules/chain.ts b/src/modules/chain.ts index b8ebda8..cb4aad3 100644 --- a/src/modules/chain.ts +++ b/src/modules/chain.ts @@ -12,7 +12,7 @@ interface ContractDefinition { address: string; } -type ContractNames = 'warp-controller' | 'warp-resolver' | 'warp-templates' | 'warp-job-account-tracker'; +type ContractNames = 'warp-controller' | 'warp-resolver' | 'warp-templates' | 'warp-account-tracker'; type NetworkConfig = { [contract in ContractNames]: ContractDefinition; @@ -166,7 +166,7 @@ export class ChainModule { controller: contractsConfig['warp-controller'].address, resolver: contractsConfig['warp-resolver'].address, templates: contractsConfig['warp-templates'].address, - jobAccountTracker: contractsConfig['warp-job-account-tracker'].address, + jobAccountTracker: contractsConfig['warp-account-tracker'].address, }; } @@ -247,7 +247,7 @@ export class ChainModule { case 'templates': return contractDefs['warp-templates'].address; case 'jobAccountTracker': - return contractDefs['warp-job-account-tracker'].address; + return contractDefs['warp-account-tracker'].address; } } } diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 09b6326..5a75d60 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -1,11 +1,5 @@ -import { - warp_controller, - warp_job_account, - warp_legacy_account, - warp_resolver, - warp_templates, -} from '../types/contracts'; -import { base64encode, nativeTokenDenom, Token, TransferMsg, TransferNftMsg } from '../utils'; +import { warp_controller, warp_account, warp_resolver, warp_templates } from '../types/contracts'; +import { nativeTokenDenom, TransferMsg, TransferNftMsg } from '../utils'; import { Coins, CreateTxOptions } from '@terra-money/feather.js'; import { TxBuilder } from '../tx'; import { JobSequenceMsgComposer } from '../composers'; @@ -286,56 +280,15 @@ export class TxModule { return txBuilder.build(); } - public async legacyDepositToAccount( - sender: string, - account: string, - token: Token, - amount: string - ): Promise { - let txPayload: CreateTxOptions; - - if (token.type === 'cw20') { - txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute(sender, token.token, { - transfer: { - amount, - recipient: account, - }, - }) - .build(); - } else { - txPayload = TxBuilder.new(this.warpSdk.chain.config) - .send(sender, account, { [token.denom]: amount }) - .build(); - } - - return txPayload; - } - - public async legacyWithdrawAssets( - sender: string, - msg: warp_legacy_account.WithdrawAssetsMsg - ): Promise { - const { account } = await this.warpSdk.legacyAccount(sender); - - const txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute>(sender, account, { - withdraw_assets: msg, - }) - .build(); - - return txPayload; - } - public async withdrawAssets( sender: string, job_id: string, - msg: warp_job_account.WithdrawAssetsMsg + msg: warp_account.WithdrawAssetsMsg ): Promise { const job = await this.warpSdk.job(job_id); const txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute>(sender, job.account, { + .execute>(sender, job.account, { warp_msgs: { msgs: [{ withdraw_assets: msg }], }, @@ -344,60 +297,4 @@ export class TxModule { return txPayload; } - - public async legacyWithdrawFromAccount( - sender: string, - receiver: string, - token: Token, - amount: string - ): Promise { - const { account } = await this.warpSdk.legacyAccount(sender); - let txPayload: CreateTxOptions; - - if (token.type === 'cw20') { - const transferMsg = { - transfer: { - amount, - recipient: receiver, - }, - }; - - txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute(sender, account, { - generic: { - msgs: [ - { - wasm: { - execute: { - contract_addr: token.token, - msg: base64encode(transferMsg), - funds: [], - }, - }, - }, - ], - }, - }) - .build(); - } else { - txPayload = TxBuilder.new(this.warpSdk.chain.config) - .execute(sender, account, { - generic: { - msgs: [ - { - bank: { - send: { - amount: [{ amount, denom: token.denom }], - to_address: receiver, - }, - }, - }, - ], - }, - }) - .build(); - } - - return txPayload; - } } diff --git a/src/refs.injective.json b/src/refs.injective.json index 4ae7580..4a8b764 100644 --- a/src/refs.injective.json +++ b/src/refs.injective.json @@ -12,7 +12,7 @@ "codeId": "2530", "address": "inj1lqe55634npthzavxd9stfpz0snr5hh0qxhhsgp" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "inj1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } @@ -30,7 +30,7 @@ "codeId": "82", "address": "inj1nxp6uvz0506u32hf438uqy3cqs023k9wq6kxp8" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "inj1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } diff --git a/src/refs.neutron.json b/src/refs.neutron.json index 9451ec2..82ebc02 100644 --- a/src/refs.neutron.json +++ b/src/refs.neutron.json @@ -12,7 +12,7 @@ "codeId": "1475", "address": "neutron1a29vd6lltycyr2cfku0w4km3axeexcxut53t3wx397dw8jndfq4swlxw9d" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "neutron1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } @@ -30,7 +30,7 @@ "codeId": "202", "address": "neutron1hn43q3v92y4dgdgtc5p7g684zx9dn6ejr74gchntdnppsljd89usxqs2s9" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "neutron1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } diff --git a/src/refs.nibiru.json b/src/refs.nibiru.json index 182bf86..f68c82f 100644 --- a/src/refs.nibiru.json +++ b/src/refs.nibiru.json @@ -12,7 +12,7 @@ "codeId": "15", "address": "nibi1cyd63pk2wuvjkqmhlvp9884z4h89rqtn8w8xgz9m28hjd2kzj2cq0q8fv4" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "nibi1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } @@ -30,7 +30,7 @@ "codeId": "15", "address": "nibi1cyd63pk2wuvjkqmhlvp9884z4h89rqtn8w8xgz9m28hjd2kzj2cq0q8fv4" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "nibi1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } diff --git a/src/refs.terra.json b/src/refs.terra.json index bc929c6..e738e36 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,8 +1,5 @@ { "testnet": { - "warp-account": { - "codeId": "9626" - }, "warp-controller": { "codeId": "11634", "address": "terra1fqcfh8vpqsl7l5yjjtq5wwu6sv989txncq5fa756tv7lywqexraq5vnjvt" @@ -15,10 +12,10 @@ "codeId": "9263", "address": "terra17xm2ewyg60y7eypnwav33fwm23hxs3qyd8qk9tnntj4d0rp2vvhsgkpwwp" }, - "warp-job-account": { + "warp-account": { "codeId": "11522" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } @@ -36,7 +33,7 @@ "codeId": "1787", "address": "terra1mcfu3tkd5h9zdwuserl3v6uzetv9xke8wyaaf9vx07p7shk6xlws3styfk" }, - "warp-job-account-tracker": { + "warp-account-tracker": { "codeId": "11630", "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } diff --git a/src/sdk.ts b/src/sdk.ts index 2c9675c..3423e64 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,4 +1,4 @@ -import { warp_legacy_account, warp_controller, warp_resolver, warp_job_account } from './types/contracts'; +import { warp_controller, warp_resolver, warp_account } from './types/contracts'; import { WalletLike, Wallet, wallet } from './wallet'; import { Condition } from './condition'; import { @@ -15,7 +15,7 @@ import { TxModule, ChainModule, ChainName, NetworkName } from './modules'; import { cosmosMsgToCreateTxMsg } from './utils'; import { warp_templates } from './types/contracts/warp_templates'; import { Job, parseJob } from './types/job'; -import { warp_job_account_tracker } from './types/contracts'; +import { warp_account_tracker } from './types/contracts'; const FEE_ADJUSTMENT_FACTOR = 3; @@ -163,59 +163,39 @@ export class WarpSdk { return response; } - public async takenJobAccounts( - msg: warp_job_account_tracker.QueryTakenAccountsMsg - ): Promise { + public async takenAccounts( + msg: warp_account_tracker.QueryTakenAccountsMsg + ): Promise { const response = await contractQuery< - Extract, - warp_job_account_tracker.AccountsResponse + Extract, + warp_account_tracker.AccountsResponse >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_taken_accounts: msg }); return response; } - public async freeJobAccounts( - msg: warp_job_account_tracker.QueryFreeAccountsMsg - ): Promise { + public async freeAccounts( + msg: warp_account_tracker.QueryFreeAccountsMsg + ): Promise { const response = await contractQuery< - Extract, - warp_job_account_tracker.AccountsResponse + Extract, + warp_account_tracker.AccountsResponse >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_free_accounts: msg }); return response; } public async fundingAccounts( - msg: warp_job_account_tracker.QueryFundingAccountsMsg - ): Promise { + msg: warp_account_tracker.QueryFundingAccountsMsg + ): Promise { const response = await contractQuery< - Extract, - warp_job_account_tracker.FundingAccountsResponse + Extract, + warp_account_tracker.FundingAccountsResponse >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_funding_accounts: msg }); return response; } - // Legacy account support - - public async legacyAccount(owner: string): Promise { - const { account } = await contractQuery< - Extract, - warp_controller.LegacyAccountResponse - >(this.wallet.lcd, this.chain.contracts.controller, { query_legacy_account: { owner } }); - - return account; - } - - public async legacyAccounts(opts: warp_controller.QueryLegacyAccountsMsg): Promise { - const { accounts } = await contractQuery< - Extract, - warp_controller.LegacyAccountsResponse - >(this.wallet.lcd, this.chain.contracts.controller, { query_legacy_accounts: opts }); - - return accounts; - } - public async config(): Promise { const { config: controllerConfig } = await contractQuery< Extract, @@ -274,8 +254,8 @@ export class WarpSdk { ): Promise { // const account = await this.account(sender); // TODO: check if this works, as before first job is created, no account is assigned to free job accounts - const response = await this.freeJobAccounts({ account_owner_addr: sender }); - const account = response.accounts[0].addr; + const response = await this.freeAccounts({ account_owner_addr: sender }); + const account = response.accounts.length === 0 ? sender : response.accounts[0].addr; const hydratedVars = await this.hydrateVars({ vars: estimateJobMsg.vars }); @@ -438,38 +418,9 @@ export class WarpSdk { return this.wallet.tx(txPayload); } - public async withdrawAssets( - sender: string, - job_id: string, - msg: warp_job_account.WithdrawAssetsMsg - ): Promise { + public async withdrawAssets(sender: string, job_id: string, msg: warp_account.WithdrawAssetsMsg): Promise { const txPayload = await this.tx.withdrawAssets(sender, job_id, msg); return this.wallet.tx(txPayload); } - - // legacy account support - - public async legacyWithdrawAssets(sender: string, msg: warp_legacy_account.WithdrawAssetsMsg): Promise { - const txPayload = await this.tx.legacyWithdrawAssets(sender, msg); - - return this.wallet.tx(txPayload); - } - - public async legacyDepositToAccount(sender: string, account: string, token: Token, amount: string): Promise { - const txPayload = await this.tx.legacyDepositToAccount(sender, account, token, amount); - - return this.wallet.tx(txPayload); - } - - public async legacyWithdrawFromAccount( - sender: string, - receiver: string, - token: Token, - amount: string - ): Promise { - const txPayload = await this.tx.legacyWithdrawFromAccount(sender, receiver, token, amount); - - return this.wallet.tx(txPayload); - } } diff --git a/src/types/contracts/index.ts b/src/types/contracts/index.ts index 50150a5..f26b7a7 100644 --- a/src/types/contracts/index.ts +++ b/src/types/contracts/index.ts @@ -1,6 +1,5 @@ +export * from './warp_account'; +export * from './warp_account_tracker'; export * from './warp_controller'; -export * from './warp_job_account'; -export * from './warp_job_account_tracker'; -export * from './warp_legacy_account'; export * from './warp_resolver'; export * from './warp_templates'; diff --git a/src/types/contracts/warp_job_account.ts b/src/types/contracts/warp_account.ts similarity index 99% rename from src/types/contracts/warp_job_account.ts rename to src/types/contracts/warp_account.ts index f7d939a..55b090e 100644 --- a/src/types/contracts/warp_job_account.ts +++ b/src/types/contracts/warp_account.ts @@ -1,4 +1,4 @@ -export module warp_job_account { +export module warp_account { export type Addr = string; export interface Config { creator_addr: Addr; @@ -7,6 +7,7 @@ export module warp_job_account { export type ExecuteMsg = { warp_msgs: WarpMsgs; }; + export type Uint64 = string; export type WarpMsg = | { generic: CosmosMsgFor_Empty; @@ -133,7 +134,6 @@ export module warp_job_account { }; }; export type Timestamp = Uint64; - export type Uint64 = string; export type WasmMsg = | { execute: { @@ -211,6 +211,7 @@ export module warp_job_account { cw721: [Addr, string]; }; export interface WarpMsgs { + job_id?: Uint64 | null; msgs: WarpMsg[]; } export interface Coin { diff --git a/src/types/contracts/warp_job_account_tracker.ts b/src/types/contracts/warp_account_tracker.ts similarity index 94% rename from src/types/contracts/warp_job_account_tracker.ts rename to src/types/contracts/warp_account_tracker.ts index 4436110..b4fe8a9 100644 --- a/src/types/contracts/warp_job_account_tracker.ts +++ b/src/types/contracts/warp_account_tracker.ts @@ -1,4 +1,4 @@ -export module warp_job_account_tracker { +export module warp_account_tracker { export type Addr = string; export type Uint64 = string; export interface Account { @@ -86,9 +86,6 @@ export module warp_job_account_tracker { | { query_first_free_account: QueryFirstFreeAccountMsg; } - | { - query_free_account: QueryFreeAccountMsg; - } | { query_first_free_funding_account: QueryFirstFreeFundingAccountMsg; } @@ -112,9 +109,6 @@ export module warp_job_account_tracker { export interface QueryFirstFreeAccountMsg { account_owner_addr: string; } - export interface QueryFreeAccountMsg { - account_addr: string; - } export interface QueryFirstFreeFundingAccountMsg { account_owner_addr: string; } diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 8d850e4..07c2fcc 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -1,10 +1,11 @@ export module warp_controller { export type Uint128 = string; - export type Uint64 = string; export type Addr = string; + export type Uint64 = string; export interface Config { a_max: Uint128; a_min: Uint128; + account_tracker_address: Addr; burn_fee_min: Uint128; burn_fee_rate: Uint128; cancellation_fee_percentage: Uint64; @@ -15,7 +16,6 @@ export module warp_controller { duration_days_right: Uint64; fee_collector: Addr; fee_denom: string; - job_account_tracker_address: Addr; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; @@ -51,13 +51,10 @@ export module warp_controller { update_config: UpdateConfigMsg; } | { - migrate_legacy_accounts: MigrateLegacyAccountsMsg; - } - | { - migrate_free_job_accounts: MigrateJobAccountsMsg; + migrate_free_accounts: MigrateAccountsMsg; } | { - migrate_taken_job_accounts: MigrateJobAccountsMsg; + migrate_taken_accounts: MigrateAccountsMsg; } | { migrate_pending_jobs: MigrateJobsMsg; @@ -387,16 +384,11 @@ export module warp_controller { t_max?: Uint64 | null; t_min?: Uint64 | null; } - export interface MigrateLegacyAccountsMsg { - limit: number; - start_after?: string | null; - warp_legacy_account_code_id: Uint64; - } - export interface MigrateJobAccountsMsg { + export interface MigrateAccountsMsg { account_owner_addr: string; limit: number; start_after?: string | null; - warp_job_account_code_id: Uint64; + warp_account_code_id: Uint64; } export interface MigrateJobsMsg { limit: number; @@ -406,6 +398,7 @@ export module warp_controller { export interface InstantiateMsg { a_max: Uint128; a_min: Uint128; + account_tracker_code_id: Uint64; burn_fee_min: Uint128; burn_fee_rate: Uint128; cancellation_fee: Uint64; @@ -416,7 +409,6 @@ export module warp_controller { duration_days_right: Uint64; fee_collector?: string | null; fee_denom: string; - job_account_tracker_code_id: Uint64; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; @@ -458,16 +450,6 @@ export module warp_controller { jobs: Job[]; total_count: number; } - export interface LegacyAccountResponse { - account: LegacyAccount; - } - export interface LegacyAccount { - account: Addr; - owner: Addr; - } - export interface LegacyAccountsResponse { - accounts: LegacyAccount[]; - } export type QueryMsg = | { query_job: QueryJobMsg; @@ -475,12 +457,6 @@ export module warp_controller { | { query_jobs: QueryJobsMsg; } - | { - query_legacy_account: QueryLegacyAccountMsg; - } - | { - query_legacy_accounts: QueryLegacyAccountsMsg; - } | { query_config: QueryConfigMsg; } @@ -504,13 +480,6 @@ export module warp_controller { _0: Uint128; _1: Uint64; } - export interface QueryLegacyAccountMsg { - owner: string; - } - export interface QueryLegacyAccountsMsg { - limit?: number | null; - start_after?: string | null; - } export interface QueryConfigMsg {} export interface QueryStateMsg {} export interface State { diff --git a/src/types/contracts/warp_legacy_account.ts b/src/types/contracts/warp_legacy_account.ts deleted file mode 100644 index 62d99a6..0000000 --- a/src/types/contracts/warp_legacy_account.ts +++ /dev/null @@ -1,274 +0,0 @@ -export module warp_legacy_account { - export type Addr = string; - export interface Config { - owner: Addr; - warp_addr: Addr; - } - export type ExecuteMsg = - | { - generic: GenericMsg; - } - | { - withdraw_assets: WithdrawAssetsMsg; - } - | { - ibc_transfer: IbcTransferMsg; - }; - export type CosmosMsgFor_Empty = - | { - bank: BankMsg; - } - | { - custom: Empty; - } - | { - staking: StakingMsg; - } - | { - distribution: DistributionMsg; - } - | { - stargate: { - type_url: string; - value: Binary; - }; - } - | { - ibc: IbcMsg; - } - | { - wasm: WasmMsg; - } - | { - gov: GovMsg; - }; - export type BankMsg = - | { - send: { - amount: Coin[]; - to_address: string; - }; - } - | { - burn: { - amount: Coin[]; - }; - }; - export type Uint128 = string; - export type StakingMsg = - | { - delegate: { - amount: Coin; - validator: string; - }; - } - | { - undelegate: { - amount: Coin; - validator: string; - }; - } - | { - redelegate: { - amount: Coin; - dst_validator: string; - src_validator: string; - }; - }; - export type DistributionMsg = - | { - set_withdraw_address: { - /** - * The `withdraw_address` - */ - address: string; - }; - } - | { - withdraw_delegator_reward: { - /** - * The `validator_address` - */ - validator: string; - }; - }; - export type Binary = string; - export type IbcMsg = - | { - transfer: { - /** - * packet data only supports one coin https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/ibc/applications/transfer/v1/transfer.proto#L11-L20 - */ - amount: Coin; - /** - * exisiting channel to send the tokens over - */ - channel_id: string; - /** - * when packet times out, measured on remote chain - */ - timeout: IbcTimeout; - /** - * address on the remote chain to receive these tokens - */ - to_address: string; - }; - } - | { - send_packet: { - channel_id: string; - data: Binary; - /** - * when packet times out, measured on remote chain - */ - timeout: IbcTimeout; - }; - } - | { - close_channel: { - channel_id: string; - }; - }; - export type Timestamp = Uint64; - export type Uint64 = string; - export type WasmMsg = - | { - execute: { - contract_addr: string; - funds: Coin[]; - /** - * msg is the json-encoded ExecuteMsg struct (as raw Binary) - */ - msg: Binary; - }; - } - | { - instantiate: { - admin?: string | null; - code_id: number; - funds: Coin[]; - /** - * A human-readbale label for the contract - */ - label: string; - /** - * msg is the JSON-encoded InstantiateMsg struct (as raw Binary) - */ - msg: Binary; - }; - } - | { - migrate: { - contract_addr: string; - /** - * msg is the json-encoded MigrateMsg struct that will be passed to the new code - */ - msg: Binary; - /** - * the code_id of the new logic to place in the given contract - */ - new_code_id: number; - }; - } - | { - update_admin: { - admin: string; - contract_addr: string; - }; - } - | { - clear_admin: { - contract_addr: string; - }; - }; - export type GovMsg = { - vote: { - proposal_id: number; - /** - * The vote option. - * - * This should be called "option" for consistency with Cosmos SDK. Sorry for that. See . - */ - vote: VoteOption; - }; - }; - export type VoteOption = 'yes' | 'no' | 'abstain' | 'no_with_veto'; - export type AssetInfo = - | { - native: string; - } - | { - cw20: Addr; - } - | { - /** - * @minItems 2 - * @maxItems 2 - */ - cw721: [Addr, string]; - }; - export interface GenericMsg { - msgs: CosmosMsgFor_Empty[]; - } - export interface Coin { - amount: Uint128; - denom: string; - } - export interface Empty {} - export interface IbcTimeout { - block?: IbcTimeoutBlock | null; - timestamp?: Timestamp | null; - } - export interface IbcTimeoutBlock { - /** - * block height after which the packet times out. the height within the given revision - */ - height: number; - /** - * the version that the client is currently on (eg. after reseting the chain this could increment 1 as height drops to 0) - */ - revision: number; - } - export interface WithdrawAssetsMsg { - asset_infos: AssetInfo[]; - } - export interface IbcTransferMsg { - timeout_block_delta?: number | null; - timeout_timestamp_seconds_delta?: number | null; - transfer_msg: TransferMsg; - } - export interface TransferMsg { - memo: string; - receiver: string; - sender: string; - source_channel: string; - source_port: string; - timeout_block?: TimeoutBlock | null; - timeout_timestamp?: number | null; - token?: Coin | null; - } - export interface TimeoutBlock { - revision_height?: number | null; - revision_number?: number | null; - } - export type CwFund = - | { - cw20: Cw20Fund; - } - | { - cw721: Cw721Fund; - }; - export interface InstantiateMsg { - funds?: CwFund[] | null; - owner: string; - } - export interface Cw20Fund { - amount: Uint128; - contract_addr: string; - } - export interface Cw721Fund { - contract_addr: string; - token_id: string; - } - export type QueryMsg = 'config'; -} From 0401610b29dbcd533a8aa617ca51dd72532a99f7 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 11 Dec 2023 11:57:20 +0100 Subject: [PATCH 21/44] new contract changes --- src/composers/template.ts | 19 ++-- src/modules/tx.ts | 88 +++++++++++++++++- src/sdk.ts | 18 ++++ src/types/contracts/warp_templates.ts | 124 +++++++------------------- 4 files changed, 143 insertions(+), 106 deletions(-) diff --git a/src/composers/template.ts b/src/composers/template.ts index 97352a1..b1ee3e8 100644 --- a/src/composers/template.ts +++ b/src/composers/template.ts @@ -1,7 +1,7 @@ -import { warp_resolver, warp_templates } from '../types'; +import { Execution, warp_resolver, warp_templates } from '../types'; export class SubmitTemplateMsgComposer { - private _condition: warp_resolver.Condition | undefined; + private _executions: Execution[] = []; private _formattedStr: string = ''; private _msgs: warp_resolver.CosmosMsgFor_Empty[] = []; private _name: string = ''; @@ -11,11 +11,6 @@ export class SubmitTemplateMsgComposer { return new SubmitTemplateMsgComposer(); } - cond(condition: warp_resolver.Condition): SubmitTemplateMsgComposer { - this._condition = condition; - return this; - } - formattedStr(formattedStr: string): SubmitTemplateMsgComposer { this._formattedStr = formattedStr; return this; @@ -31,8 +26,8 @@ export class SubmitTemplateMsgComposer { return this; } - msg(msg: warp_resolver.CosmosMsgFor_Empty): SubmitTemplateMsgComposer { - this._msgs.push(msg); + executions(executions: Execution[]): SubmitTemplateMsgComposer { + this._executions = executions; return this; } @@ -42,9 +37,11 @@ export class SubmitTemplateMsgComposer { } const submitTemplateMsg: warp_templates.SubmitTemplateMsg = { - condition: this._condition, formatted_str: this._formattedStr, - msg: JSON.stringify(this._msgs), + executions: this._executions.map((e) => ({ + condition: JSON.stringify(e.condition), + msgs: JSON.stringify(e.msgs), + })), name: this._name, vars: this._vars, }; diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 5a75d60..006c8fb 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -1,5 +1,5 @@ import { warp_controller, warp_account, warp_resolver, warp_templates } from '../types/contracts'; -import { nativeTokenDenom, TransferMsg, TransferNftMsg } from '../utils'; +import { base64encode, nativeTokenDenom, Token, TransferMsg, TransferNftMsg } from '../utils'; import { Coins, CreateTxOptions } from '@terra-money/feather.js'; import { TxBuilder } from '../tx'; import { JobSequenceMsgComposer } from '../composers'; @@ -297,4 +297,90 @@ export class TxModule { return txPayload; } + + public async depositToAccount( + sender: string, + account: string, + token: Token, + amount: string + ): Promise { + let txPayload: CreateTxOptions; + + if (token.type === 'cw20') { + txPayload = TxBuilder.new(this.warpSdk.chain.config) + .execute(sender, token.token, { + transfer: { + amount, + recipient: account, + }, + }) + .build(); + } else { + txPayload = TxBuilder.new(this.warpSdk.chain.config) + .send(sender, account, { [token.denom]: amount }) + .build(); + } + + return txPayload; + } + + public async withdrawFromAccount( + sender: string, + account: string, + receiver: string, + token: Token, + amount: string + ): Promise { + let txPayload: CreateTxOptions; + + if (token.type === 'cw20') { + const transferMsg = { + transfer: { + amount, + recipient: receiver, + }, + }; + + txPayload = TxBuilder.new(this.warpSdk.chain.config) + .execute(sender, account, { + warp_msgs: { + msgs: [ + { + generic: { + wasm: { + execute: { + contract_addr: token.token, + msg: base64encode(transferMsg), + funds: [], + }, + }, + }, + }, + ], + }, + }) + .build(); + } else { + txPayload = TxBuilder.new(this.warpSdk.chain.config) + .execute(sender, account, { + warp_msgs: { + msgs: [ + { + generic: { + bank: { + send: { + amount: [{ amount, denom: token.denom }], + to_address: receiver, + }, + }, + }, + }, + ], + }, + }) + .build(); + } + + return txPayload; + } } diff --git a/src/sdk.ts b/src/sdk.ts index 3423e64..e5280f2 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -423,4 +423,22 @@ export class WarpSdk { return this.wallet.tx(txPayload); } + + public async depositToAccount(sender: string, account: string, token: Token, amount: string): Promise { + const txPayload = await this.tx.depositToAccount(sender, account, token, amount); + + return this.wallet.tx(txPayload); + } + + public async withdrawFromAccount( + sender: string, + account: string, + receiver: string, + token: Token, + amount: string + ): Promise { + const txPayload = await this.tx.withdrawFromAccount(sender, account, receiver, token, amount); + + return this.wallet.tx(txPayload); + } } diff --git a/src/types/contracts/warp_templates.ts b/src/types/contracts/warp_templates.ts index 3b6a701..9c848c7 100644 --- a/src/types/contracts/warp_templates.ts +++ b/src/types/contracts/warp_templates.ts @@ -23,53 +23,38 @@ export module warp_templates { | { update_config: UpdateConfigMsg; }; - export type Condition = - | { - and: Condition[]; - } + export type Variable = | { - or: Condition[]; + static: StaticVariable; } | { - not: Condition; + external: ExternalVariable; } | { - expr: Expr; + query: QueryVariable; }; - export type Expr = - | { - string: GenExprFor_StringValueFor_StringAnd_StringOp; - } + export type FnValue = | { - uint: GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp; + uint: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; } | { - int: GenExprFor_NumValueForInt128And_NumExprOpAnd_IntFnOpAnd_NumOp; + int: NumValueForInt128And_NumExprOpAnd_IntFnOp; } | { - decimal: GenExprFor_NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOpAnd_NumOp; + decimal: NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp; } | { - timestamp: TimeExpr; + timestamp: NumValueForInt128And_NumExprOpAnd_IntFnOp; } | { - block_height: BlockExpr; + block_height: NumValueForInt128And_NumExprOpAnd_IntFnOp; } | { bool: string; - }; - export type StringValueFor_String = - | { - simple: string; - } - | { - ref: string; } | { - env: StringEnvValue; + string: StringValueFor_String; }; - export type StringEnvValue = 'warp_account_addr'; - export type StringOp = 'starts_with' | 'ends_with' | 'contains' | 'eq' | 'neq'; export type NumValueFor_Uint256And_NumExprOpAnd_IntFnOp = | { simple: Uint256; @@ -90,7 +75,6 @@ export module warp_templates { export type NumExprOp = 'add' | 'sub' | 'div' | 'mul' | 'mod'; export type IntFnOp = 'abs' | 'neg'; export type NumEnvValue = 'time' | 'block_height'; - export type NumOp = 'eq' | 'neq' | 'lt' | 'gt' | 'gte' | 'lte'; export type NumValueForInt128And_NumExprOpAnd_IntFnOp = | { simple: number; @@ -125,40 +109,17 @@ export module warp_templates { }; export type Decimal256 = string; export type DecimalFnOp = 'abs' | 'neg' | 'floor' | 'sqrt' | 'ceil'; - export type Uint64 = string; - export type TimeOp = 'lt' | 'gt'; - export type Variable = - | { - static: StaticVariable; - } - | { - external: ExternalVariable; - } - | { - query: QueryVariable; - }; - export type FnValue = - | { - uint: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; - } - | { - int: NumValueForInt128And_NumExprOpAnd_IntFnOp; - } - | { - decimal: NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp; - } - | { - timestamp: NumValueForInt128And_NumExprOpAnd_IntFnOp; - } + export type StringValueFor_String = | { - block_height: NumValueForInt128And_NumExprOpAnd_IntFnOp; + simple: string; } | { - bool: string; + ref: string; } | { - string: StringValueFor_String; + env: StringEnvValue; }; + export type StringEnvValue = 'warp_account_addr'; export type VariableKind = 'string' | 'uint' | 'int' | 'decimal' | 'timestamp' | 'bool' | 'amount' | 'asset' | 'json'; export type Method = 'get' | 'post' | 'put' | 'patch' | 'delete'; export type QueryRequestFor_String = @@ -267,22 +228,25 @@ export module warp_templates { contract_addr: string; }; }; + export type Uint64 = string; export interface SubmitTemplateMsg { - condition?: Condition | null; + executions: Execution[]; formatted_str: string; - msg: string; name: string; vars: Variable[]; } - export interface GenExprFor_StringValueFor_StringAnd_StringOp { - left: StringValueFor_String; - op: StringOp; - right: StringValueFor_String; + export interface Execution { + condition: string; + msgs: string; } - export interface GenExprFor_NumValueFor_Uint256And_NumExprOpAnd_IntFnOpAnd_NumOp { - left: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; - op: NumOp; - right: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; + export interface StaticVariable { + encode: boolean; + init_fn: FnValue; + kind: VariableKind; + name: string; + reinitialize: boolean; + update_fn?: UpdateFn | null; + value?: string | null; } export interface NumExprValueFor_Uint256And_NumExprOpAnd_IntFnOp { left: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; @@ -293,11 +257,6 @@ export module warp_templates { op: IntFnOp; right: NumValueFor_Uint256And_NumExprOpAnd_IntFnOp; } - export interface GenExprFor_NumValueForInt128And_NumExprOpAnd_IntFnOpAnd_NumOp { - left: NumValueForInt128And_NumExprOpAnd_IntFnOp; - op: NumOp; - right: NumValueForInt128And_NumExprOpAnd_IntFnOp; - } export interface NumExprValueForInt128And_NumExprOpAnd_IntFnOp { left: NumValueForInt128And_NumExprOpAnd_IntFnOp; op: NumExprOp; @@ -307,11 +266,6 @@ export module warp_templates { op: IntFnOp; right: NumValueForInt128And_NumExprOpAnd_IntFnOp; } - export interface GenExprFor_NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOpAnd_NumOp { - left: NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp; - op: NumOp; - right: NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp; - } export interface NumExprValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp { left: NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp; op: NumExprOp; @@ -321,23 +275,6 @@ export module warp_templates { op: DecimalFnOp; right: NumValueFor_Decimal256And_NumExprOpAnd_DecimalFnOp; } - export interface TimeExpr { - comparator: Uint64; - op: TimeOp; - } - export interface BlockExpr { - comparator: Uint64; - op: NumOp; - } - export interface StaticVariable { - encode: boolean; - init_fn: FnValue; - kind: VariableKind; - name: string; - reinitialize: boolean; - update_fn?: UpdateFn | null; - value?: string | null; - } export interface UpdateFn { on_error?: FnValue | null; on_success?: FnValue | null; @@ -393,10 +330,9 @@ export module warp_templates { templates: Template[]; } export interface Template { - condition?: Condition | null; + executions: Execution[]; formatted_str: string; id: Uint64; - msg: string; name: string; owner: Addr; vars: Variable[]; From 9bfacfeebf9569deb5c175fcda14f353d298d645 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 11 Dec 2023 12:10:59 +0100 Subject: [PATCH 22/44] new terra refs --- src/refs.terra.json | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/refs.terra.json b/src/refs.terra.json index e738e36..037d8ee 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,23 +1,22 @@ { "testnet": { + "warp-account": { + "codeId": "12318" + }, "warp-controller": { - "codeId": "11634", - "address": "terra1fqcfh8vpqsl7l5yjjtq5wwu6sv989txncq5fa756tv7lywqexraq5vnjvt" + "codeId": "12321", + "address": "terra1sylnrt9rkv7lraqvxssdzwmhm804qjtlp8ssjc502538ykyhdn5sns9edd" }, "warp-resolver": { - "codeId": "11521", - "address": "terra1lxfx6n792aw3hg47tchmyuhv5t30f334gus67pc250qx5zljadws65elnf" + "codeId": "12319", + "address": "terra1yr249ds5f24u72cnyspdu0vghlkxyfanjj5kyagx9q4fm6nlsads89f9l7" }, "warp-templates": { - "codeId": "9263", - "address": "terra17xm2ewyg60y7eypnwav33fwm23hxs3qyd8qk9tnntj4d0rp2vvhsgkpwwp" - }, - "warp-account": { - "codeId": "11522" + "codeId": "12320", + "address": "terra1g8v5syvvfcsdlwd5yyguujlsf6vnadhdxghmnwu3ah6q8m7vn0jq0hcgwt" }, "warp-account-tracker": { - "codeId": "11630", - "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" + "codeId": "12322" } }, "mainnet": { From 8f682c4ecbc8a139cc8dd810f8077e85c386ddbc Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 11 Dec 2023 12:13:16 +0100 Subject: [PATCH 23/44] minor refactor --- src/modules/chain.ts | 6 +++--- src/refs.terra.json | 5 +++-- src/sdk.ts | 6 +++--- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/modules/chain.ts b/src/modules/chain.ts index cb4aad3..c440ad2 100644 --- a/src/modules/chain.ts +++ b/src/modules/chain.ts @@ -148,7 +148,7 @@ export interface ContractAddresses { controller: string; resolver: string; templates: string; - jobAccountTracker: string; + accountTracker: string; } export class ChainModule { @@ -166,7 +166,7 @@ export class ChainModule { controller: contractsConfig['warp-controller'].address, resolver: contractsConfig['warp-resolver'].address, templates: contractsConfig['warp-templates'].address, - jobAccountTracker: contractsConfig['warp-account-tracker'].address, + accountTracker: contractsConfig['warp-account-tracker'].address, }; } @@ -246,7 +246,7 @@ export class ChainModule { return contractDefs['warp-resolver'].address; case 'templates': return contractDefs['warp-templates'].address; - case 'jobAccountTracker': + case 'accountTracker': return contractDefs['warp-account-tracker'].address; } } diff --git a/src/refs.terra.json b/src/refs.terra.json index 037d8ee..0d0086e 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -16,7 +16,8 @@ "address": "terra1g8v5syvvfcsdlwd5yyguujlsf6vnadhdxghmnwu3ah6q8m7vn0jq0hcgwt" }, "warp-account-tracker": { - "codeId": "12322" + "codeId": "12322", + "address": "terra1lhxshdp748xs56v83rsegwpmyuqxf2uszdr3wuazjrfq2wza2kyslq800h" } }, "mainnet": { @@ -37,4 +38,4 @@ "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" } } -} \ No newline at end of file +} diff --git a/src/sdk.ts b/src/sdk.ts index e5280f2..3156d66 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -169,7 +169,7 @@ export class WarpSdk { const response = await contractQuery< Extract, warp_account_tracker.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_taken_accounts: msg }); + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_taken_accounts: msg }); return response; } @@ -180,7 +180,7 @@ export class WarpSdk { const response = await contractQuery< Extract, warp_account_tracker.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_free_accounts: msg }); + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_free_accounts: msg }); return response; } @@ -191,7 +191,7 @@ export class WarpSdk { const response = await contractQuery< Extract, warp_account_tracker.FundingAccountsResponse - >(this.wallet.lcd, this.chain.contracts.jobAccountTracker, { query_funding_accounts: msg }); + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_funding_accounts: msg }); return response; } From 0a4487cd04d33de46ae32027fe7aa394fb4f4042 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 11 Dec 2023 15:33:36 +0100 Subject: [PATCH 24/44] more sdk apis --- src/sdk.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/sdk.ts b/src/sdk.ts index 3156d66..df499c0 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -185,6 +185,28 @@ export class WarpSdk { return response; } + public async firstFreeAccount( + msg: warp_account_tracker.QueryFirstFreeAccountMsg + ): Promise { + const response = await contractQuery< + Extract, + warp_account_tracker.AccountResponse + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_first_free_account: msg }); + + return response; + } + + public async firstFreeFundingAccount( + msg: warp_account_tracker.QueryFirstFreeAccountMsg + ): Promise { + const response = await contractQuery< + Extract, + warp_account_tracker.FundingAccountResponse + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_first_free_funding_account: msg }); + + return response; + } + public async fundingAccounts( msg: warp_account_tracker.QueryFundingAccountsMsg ): Promise { From 1db7718f7f8a577acebfffa35c09134216fcfee9 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 11 Dec 2023 18:41:58 +0100 Subject: [PATCH 25/44] limit lowest reward estimate to minimum reward --- src/sdk.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/sdk.ts b/src/sdk.ts index df499c0..43d183e 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -255,7 +255,7 @@ export class WarpSdk { const totalFee = jobRewardAmount.add(burnFee).add(creationFee).add(maintenanceFee); - return new Coin(denom, totalFee.toString()); + return new Coin(denom, totalFee.toFixed(0)); } public async estimateJobReward(sender: string, estimateJobMsg: EstimateJobMsg): Promise { @@ -266,6 +266,12 @@ export class WarpSdk { estimatedReward = estimatedReward.add(await this.estimateJobExecutionReward(sender, estimateJobMsg, execution)); } + const config = await this.config(); + + if (Big(config.minimum_reward).gte(estimatedReward.amount.toString())) { + return new Coin(denom, config.minimum_reward); + } + return estimatedReward; } From 1e5f9dab46f989910e6b841a4f270f86d46006cf Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 12 Dec 2023 14:08:55 +0100 Subject: [PATCH 26/44] simulate as sender not account --- src/sdk.ts | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/sdk.ts b/src/sdk.ts index 43d183e..3038f93 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -17,7 +17,7 @@ import { warp_templates } from './types/contracts/warp_templates'; import { Job, parseJob } from './types/job'; import { warp_account_tracker } from './types/contracts'; -const FEE_ADJUSTMENT_FACTOR = 3; +const FEE_ADJUSTMENT_FACTOR = 4; export type EstimateJobMsg = { vars: string; @@ -280,11 +280,6 @@ export class WarpSdk { estimateJobMsg: EstimateJobMsg, execution: warp_controller.Execution ): Promise { - // const account = await this.account(sender); - // TODO: check if this works, as before first job is created, no account is assigned to free job accounts - const response = await this.freeAccounts({ account_owner_addr: sender }); - const account = response.accounts.length === 0 ? sender : response.accounts[0].addr; - const hydratedVars = await this.hydrateVars({ vars: estimateJobMsg.vars }); const hydratedMsgs = await this.hydrateMsgs({ @@ -296,7 +291,7 @@ export class WarpSdk { msgs.push( ...( - await this.tx.executeHydrateVars(account, { + await this.tx.executeHydrateVars(sender, { vars: hydratedVars, }) ).msgs @@ -304,7 +299,7 @@ export class WarpSdk { msgs.push( ...( - await this.tx.executeHydrateMsgs(account, { + await this.tx.executeHydrateMsgs(sender, { vars: hydratedVars, msgs: execution.msgs, }) @@ -313,7 +308,7 @@ export class WarpSdk { msgs.push( ...( - await this.tx.executeResolveCondition(account, { + await this.tx.executeResolveCondition(sender, { condition: execution.condition, vars: hydratedVars, }) @@ -323,7 +318,7 @@ export class WarpSdk { if (estimateJobMsg.recurring) { msgs.push( ...( - await this.tx.executeApplyVarFn(account, { + await this.tx.executeApplyVarFn(sender, { vars: hydratedVars, status: 'Executed', }) @@ -342,9 +337,10 @@ export class WarpSdk { }) .filter(Boolean); - msgs.push(...transformedMsgs.map((msg) => cosmosMsgToCreateTxMsg(account, msg))); + // works only for cosmos msgs + msgs.push(...transformedMsgs.map((msg) => cosmosMsgToCreateTxMsg(sender, msg))); - const accountInfo = await this.wallet.lcd.auth.accountInfo(account); + const accountInfo = await this.wallet.lcd.auth.accountInfo(sender); const fee = await this.wallet.lcd.tx.estimateFee( [ From 953fb408bc2e16acd58db9a34bd5239f1aebd403 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 12 Dec 2023 14:53:28 +0100 Subject: [PATCH 27/44] new contract types --- src/sdk.ts | 26 ++--- src/types/contracts/warp_account_tracker.ts | 20 ++-- src/types/contracts/warp_controller.ts | 4 +- src/types/contracts/warp_resolver.ts | 101 +++++++++++--------- 4 files changed, 79 insertions(+), 72 deletions(-) diff --git a/src/sdk.ts b/src/sdk.ts index 3038f93..044561f 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -163,41 +163,41 @@ export class WarpSdk { return response; } - public async takenAccounts( - msg: warp_account_tracker.QueryTakenAccountsMsg + public async takenJobAccounts( + msg: warp_account_tracker.QueryTakenJobAccountsMsg ): Promise { const response = await contractQuery< - Extract, + Extract, warp_account_tracker.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_taken_accounts: msg }); + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_taken_job_accounts: msg }); return response; } - public async freeAccounts( - msg: warp_account_tracker.QueryFreeAccountsMsg + public async freeJobAccounts( + msg: warp_account_tracker.QueryFreeJobAccountsMsg ): Promise { const response = await contractQuery< - Extract, + Extract, warp_account_tracker.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_free_accounts: msg }); + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_free_job_accounts: msg }); return response; } - public async firstFreeAccount( - msg: warp_account_tracker.QueryFirstFreeAccountMsg + public async firstFreeJobAccount( + msg: warp_account_tracker.QueryFirstFreeJobAccountMsg ): Promise { const response = await contractQuery< - Extract, + Extract, warp_account_tracker.AccountResponse - >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_first_free_account: msg }); + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_first_free_job_account: msg }); return response; } public async firstFreeFundingAccount( - msg: warp_account_tracker.QueryFirstFreeAccountMsg + msg: warp_account_tracker.QueryFirstFreeJobAccountMsg ): Promise { const response = await contractQuery< Extract, diff --git a/src/types/contracts/warp_account_tracker.ts b/src/types/contracts/warp_account_tracker.ts index b4fe8a9..de6bbf5 100644 --- a/src/types/contracts/warp_account_tracker.ts +++ b/src/types/contracts/warp_account_tracker.ts @@ -21,10 +21,10 @@ export module warp_account_tracker { } export type ExecuteMsg = | { - take_account: TakeAccountMsg; + take_job_account: TakeJobAccountMsg; } | { - free_account: FreeAccountMsg; + free_job_account: FreeJobAccountMsg; } | { take_funding_account: TakeFundingAccountMsg; @@ -35,12 +35,12 @@ export module warp_account_tracker { | { add_funding_account: AddFundingAccountMsg; }; - export interface TakeAccountMsg { + export interface TakeJobAccountMsg { account_addr: string; account_owner_addr: string; job_id: Uint64; } - export interface FreeAccountMsg { + export interface FreeJobAccountMsg { account_addr: string; account_owner_addr: string; last_job_id: Uint64; @@ -78,13 +78,13 @@ export module warp_account_tracker { query_config: QueryConfigMsg; } | { - query_taken_accounts: QueryTakenAccountsMsg; + query_taken_job_accounts: QueryTakenJobAccountsMsg; } | { - query_free_accounts: QueryFreeAccountsMsg; + query_free_job_accounts: QueryFreeJobAccountsMsg; } | { - query_first_free_account: QueryFirstFreeAccountMsg; + query_first_free_job_account: QueryFirstFreeJobAccountMsg; } | { query_first_free_funding_account: QueryFirstFreeFundingAccountMsg; @@ -96,17 +96,17 @@ export module warp_account_tracker { query_funding_account: QueryFundingAccountMsg; }; export interface QueryConfigMsg {} - export interface QueryTakenAccountsMsg { + export interface QueryTakenJobAccountsMsg { account_owner_addr: string; limit?: number | null; start_after?: string | null; } - export interface QueryFreeAccountsMsg { + export interface QueryFreeJobAccountsMsg { account_owner_addr: string; limit?: number | null; start_after?: string | null; } - export interface QueryFirstFreeAccountMsg { + export interface QueryFirstFreeJobAccountMsg { account_owner_addr: string; } export interface QueryFirstFreeFundingAccountMsg { diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 07c2fcc..8fe4d6d 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -51,10 +51,10 @@ export module warp_controller { update_config: UpdateConfigMsg; } | { - migrate_free_accounts: MigrateAccountsMsg; + migrate_free_job_accounts: MigrateAccountsMsg; } | { - migrate_taken_accounts: MigrateAccountsMsg; + migrate_taken_job_accounts: MigrateAccountsMsg; } | { migrate_pending_jobs: MigrateJobsMsg; diff --git a/src/types/contracts/warp_resolver.ts b/src/types/contracts/warp_resolver.ts index 395268c..0ca7ced 100644 --- a/src/types/contracts/warp_resolver.ts +++ b/src/types/contracts/warp_resolver.ts @@ -386,6 +386,9 @@ export module warp_resolver { } | { execute_hydrate_msgs: ExecuteHydrateMsgsMsg; + } + | { + warp_msgs_to_cosmos_msgs: WarpMsgsToCosmosMsgsMsg; }; export type QueryRequestFor_String = | { @@ -493,6 +496,31 @@ export module warp_resolver { }; }; export type JobStatus = 'Pending' | 'Executed' | 'Failed' | 'Cancelled' | 'Evicted'; + export type WarpMsg = + | { + generic: CosmosMsgFor_Empty; + } + | { + ibc_transfer: IbcTransferMsg; + } + | { + withdraw_assets: WithdrawAssetsMsg; + }; + export type AssetInfo = + | { + native: string; + } + | { + cw20: Addr; + } + | { + /** + * @minItems 2 + * @maxItems 2 + */ + cw721: [Addr, string]; + }; + export type Addr = string; export interface ExecuteSimulateQueryMsg { query: QueryRequestFor_String; } @@ -528,6 +556,32 @@ export module warp_resolver { msgs: string; vars: string; } + export interface WarpMsgsToCosmosMsgsMsg { + msgs: WarpMsg[]; + owner: Addr; + } + export interface IbcTransferMsg { + timeout_block_delta?: number | null; + timeout_timestamp_seconds_delta?: number | null; + transfer_msg: TransferMsg; + } + export interface TransferMsg { + memo: string; + receiver: string; + sender: string; + source_channel: string; + source_port: string; + timeout_block?: TimeoutBlock | null; + timeout_timestamp?: number | null; + token?: Coin | null; + } + export interface TimeoutBlock { + revision_height?: number | null; + revision_number?: number | null; + } + export interface WithdrawAssetsMsg { + asset_infos: AssetInfo[]; + } export interface InstantiateMsg {} export type QueryMsg = | { @@ -656,51 +710,4 @@ export module warp_resolver { query: QueryRequestFor_String; selector: string; } - export type WarpMsg = - | { - generic: CosmosMsgFor_Empty; - } - | { - ibc_transfer: IbcTransferMsg; - } - | { - withdraw_assets: WithdrawAssetsMsg; - }; - export type AssetInfo = - | { - native: string; - } - | { - cw20: Addr; - } - | { - /** - * @minItems 2 - * @maxItems 2 - */ - cw721: [Addr, string]; - }; - export type Addr = string; - export interface IbcTransferMsg { - timeout_block_delta?: number | null; - timeout_timestamp_seconds_delta?: number | null; - transfer_msg: TransferMsg; - } - export interface TransferMsg { - memo: string; - receiver: string; - sender: string; - source_channel: string; - source_port: string; - timeout_block?: TimeoutBlock | null; - timeout_timestamp?: number | null; - token?: Coin | null; - } - export interface TimeoutBlock { - revision_height?: number | null; - revision_number?: number | null; - } - export interface WithdrawAssetsMsg { - asset_infos: AssetInfo[]; - } } From 2c6f2f39d54df5b2a3f0f94092b20ee6fc15f801 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 12 Dec 2023 22:54:18 +0100 Subject: [PATCH 28/44] new contracts code --- src/sdk.ts | 27 +++------ src/types/contracts/warp_account_tracker.ts | 61 +++++++++++++-------- src/types/contracts/warp_controller.ts | 5 +- 3 files changed, 48 insertions(+), 45 deletions(-) diff --git a/src/sdk.ts b/src/sdk.ts index 044561f..e174950 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -163,34 +163,23 @@ export class WarpSdk { return response; } - public async takenJobAccounts( - msg: warp_account_tracker.QueryTakenJobAccountsMsg - ): Promise { + public async jobAccounts( + msg: warp_account_tracker.QueryJobAccountsMsg + ): Promise { const response = await contractQuery< - Extract, - warp_account_tracker.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_taken_job_accounts: msg }); - - return response; - } - - public async freeJobAccounts( - msg: warp_account_tracker.QueryFreeJobAccountsMsg - ): Promise { - const response = await contractQuery< - Extract, - warp_account_tracker.AccountsResponse - >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_free_job_accounts: msg }); + Extract, + warp_account_tracker.JobAccountsResponse + >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_job_accounts: msg }); return response; } public async firstFreeJobAccount( msg: warp_account_tracker.QueryFirstFreeJobAccountMsg - ): Promise { + ): Promise { const response = await contractQuery< Extract, - warp_account_tracker.AccountResponse + warp_account_tracker.JobAccountResponse >(this.wallet.lcd, this.chain.contracts.accountTracker, { query_first_free_job_account: msg }); return response; diff --git a/src/types/contracts/warp_account_tracker.ts b/src/types/contracts/warp_account_tracker.ts index de6bbf5..00fd8a3 100644 --- a/src/types/contracts/warp_account_tracker.ts +++ b/src/types/contracts/warp_account_tracker.ts @@ -1,16 +1,13 @@ export module warp_account_tracker { export type Addr = string; - export type Uint64 = string; + export type AccountType = 'funding' | 'job'; export interface Account { - addr: Addr; - taken_by_job_id?: Uint64 | null; - } - export interface AccountResponse { - account?: Account | null; + account_addr: Addr; + account_type: AccountType; + owner_addr: Addr; } export interface AccountsResponse { accounts: Account[]; - total_count: number; } export interface Config { admin: Addr; @@ -31,10 +28,8 @@ export module warp_account_tracker { } | { free_funding_account: FreeFundingAccountMsg; - } - | { - add_funding_account: AddFundingAccountMsg; }; + export type Uint64 = string; export interface TakeJobAccountMsg { account_addr: string; account_owner_addr: string; @@ -55,68 +50,90 @@ export module warp_account_tracker { account_owner_addr: string; job_id: Uint64; } - export interface AddFundingAccountMsg { - account_addr: string; - account_owner_addr: string; - } + export type AccountStatus = 'free' | 'taken'; export interface FundingAccountResponse { funding_account?: FundingAccount | null; } export interface FundingAccount { account_addr: Addr; + account_status: AccountStatus; taken_by_job_ids: Uint64[]; } export interface FundingAccountsResponse { funding_accounts: FundingAccount[]; + total_count: number; } export interface InstantiateMsg { admin: string; warp_addr: string; } + export interface JobAccountResponse { + job_account?: JobAccount | null; + } + export interface JobAccount { + account_addr: Addr; + account_status: AccountStatus; + taken_by_job_id: Uint64; + } + export interface JobAccountsResponse { + job_accounts: JobAccount[]; + total_count: number; + } export type QueryMsg = | { query_config: QueryConfigMsg; } | { - query_taken_job_accounts: QueryTakenJobAccountsMsg; + query_accounts: QueryAccountsMsg; } | { - query_free_job_accounts: QueryFreeJobAccountsMsg; + query_job_accounts: QueryJobAccountsMsg; } | { - query_first_free_job_account: QueryFirstFreeJobAccountMsg; + query_job_account: QueryJobAccountMsg; } | { - query_first_free_funding_account: QueryFirstFreeFundingAccountMsg; + query_first_free_job_account: QueryFirstFreeJobAccountMsg; } | { query_funding_accounts: QueryFundingAccountsMsg; } | { query_funding_account: QueryFundingAccountMsg; + } + | { + query_first_free_funding_account: QueryFirstFreeFundingAccountMsg; }; export interface QueryConfigMsg {} - export interface QueryTakenJobAccountsMsg { + export interface QueryAccountsMsg { account_owner_addr: string; limit?: number | null; start_after?: string | null; } - export interface QueryFreeJobAccountsMsg { + export interface QueryJobAccountsMsg { account_owner_addr: string; + account_status: AccountStatus; limit?: number | null; start_after?: string | null; } - export interface QueryFirstFreeJobAccountMsg { + export interface QueryJobAccountMsg { + account_addr: string; account_owner_addr: string; } - export interface QueryFirstFreeFundingAccountMsg { + export interface QueryFirstFreeJobAccountMsg { account_owner_addr: string; } export interface QueryFundingAccountsMsg { account_owner_addr: string; + account_status: AccountStatus; + limit?: number | null; + start_after?: string | null; } export interface QueryFundingAccountMsg { account_addr: string; account_owner_addr: string; } + export interface QueryFirstFreeFundingAccountMsg { + account_owner_addr: string; + } } diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 8fe4d6d..3f99655 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -51,10 +51,7 @@ export module warp_controller { update_config: UpdateConfigMsg; } | { - migrate_free_job_accounts: MigrateAccountsMsg; - } - | { - migrate_taken_job_accounts: MigrateAccountsMsg; + migrate_accounts: MigrateAccountsMsg; } | { migrate_pending_jobs: MigrateJobsMsg; From 47bced2133eb2c2c24d1d5667fb8b230a6a8135f Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 12 Dec 2023 23:02:25 +0100 Subject: [PATCH 29/44] new contracts --- src/refs.terra.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/refs.terra.json b/src/refs.terra.json index 0d0086e..a985c87 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,22 +1,22 @@ { "testnet": { "warp-account": { - "codeId": "12318" + "codeId": "12374" }, "warp-controller": { - "codeId": "12321", - "address": "terra1sylnrt9rkv7lraqvxssdzwmhm804qjtlp8ssjc502538ykyhdn5sns9edd" + "codeId": "12377", + "address": "terra15g0v6w0na27lud72lqm6ks4xup4ypj765ydkl9zfcxde9lpzm4lsns80pk" }, "warp-resolver": { - "codeId": "12319", - "address": "terra1yr249ds5f24u72cnyspdu0vghlkxyfanjj5kyagx9q4fm6nlsads89f9l7" + "codeId": "12375", + "address": "terra1f2ah2ftzagfrcw2wp9l8el7cjtr6n7q55w5l8hvz537wa6nejeuq2rxytl" }, "warp-templates": { - "codeId": "12320", - "address": "terra1g8v5syvvfcsdlwd5yyguujlsf6vnadhdxghmnwu3ah6q8m7vn0jq0hcgwt" + "codeId": "12376", + "address": "terra1w0gn3y7hmshmqp7juxejfh09rll55yr9g32wdc5usrrajfktu7rqed6rpv" }, "warp-account-tracker": { - "codeId": "12322", + "codeId": "12378", "address": "terra1lhxshdp748xs56v83rsegwpmyuqxf2uszdr3wuazjrfq2wza2kyslq800h" } }, From 50b3b24a4a4d0175804127095583210804c12f1d Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 13 Dec 2023 05:20:17 +0100 Subject: [PATCH 30/44] new contracts --- src/refs.terra.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/refs.terra.json b/src/refs.terra.json index a985c87..b48620c 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,22 +1,22 @@ { "testnet": { "warp-account": { - "codeId": "12374" + "codeId": "12384" }, "warp-controller": { - "codeId": "12377", - "address": "terra15g0v6w0na27lud72lqm6ks4xup4ypj765ydkl9zfcxde9lpzm4lsns80pk" + "codeId": "12387", + "address": "terra1h6qvvjkkv2yvr66hkds85esfqm9qe0d7s4svk6hnsj09xdwxxg8q7j7jvu" }, "warp-resolver": { - "codeId": "12375", - "address": "terra1f2ah2ftzagfrcw2wp9l8el7cjtr6n7q55w5l8hvz537wa6nejeuq2rxytl" + "codeId": "12385", + "address": "terra1qfkyljtyvkjccwvxejwhdfaxnkwwt67upnyljwe768dku7lchztqxn94d0" }, "warp-templates": { - "codeId": "12376", - "address": "terra1w0gn3y7hmshmqp7juxejfh09rll55yr9g32wdc5usrrajfktu7rqed6rpv" + "codeId": "12386", + "address": "terra1wergw3euhfxz8qwp3zc2s8ppyarksvw9p3e8mty4yg9ggpzutrds0yn2ku" }, "warp-account-tracker": { - "codeId": "12378", + "codeId": "12388", "address": "terra1lhxshdp748xs56v83rsegwpmyuqxf2uszdr3wuazjrfq2wza2kyslq800h" } }, From 389d902757d2b24d940503f9ce657c6420d0faeb Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 13 Dec 2023 05:21:56 +0100 Subject: [PATCH 31/44] new types --- src/types/contracts/warp_controller.ts | 42 ++++++++------------------ src/utils/fee.ts | 4 +-- 2 files changed, 14 insertions(+), 32 deletions(-) diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 3f99655..28558eb 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -1,31 +1,25 @@ export module warp_controller { - export type Uint128 = string; export type Addr = string; + export type Uint128 = string; export type Uint64 = string; export interface Config { - a_max: Uint128; - a_min: Uint128; account_tracker_address: Addr; burn_fee_min: Uint128; burn_fee_rate: Uint128; - cancellation_fee_percentage: Uint64; + cancellation_fee_rate: Uint64; creation_fee_max: Uint128; creation_fee_min: Uint128; - creation_fee_percentage: Uint64; - duration_days_left: Uint64; - duration_days_right: Uint64; + duration_days_max: Uint64; + duration_days_min: Uint64; fee_collector: Addr; fee_denom: string; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; owner: Addr; - q_max: Uint64; queue_size_left: Uint64; queue_size_right: Uint64; resolver_address: Addr; - t_max: Uint64; - t_min: Uint64; warp_account_code_id: Uint64; } export interface ConfigResponse { @@ -360,26 +354,20 @@ export module warp_controller { id: Uint64; } export interface UpdateConfigMsg { - a_max?: Uint128 | null; - a_min?: Uint128 | null; burn_fee_min?: Uint128 | null; burn_fee_rate?: Uint128 | null; - cancellation_fee_percentage?: Uint64 | null; + cancellation_fee_rate?: Uint64 | null; creation_fee_max?: Uint128 | null; creation_fee_min?: Uint128 | null; - creation_fee_percentage?: Uint64 | null; - duration_days_left?: Uint128 | null; - duration_days_right?: Uint128 | null; + duration_days_max?: Uint64 | null; + duration_days_min?: Uint64 | null; fee_collector?: string | null; maintenance_fee_max?: Uint128 | null; maintenance_fee_min?: Uint128 | null; minimum_reward?: Uint128 | null; owner?: string | null; - q_max?: Uint64 | null; - queue_size_left?: Uint128 | null; - queue_size_right?: Uint128 | null; - t_max?: Uint64 | null; - t_min?: Uint64 | null; + queue_size_left?: Uint64 | null; + queue_size_right?: Uint64 | null; } export interface MigrateAccountsMsg { account_owner_addr: string; @@ -393,29 +381,23 @@ export module warp_controller { } export interface CreateFundingAccountMsg {} export interface InstantiateMsg { - a_max: Uint128; - a_min: Uint128; account_tracker_code_id: Uint64; burn_fee_min: Uint128; burn_fee_rate: Uint128; - cancellation_fee: Uint64; - creation_fee: Uint64; + cancellation_fee_rate: Uint64; creation_fee_max: Uint128; creation_fee_min: Uint128; - duration_days_left: Uint64; - duration_days_right: Uint64; + duration_days_max: Uint64; + duration_days_min: Uint64; fee_collector?: string | null; fee_denom: string; maintenance_fee_max: Uint128; maintenance_fee_min: Uint128; minimum_reward: Uint128; owner?: string | null; - q_max: Uint64; queue_size_left: Uint64; queue_size_right: Uint64; resolver_address: string; - t_max: Uint64; - t_min: Uint64; warp_account_code_id: Uint64; } export type JobStatus = 'Pending' | 'Executed' | 'Failed' | 'Cancelled' | 'Evicted'; diff --git a/src/utils/fee.ts b/src/utils/fee.ts index 74ca8ff..ef48e10 100644 --- a/src/utils/fee.ts +++ b/src/utils/fee.ts @@ -19,9 +19,9 @@ export function computeCreationFee(queueSize: Big, config: warp_controller.Confi } export function computeMaintenanceFee(durationDays: Big, config: warp_controller.Config): Big { - const x1 = Big(config.duration_days_left); + const x1 = Big(config.duration_days_min); const y1 = Big(config.maintenance_fee_min); - const x2 = Big(config.duration_days_right); + const x2 = Big(config.duration_days_max); const y2 = Big(config.maintenance_fee_max); const slope = y2.minus(y1).div(x2.minus(x1)); From 05dc325df115b94da66df42bdbf02318b268ce1d Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 13 Dec 2023 05:25:12 +0100 Subject: [PATCH 32/44] update account-tracker address --- src/refs.terra.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/refs.terra.json b/src/refs.terra.json index b48620c..8734d5d 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -17,7 +17,7 @@ }, "warp-account-tracker": { "codeId": "12388", - "address": "terra1lhxshdp748xs56v83rsegwpmyuqxf2uszdr3wuazjrfq2wza2kyslq800h" + "address": "terra1dg2wm2ftljtydvmkwf6y2vavtjcz496um22tx548zvvupndv8gws0k9daq" } }, "mainnet": { From c70798124c34403bbeb75fbb273eecd1f6a017f7 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 13 Dec 2023 21:57:18 +0100 Subject: [PATCH 33/44] new contract types --- src/composers/job.ts | 7 +++++++ src/refs.terra.json | 18 +++++++++--------- src/types/contracts/warp_controller.ts | 1 - 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/composers/job.ts b/src/composers/job.ts index df29bbe..3f189f4 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -48,6 +48,7 @@ export class CreateJobMsgComposer { private _vars: warp_resolver.Variable[] = []; private _executions: Execution[] = []; private _durationDays: string; + private _fundingAccount: string; private _operationalAmount: warp_controller.Uint128 | undefined; static new(): CreateJobMsgComposer { @@ -84,6 +85,11 @@ export class CreateJobMsgComposer { return this; } + fundingAccount(fundingAccount: string): CreateJobMsgComposer { + this._fundingAccount = fundingAccount; + return this; + } + operationalAmount(operationalAmount: warp_controller.Uint128): CreateJobMsgComposer { this._operationalAmount = operationalAmount; return this; @@ -130,6 +136,7 @@ export class CreateJobMsgComposer { vars: JSON.stringify(this._vars), assets_to_withdraw: this._assetsToWithdraw, operational_amount: this._operationalAmount, + funding_account: this._fundingAccount, }; return createJobMsg; diff --git a/src/refs.terra.json b/src/refs.terra.json index 8734d5d..c999244 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,23 +1,23 @@ { "testnet": { "warp-account": { - "codeId": "12384" + "codeId": "12397" }, "warp-controller": { - "codeId": "12387", - "address": "terra1h6qvvjkkv2yvr66hkds85esfqm9qe0d7s4svk6hnsj09xdwxxg8q7j7jvu" + "codeId": "12409", + "address": "terra16zlwx7yeugjpzvdw2cs8v7zghssmh95thrwuzjf56u4g6xu0udpqqctnxa" }, "warp-resolver": { - "codeId": "12385", - "address": "terra1qfkyljtyvkjccwvxejwhdfaxnkwwt67upnyljwe768dku7lchztqxn94d0" + "codeId": "12398", + "address": "terra12sm42c7g0733zullajvpczazpgtj4w0ndma3yta38840d3sqg5cswv0drc" }, "warp-templates": { - "codeId": "12386", - "address": "terra1wergw3euhfxz8qwp3zc2s8ppyarksvw9p3e8mty4yg9ggpzutrds0yn2ku" + "codeId": "12399", + "address": "terra1cp3lf3qf5gtmv30stprmrt7ye03j5t6nazhe45rzk6nuz2ka83ks9an6gy" }, "warp-account-tracker": { - "codeId": "12388", - "address": "terra1dg2wm2ftljtydvmkwf6y2vavtjcz496um22tx548zvvupndv8gws0k9daq" + "codeId": "12401", + "address": "terra15evxsh7hxdpwvpd6c6t9hn3q6r6q6pfxq8nz27kpp56nusqfyeuqpc0jjp" } }, "mainnet": { diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 28558eb..00332ac 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -416,7 +416,6 @@ export module warp_controller { labels: string[]; last_update_time: Uint64; name: string; - operational_amount: Uint128; owner: Addr; prev_id?: Uint64 | null; recurring: boolean; From 69e9e06bab5577e069da9211b1f5a4f87dbdc737 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 18 Dec 2023 15:37:56 +0100 Subject: [PATCH 34/44] new testnet contracts --- src/refs.terra.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/refs.terra.json b/src/refs.terra.json index c999244..5658941 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,23 +1,23 @@ { "testnet": { "warp-account": { - "codeId": "12397" + "codeId": "12473" }, "warp-controller": { - "codeId": "12409", - "address": "terra16zlwx7yeugjpzvdw2cs8v7zghssmh95thrwuzjf56u4g6xu0udpqqctnxa" + "codeId": "12476", + "address": "terra1r6crnz2j0zkcclhtzqm74l5n7p3pk27fk3uy4cg3pkr45y3pzjtsg3zzmt" }, "warp-resolver": { - "codeId": "12398", - "address": "terra12sm42c7g0733zullajvpczazpgtj4w0ndma3yta38840d3sqg5cswv0drc" + "codeId": "12474", + "address": "terra1xpewwp0fput9xx8wyk5cglketkke27kgyeykzscafk4sgna4jp5qgzwmmz" }, "warp-templates": { - "codeId": "12399", - "address": "terra1cp3lf3qf5gtmv30stprmrt7ye03j5t6nazhe45rzk6nuz2ka83ks9an6gy" + "codeId": "12475", + "address": "terra1pn6v2jx4m95rdwq3jrjg7dgf3fjv0w506s45jdhskgzc9s5l23dsn2y7pw" }, "warp-account-tracker": { - "codeId": "12401", - "address": "terra15evxsh7hxdpwvpd6c6t9hn3q6r6q6pfxq8nz27kpp56nusqfyeuqpc0jjp" + "codeId": "12477", + "address": "terra1qgexzlztyl49q8at7y6jxjagan8afmkg0aake0z36tq90ckmf2psh39dsy" } }, "mainnet": { From 180088c6dbccf18560baa71fa1fd6bf96acaaf9b Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 29 Jan 2024 16:24:34 +0100 Subject: [PATCH 35/44] minor fix --- src/composers/job.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/composers/job.ts b/src/composers/job.ts index 3f189f4..620ecb8 100644 --- a/src/composers/job.ts +++ b/src/composers/job.ts @@ -85,7 +85,7 @@ export class CreateJobMsgComposer { return this; } - fundingAccount(fundingAccount: string): CreateJobMsgComposer { + fundingAccount(fundingAccount?: string): CreateJobMsgComposer { this._fundingAccount = fundingAccount; return this; } From a6367acc0fb564e999ba3b53382632857a439961 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 29 Jan 2024 16:39:31 +0100 Subject: [PATCH 36/44] new v --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e1841ac..b599929 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/terra-money/warp-sdk/issues" }, "homepage": "https://github.com/terra-money/warp-sdk#readme", - "version": "0.1.62", + "version": "0.1.70-rc1", "scripts": { "clean": "rm -rf dist", "build": "yarn clean && yarn build:node && yarn build:browser", From 383e4998c2e8b29e627040ef1ee89a4c375be925 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Fri, 2 Feb 2024 15:20:59 +0100 Subject: [PATCH 37/44] fix create funding account --- src/modules/tx.ts | 5 +++-- src/sdk.ts | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/modules/tx.ts b/src/modules/tx.ts index 006c8fb..7241094 100644 --- a/src/modules/tx.ts +++ b/src/modules/tx.ts @@ -116,14 +116,15 @@ export class TxModule { .build(); } - public async createFundingAccount(sender: string): Promise { + public async createFundingAccount(sender: string, funds?: Coins.Input): Promise { return TxBuilder.new(this.warpSdk.chain.config) .execute>( sender, this.warpSdk.chain.contracts.controller, { create_funding_account: {}, - } + }, + funds ) .build(); } diff --git a/src/sdk.ts b/src/sdk.ts index e174950..8fa1cc1 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -407,8 +407,8 @@ export class WarpSdk { return this.wallet.tx(txPayload); } - public async createFundingAccount(sender: string): Promise { - const txPayload = await this.tx.createFundingAccount(sender); + public async createFundingAccount(sender: string, funds?: Coins.Input): Promise { + const txPayload = await this.tx.createFundingAccount(sender, funds); return this.wallet.tx(txPayload); } From 56e462d927c41c990571c57d15a995b4d4608492 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Fri, 2 Feb 2024 15:21:12 +0100 Subject: [PATCH 38/44] new testnet contracts --- package.json | 2 +- src/refs.terra.json | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index b599929..31cf513 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/terra-money/warp-sdk/issues" }, "homepage": "https://github.com/terra-money/warp-sdk#readme", - "version": "0.1.70-rc1", + "version": "0.1.71-rc3", "scripts": { "clean": "rm -rf dist", "build": "yarn clean && yarn build:node && yarn build:browser", diff --git a/src/refs.terra.json b/src/refs.terra.json index 5658941..6340584 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -1,23 +1,23 @@ { "testnet": { "warp-account": { - "codeId": "12473" + "codeId": "12858" }, "warp-controller": { - "codeId": "12476", - "address": "terra1r6crnz2j0zkcclhtzqm74l5n7p3pk27fk3uy4cg3pkr45y3pzjtsg3zzmt" + "codeId": "12861", + "address": "terra1mmsl3mxq9n8a6dgye05pn0qlup7r24e2vyjkqgpe32pv3ehjgnes0jz5nc" }, "warp-resolver": { - "codeId": "12474", - "address": "terra1xpewwp0fput9xx8wyk5cglketkke27kgyeykzscafk4sgna4jp5qgzwmmz" + "codeId": "12859", + "address": "terra1kjv3e7v7m03kk8lrjqr2j604vusxrpxadg6xjz89jucladh5m5gqqag8q7" }, "warp-templates": { - "codeId": "12475", - "address": "terra1pn6v2jx4m95rdwq3jrjg7dgf3fjv0w506s45jdhskgzc9s5l23dsn2y7pw" + "codeId": "12860", + "address": "terra155wp5wwvquqzg30r6luu4e9d95p7pexe3xjszhflcsqe5gpayd6smz5w6k" }, "warp-account-tracker": { - "codeId": "12477", - "address": "terra1qgexzlztyl49q8at7y6jxjagan8afmkg0aake0z36tq90ckmf2psh39dsy" + "codeId": "12862", + "address": "terra15yefd9r33wad527jrxphef8r0jr7n4chg4ehgq0lmrwsfsflaajq5ps2jz" } }, "mainnet": { From 130970ac8d12d3a0308a75f3a42904a6a06a9f9c Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 5 Feb 2024 16:52:55 +0100 Subject: [PATCH 39/44] adjust fee factor --- src/sdk.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sdk.ts b/src/sdk.ts index 8fa1cc1..300e75b 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -17,7 +17,7 @@ import { warp_templates } from './types/contracts/warp_templates'; import { Job, parseJob } from './types/job'; import { warp_account_tracker } from './types/contracts'; -const FEE_ADJUSTMENT_FACTOR = 4; +const FEE_ADJUSTMENT_FACTOR = 8; export type EstimateJobMsg = { vars: string; From 5976f6d4226f42c16b8b6cfbbf55fad164310161 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 5 Feb 2024 17:18:19 +0100 Subject: [PATCH 40/44] add duration days adjustment factor --- package.json | 2 +- src/sdk.ts | 11 ++++++++++- src/utils/fee.ts | 10 ++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 31cf513..9447529 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/terra-money/warp-sdk/issues" }, "homepage": "https://github.com/terra-money/warp-sdk#readme", - "version": "0.1.71-rc3", + "version": "0.1.71-rc11", "scripts": { "clean": "rm -rf dist", "build": "yarn clean && yarn build:node && yarn build:browser", diff --git a/src/sdk.ts b/src/sdk.ts index 300e75b..8e893bb 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -8,6 +8,7 @@ import { computeBurnFee, computeCreationFee, computeMaintenanceFee, + calculateDurationDaysAdjustmentFactor, } from './utils'; import { TxInfo, LCDClientConfig, LCDClient, Coins, Coin } from '@terra-money/feather.js'; import Big from 'big.js'; @@ -346,7 +347,15 @@ export class WarpSdk { const denom = await this.nativeTokenDenom(); - return new Coin(denom, Big(fee.amount.get(denom).amount.toString()).mul(FEE_ADJUSTMENT_FACTOR).toString()); + const durationDaysAdjustmentFactor = calculateDurationDaysAdjustmentFactor(Big(estimateJobMsg.duration_days)); + + return new Coin( + denom, + Big(fee.amount.get(denom).amount.toString()) + .mul(FEE_ADJUSTMENT_FACTOR) + .mul(durationDaysAdjustmentFactor) + .toString() + ); } public async nativeTokenDenom(): Promise { diff --git a/src/utils/fee.ts b/src/utils/fee.ts index ef48e10..3cb494d 100644 --- a/src/utils/fee.ts +++ b/src/utils/fee.ts @@ -45,3 +45,13 @@ export function computeBurnFee(jobReward: Big, config: warp_controller.Config): return minFee; } } + +export function calculateDurationDaysAdjustmentFactor(durationDays: Big): Big { + if (durationDays.lte(7)) { + return Big(1); + } else if (durationDays.gte(90)) { + return Big(2); + } + + return Big(1).add(durationDays.sub(7).mul(Big(1).div(83))); +} From 998ebb3309964b4de7cab9fd3f5efb9ff0910d82 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Tue, 13 Feb 2024 18:16:38 +0100 Subject: [PATCH 41/44] new sdk v + fix reward decimals --- package.json | 2 +- src/sdk.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 9447529..0f7f1b2 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/terra-money/warp-sdk/issues" }, "homepage": "https://github.com/terra-money/warp-sdk#readme", - "version": "0.1.71-rc11", + "version": "0.1.71-rc12", "scripts": { "clean": "rm -rf dist", "build": "yarn clean && yarn build:node && yarn build:browser", diff --git a/src/sdk.ts b/src/sdk.ts index 8e893bb..2dcaa50 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -262,7 +262,7 @@ export class WarpSdk { return new Coin(denom, config.minimum_reward); } - return estimatedReward; + return new Coin(denom, estimatedReward.amount.toFixed(0)); } public async estimateJobExecutionReward( From 0f98a4b3727d3e0efa8093cb3087b2fff3e63f98 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Mon, 19 Feb 2024 17:35:52 +0100 Subject: [PATCH 42/44] add readme updates --- README.md | 45 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 7071b83..9f7c31b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # warp-sdk -WarpSdk provides a Typescript API for interacting with warp protocol, the automation protocol for the Cosmos ecosystem. The SDK provides a simple way to interact with the warp protocol's contracts, allowing developers to perform operations such as creating and managing jobs, templates, and accounts. +The Warp SDK provides a Typescript API for interacting with Warp Protocol, the decentralized automation tool for the Cosmos ecosystem. Warp allows developers to create novel features or experiences for their users through cost-efficient, on-chain automation—no smart contract changes necessary. + +The SDK provides a simple way to interact with Warp Protocol's contracts to automatically execute transactions in the future based on any available on-chain data. The trigger for execution is referred to as a condition, and the corresponding job encompasses the executable message. Warp jobs are submitted to a job queue, where participants called keepers monitor the conditions and—once met—execute the pre-signed job message. + +Read on below, check out the [docs](https://docs.warp.money/) for more information, or [get in touch](https://docs.google.com/forms/d/e/1FAIpQLSeYGdWL9tIHC3BP2riYXtT_cyZVDMGKrrSH0JCPCdV3PtZGyg/viewform) with the team to start building with Warp. ## Installation @@ -30,7 +34,7 @@ const lcd = new LCDClient({ 'pisco-1': piscoLcdClientConfig, }); -const wallet = new Wallet(lcd, new MnemonicKey({ mnemonic: '' })); +const wallet = new Wallet(lcd, new MnemonicKey({ mnemonic: '...' })); const sdk = new WarpSdk(wallet, piscoLcdClientConfig); const sender = wallet.key.accAddress(piscoLcdClientConfig.prefix); @@ -46,20 +50,43 @@ const nextExecution = variable const condition = cond.uint(uint.env('time'), 'gt', uint.ref(nextExecution)); +const executions = [ + { + condition, + msgs: [msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })], + }, +]; + +const recurring = true; +const durationDays = '30'; +const vars = [nextExecution]; + +const estimateJobRewardMsg = job + .estimate() + .recurring(recurring) + .durationDays(durationDays) + .vars(vars) + .executions(executions) + .compose(); + +const reward = await sdk.estimateJobReward(sender, estimateJobRewardMsg); + +const operationalAmount = await sdk.estimateJobFee(sender, estimateJobRewardMsg, reward.amount.toString()); + const createJobMsg = job .create() .name('eris-harvest') .description('This job harvests rewards for eris protoocl vaults each day.') .labels([]) - .recurring(true) - .requeueOnEvict(true) - .reward('50000') - .cond(condition) - .var(nextExecution) - .msg(msg.execute('terra10788fkzah89xrdm27zkj5yvhj9x3494lxawzm5qq3vvxcqz2yzaqyd3enk', { harvest: {} })) + .recurring(recurring) + .reward(reward.amount.toString()) + .operationalAmount(operationalAmount.amount.toString()) + .vars(vars) + .durationDays(durationDays) + .executions(executions) .compose(); -sdk.createJob(sender, createJobMsg).then((response) => { +sdk.createJob(sender, createJobMsg, [operationalAmount]).then((response) => { console.log(response); }); From 06f8e2a12355ba7a1aab7f286090240c33cb101e Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 21 Feb 2024 15:37:30 +0100 Subject: [PATCH 43/44] types --- src/types/contracts/warp_account_tracker.ts | 6 ++++++ src/types/contracts/warp_controller.ts | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/types/contracts/warp_account_tracker.ts b/src/types/contracts/warp_account_tracker.ts index 00fd8a3..f52c44a 100644 --- a/src/types/contracts/warp_account_tracker.ts +++ b/src/types/contracts/warp_account_tracker.ts @@ -28,6 +28,9 @@ export module warp_account_tracker { } | { free_funding_account: FreeFundingAccountMsg; + } + | { + update_config: UpdateConfigMsg; }; export type Uint64 = string; export interface TakeJobAccountMsg { @@ -50,6 +53,9 @@ export module warp_account_tracker { account_owner_addr: string; job_id: Uint64; } + export interface UpdateConfigMsg { + admin?: string | null; + } export type AccountStatus = 'free' | 'taken'; export interface FundingAccountResponse { funding_account?: FundingAccount | null; diff --git a/src/types/contracts/warp_controller.ts b/src/types/contracts/warp_controller.ts index 80e6ff9..16b1b84 100644 --- a/src/types/contracts/warp_controller.ts +++ b/src/types/contracts/warp_controller.ts @@ -9,6 +9,7 @@ export module warp_controller { cancellation_fee_rate: Uint64; creation_fee_max: Uint128; creation_fee_min: Uint128; + duration_days_limit: Uint64; duration_days_max: Uint64; duration_days_min: Uint64; fee_collector: Addr; @@ -52,6 +53,9 @@ export module warp_controller { } | { migrate_finished_jobs: MigrateJobsMsg; + } + | { + create_funding_account: CreateFundingAccountMsg; }; export type WarpMsg = | { @@ -356,6 +360,7 @@ export module warp_controller { cancellation_fee_rate?: Uint64 | null; creation_fee_max?: Uint128 | null; creation_fee_min?: Uint128 | null; + duration_days_limit?: Uint64 | null; duration_days_max?: Uint64 | null; duration_days_min?: Uint64 | null; fee_collector?: string | null; @@ -384,6 +389,7 @@ export module warp_controller { cancellation_fee_rate: Uint64; creation_fee_max: Uint128; creation_fee_min: Uint128; + duration_days_limit: Uint64; duration_days_max: Uint64; duration_days_min: Uint64; fee_collector?: string | null; From e8aebe4b782c6df041e24866c2e63da0e5e18018 Mon Sep 17 00:00:00 2001 From: simke9445 Date: Wed, 21 Feb 2024 16:51:12 +0100 Subject: [PATCH 44/44] add mainnet contracts --- package.json | 2 +- src/refs.injective.json | 16 ++++++++-------- src/refs.neutron.json | 14 +++++++------- src/refs.terra.json | 16 ++++++++-------- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/package.json b/package.json index 2e73ecd..9a3f086 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "url": "https://github.com/terra-money/warp-sdk/issues" }, "homepage": "https://github.com/terra-money/warp-sdk#readme", - "version": "0.1.71-rc12", + "version": "0.2.1", "scripts": { "clean": "rm -rf dist", "build": "yarn clean && yarn build:node && yarn build:browser", diff --git a/src/refs.injective.json b/src/refs.injective.json index 4a8b764..96b0dd1 100644 --- a/src/refs.injective.json +++ b/src/refs.injective.json @@ -19,20 +19,20 @@ }, "mainnet": { "warp-controller": { - "codeId": "71", - "address": "inj1l5xlk2eerslrd8va5qu6wd8yzc8yz8hdc579fg" + "codeId": "504", + "address": "inj1rnpwwhfg4q82rt3ylr8acyv99hwc57rdrrqnt4" }, "warp-resolver": { - "codeId": "70", - "address": "inj147v6a22ue68uumjxgz3t93g06w8vrlv7mmfuyf" + "codeId": "505", + "address": "inj14dln7eeucds7skjkkxqgesth46rl09zl7hlrfu" }, "warp-templates": { - "codeId": "82", - "address": "inj1nxp6uvz0506u32hf438uqy3cqs023k9wq6kxp8" + "codeId": "506", + "address": "inj1872z8v0zldhckg2a2yx7yjf3nmtvfc2x5llxpd" }, "warp-account-tracker": { - "codeId": "11630", - "address": "inj1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" + "codeId": "503", + "address": "inj1ng0hfwuan93cjmkf4xyrp95r589ryk5pk3sze0" } } } diff --git a/src/refs.neutron.json b/src/refs.neutron.json index 82ebc02..4978241 100644 --- a/src/refs.neutron.json +++ b/src/refs.neutron.json @@ -19,20 +19,20 @@ }, "mainnet": { "warp-controller": { - "codeId": "200", - "address": "neutron12aavdpccvq7lyrr8zaq5f54hk5ux0lw0q5xstqzre6sm2cvyfw5stlmlr3" + "codeId": "741", + "address": "neutron1qx2u4fqlyy8gfx9r5vfz80pzh88j07zr45whx30tfpj45usnt6eszwv9nj" }, "warp-resolver": { - "codeId": "201", - "address": "neutron1dzax7rxeq7ju0t8rgr5afg8kfdaxpe296qdeymreq030ay4rcx2s6sgx9p" + "codeId": "742", + "address": "neutron1tqk6vgqyfvfk30w5khy0qpuvj0h2lnzkfeynv3hzuha3yys6s2zqwrxhje" }, "warp-templates": { - "codeId": "202", + "codeId": "743", "address": "neutron1hn43q3v92y4dgdgtc5p7g684zx9dn6ejr74gchntdnppsljd89usxqs2s9" }, "warp-account-tracker": { - "codeId": "11630", - "address": "neutron1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" + "codeId": "740", + "address": "neutron1k889vqh8aarqs45d2c2kcm7krv6d030uzzkpfh5yd5kajqrt7x0sy52we9" } } } diff --git a/src/refs.terra.json b/src/refs.terra.json index 3923173..467a446 100644 --- a/src/refs.terra.json +++ b/src/refs.terra.json @@ -22,20 +22,20 @@ }, "mainnet": { "warp-controller": { - "codeId": "2495", - "address": "terra1mg93d4g69tsf3x6sa9nkmkzc9wl38gdrygu0sewwcwj6l2a4089sdd7fgj" + "codeId": "2624", + "address": "terra1w6j6w9kx29h6kssqstupppm8vytvh2phpul72wsz8ylluqdd44us5u95ny" }, "warp-resolver": { - "codeId": "1616", - "address": "terra13taf05fedehdfsguu0v24ssmrs9xfzn6wewwkxxlsdy2qmudhwfsvvgdm5" + "codeId": "2625", + "address": "terra1t7zxwt5a2aheyh5ykg9j6ax20kz2q6v9q5ty7t0vdshsadnjegjqu6yjd6" }, "warp-templates": { - "codeId": "1787", - "address": "terra1mcfu3tkd5h9zdwuserl3v6uzetv9xke8wyaaf9vx07p7shk6xlws3styfk" + "codeId": "2626", + "address": "terra1s94r56gkyyavx5xxea9kgzemh9yeh6q9h065sf3ngc2pfd7ua67srrq5gh" }, "warp-account-tracker": { - "codeId": "11630", - "address": "terra1zzgg30ygltd5s3xtescfquwmm2jktaq28t37f2j9h5wwswpxtyyspugek8" + "codeId": "2623", + "address": "terra1mwrmemx45mmqylz3j2wsq0cscnajeynlxval8rqq6vxh30fqyassajfvdq" } } }