assembly/core/strategies/helpers/strategy.ts

108 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-08-22 11:27:02 +00:00
import DSA from "dsa-connect";
import Web3 from "web3";
2021-08-22 13:49:31 +00:00
import slugify from "slugify";
2021-08-22 11:27:02 +00:00
export interface IStrategyContext {
dsa: typeof DSA;
web3: Web3;
inputs: IStrategyInput[];
}
export interface IStrategyToken {
2021-08-22 13:49:31 +00:00
address: string;
key: string;
symbol: string;
balance: string;
2021-08-22 11:27:02 +00:00
2021-08-22 13:49:31 +00:00
supply: string;
borrow: string;
2021-08-22 11:27:02 +00:00
}
export enum StrategyInputType {
INPUT = "input",
INPUT_WITH_TOKEN = "input-with-token"
}
2021-08-22 12:54:23 +00:00
// type InputTypes = {
// [StrategyInputType.INPUT] : {
// token?: IStrategyToken;
// value?: any;
// };
// }
2021-08-22 11:27:02 +00:00
export interface IStrategyInput {
type: StrategyInputType;
name: string;
placeholder:
| string
| ((context: IStrategyContext & { input: IStrategyInput }) => string);
2021-08-22 13:49:31 +00:00
validate?: (
context: IStrategyContext & { input: IStrategyInput }
) => boolean | string;
2021-08-22 11:27:02 +00:00
// If type is "input-with-token", this is the token
token?: IStrategyToken;
value?: any;
2021-08-22 12:54:23 +00:00
[key: string]: any;
2021-08-22 11:27:02 +00:00
}
export interface IStrategy {
2021-08-22 12:54:23 +00:00
id?: string;
2021-08-22 11:27:02 +00:00
name: string;
description: string;
author?: string;
inputs: IStrategyInput[];
spells: (context: IStrategyContext) => any;
2021-08-22 12:54:23 +00:00
submitText?: string;
2021-08-22 11:27:02 +00:00
}
2021-08-22 13:49:31 +00:00
export function defineStrategy(strategy: IStrategy) {
return {
...strategy,
id: strategy.id ? strategy.id : slugify(strategy.name).toLowerCase(),
inputs: strategy.inputs.map(input => ({
...input,
value: null,
onInput: (val: any) => {
input.value = val;
}
})),
submit: async (context: Pick<IStrategyContext, "web3" | "dsa">) => {
await this.validate({
...context,
inputs: strategy.inputs
});
2021-08-22 12:54:23 +00:00
2021-08-22 13:49:31 +00:00
const spells = strategy.spells({
...context,
inputs: strategy.inputs
});
2021-08-22 12:54:23 +00:00
2021-08-22 13:49:31 +00:00
return await context.dsa.cast({
spells,
onReceipt: this.onReceipt
});
},
validate: async (context: IStrategyContext) => {
for (const input of this.inputs) {
const result = await input.validate({
...context,
inputs: strategy.inputs,
input
});
if (result !== true) {
throw new Error(result || "Error has occurred");
}
}
},
onReceipt: (txHash: string, txReceipt: any) => {
// do something
}
};
2021-08-22 11:27:02 +00:00
}
2021-08-22 13:49:31 +00:00
export type DefineStrategy = ReturnType<typeof defineStrategy>;