diff --git a/README.md b/README.md index 19e1019..869bf2f 100644 --- a/README.md +++ b/README.md @@ -81,23 +81,6 @@ To ensure the SDK is functioning correctly, we have a comprehensive test suite. This will execute all unit and integration tests. Make sure all tests pass before submitting a pull request or deploying changes. -## Version Management - -This project uses [Changesets](https://github.com/changesets/changesets) to manage versions and changelogs. To contribute changes: - -1. Make your changes to the codebase. -2. Run `npm run changeset` to create a new changeset. -3. Follow the prompts to describe your changes. -4. Commit the generated changeset file along with your changes. - -To release a new version: - -1. Run `npm run version` to update package versions and changelogs. -2. Review and commit the changes. -3. Run `npm run release` to publish the new version to npm. - -For more detailed information on using Changesets, refer to the [Changesets documentation](https://github.com/changesets/changesets/blob/main/docs/intro-to-using-changesets.md). - ## Release Process This repository uses a two-step workflow process for creating new releases: diff --git a/dist/index.d.mts b/dist/index.d.mts index 4816e93..4ba3997 100644 --- a/dist/index.d.mts +++ b/dist/index.d.mts @@ -474,8 +474,8 @@ declare namespace BranchAction { } declare class TaskAction extends jspb.Message { - getTaskType(): TaskType; - setTaskType(value: TaskType): TaskAction; + getTaskType(): TaskType$1; + setTaskType(value: TaskType$1): TaskAction; getId(): string; setId(value: string): TaskAction; getName(): string; @@ -527,7 +527,7 @@ declare class TaskAction extends jspb.Message { declare namespace TaskAction { export type AsObject = { - taskType: TaskType, + taskType: TaskType$1, id: string, name: string, nextList: Array, @@ -566,53 +566,53 @@ declare namespace Execution { } } -declare class Task$1 extends jspb.Message { +declare class Task extends jspb.Message { hasId(): boolean; clearId(): void; getId(): UUID | undefined; - setId(value?: UUID): Task$1; + setId(value?: UUID): Task; getOwner(): string; - setOwner(value: string): Task$1; + setOwner(value: string): Task; getSmartAccountAddress(): string; - setSmartAccountAddress(value: string): Task$1; + setSmartAccountAddress(value: string): Task; hasTrigger(): boolean; clearTrigger(): void; getTrigger(): TaskTrigger | undefined; - setTrigger(value?: TaskTrigger): Task$1; + setTrigger(value?: TaskTrigger): Task; clearNodesList(): void; getNodesList(): Array; - setNodesList(value: Array): Task$1; + setNodesList(value: Array): Task; addNodes(value?: TaskAction, index?: number): TaskAction; getStartAt(): number; - setStartAt(value: number): Task$1; + setStartAt(value: number): Task; getExpiredAt(): number; - setExpiredAt(value: number): Task$1; + setExpiredAt(value: number): Task; getMemo(): string; - setMemo(value: string): Task$1; + setMemo(value: string): Task; getCompletedAt(): number; - setCompletedAt(value: number): Task$1; + setCompletedAt(value: number): Task; getStatus(): TaskStatus; - setStatus(value: TaskStatus): Task$1; + setStatus(value: TaskStatus): Task; getRepeatable(): boolean; - setRepeatable(value: boolean): Task$1; + setRepeatable(value: boolean): Task; clearExecutionsList(): void; getExecutionsList(): Array; - setExecutionsList(value: Array): Task$1; + setExecutionsList(value: Array): Task; addExecutions(value?: Execution, index?: number): Execution; serializeBinary(): Uint8Array; - toObject(includeInstance?: boolean): Task$1.AsObject; - static toObject(includeInstance: boolean, msg: Task$1): Task$1.AsObject; + toObject(includeInstance?: boolean): Task.AsObject; + static toObject(includeInstance: boolean, msg: Task): Task.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; - static serializeBinaryToWriter(message: Task$1, writer: jspb.BinaryWriter): void; - static deserializeBinary(bytes: Uint8Array): Task$1; - static deserializeBinaryFromReader(message: Task$1, reader: jspb.BinaryReader): Task$1; + static serializeBinaryToWriter(message: Task, writer: jspb.BinaryWriter): void; + static deserializeBinary(bytes: Uint8Array): Task; + static deserializeBinaryFromReader(message: Task, reader: jspb.BinaryReader): Task; } -declare namespace Task$1 { +declare namespace Task { export type AsObject = { id?: UUID.AsObject, owner: string, @@ -939,7 +939,7 @@ declare enum TriggerType { EXPRESSIONTRIGGER = 2, } -declare enum TaskType { +declare enum TaskType$1 { ETHTRANSFERTASK = 0, CONTRACTEXECUTIONTASK = 1, GRAPHQLDATAQUERYTASK = 2, @@ -1088,18 +1088,18 @@ interface IAggregatorClient { ): grpc.ClientUnaryCall; getTask( request: UUID, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; getTask( request: UUID, metadata: grpc.Metadata, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; getTask( request: UUID, metadata: grpc.Metadata, options: Partial, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; cancelTask( request: UUID, @@ -1336,18 +1336,18 @@ declare class AggregatorClient extends grpc.Client implements IAggregatorClient ): grpc.ClientUnaryCall; public getTask( request: UUID, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; public getTask( request: UUID, metadata: grpc.Metadata, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; public getTask( request: UUID, metadata: grpc.Metadata, options: Partial, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; public cancelTask( request: UUID, @@ -1466,30 +1466,58 @@ interface GetKeyResponse { } interface ClientOption { endpoint: string; - jwtApiKey?: string; } -interface Task { +interface TaskType { id: string; - status: string; - result?: any; - error?: string; + owner: string; + smartAccountAddress: string; + trigger: { + triggerType: number; + schedule?: any; + contractQuery?: any; + expression: { + expression: string; + }; + }; + nodesList: Array<{ + taskType: number; + id: string; + name: string; + nextList: any[]; + ethTransfer?: any; + contractExecution: any; + graphqlDataQuery?: any; + httpDataQuery?: any; + customCode?: any; + branch?: any; + }>; + startAt: number; + expiredAt: number; + memo: string; + completedAt: number; + status: number; + repeatable: boolean; + executionsList: any[]; } interface CreateTaskResponse { id: string; } interface ListTasksResponse { - tasks: Task[]; + tasks: { + id: string; + status: string; + }[]; +} +interface CancelTaskResponse { + value: boolean; +} +interface DeleteTaskResponse { + value: boolean; } interface GetAddressesResponse { owner: string; smart_account_address: string; } -interface TransactionResp { - hash: string; -} -interface BalanceResp { - balance: string; -} declare class BaseClient { readonly endpoint: string; @@ -1510,11 +1538,21 @@ declare class Client extends BaseClient { address: string; tokenContract: string; oracleContract: string; + }, { authKey }: { + authKey: string; }): Promise; - listTasks(address: string): Promise; - getTask(id: string): Promise; - cancelTask(id: string): Promise; - deleteTask(id: string): Promise; + listTasks(address: string, { authKey }: { + authKey: string; + }): Promise; + getTask(id: string, { authKey }: { + authKey: string; + }): Promise; + cancelTask(id: string, { authKey }: { + authKey: string; + }): Promise; + deleteTask(id: string, { authKey }: { + authKey: string; + }): Promise; } -export { AUTH_KEY_HEADER, type BalanceResp, type ClientOption, type CreateTaskResponse, type Environment, type GetAddressesResponse, type GetKeyResponse, type ListTasksResponse, type RequestOptions, type Task, type TransactionResp, Client as default, getKeyRequestMessage }; +export { AUTH_KEY_HEADER, type CancelTaskResponse, type ClientOption, type CreateTaskResponse, type DeleteTaskResponse, type Environment, type GetAddressesResponse, type GetKeyResponse, type ListTasksResponse, type RequestOptions, type TaskType, Client as default, getKeyRequestMessage }; diff --git a/dist/index.d.ts b/dist/index.d.ts index 4816e93..4ba3997 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -474,8 +474,8 @@ declare namespace BranchAction { } declare class TaskAction extends jspb.Message { - getTaskType(): TaskType; - setTaskType(value: TaskType): TaskAction; + getTaskType(): TaskType$1; + setTaskType(value: TaskType$1): TaskAction; getId(): string; setId(value: string): TaskAction; getName(): string; @@ -527,7 +527,7 @@ declare class TaskAction extends jspb.Message { declare namespace TaskAction { export type AsObject = { - taskType: TaskType, + taskType: TaskType$1, id: string, name: string, nextList: Array, @@ -566,53 +566,53 @@ declare namespace Execution { } } -declare class Task$1 extends jspb.Message { +declare class Task extends jspb.Message { hasId(): boolean; clearId(): void; getId(): UUID | undefined; - setId(value?: UUID): Task$1; + setId(value?: UUID): Task; getOwner(): string; - setOwner(value: string): Task$1; + setOwner(value: string): Task; getSmartAccountAddress(): string; - setSmartAccountAddress(value: string): Task$1; + setSmartAccountAddress(value: string): Task; hasTrigger(): boolean; clearTrigger(): void; getTrigger(): TaskTrigger | undefined; - setTrigger(value?: TaskTrigger): Task$1; + setTrigger(value?: TaskTrigger): Task; clearNodesList(): void; getNodesList(): Array; - setNodesList(value: Array): Task$1; + setNodesList(value: Array): Task; addNodes(value?: TaskAction, index?: number): TaskAction; getStartAt(): number; - setStartAt(value: number): Task$1; + setStartAt(value: number): Task; getExpiredAt(): number; - setExpiredAt(value: number): Task$1; + setExpiredAt(value: number): Task; getMemo(): string; - setMemo(value: string): Task$1; + setMemo(value: string): Task; getCompletedAt(): number; - setCompletedAt(value: number): Task$1; + setCompletedAt(value: number): Task; getStatus(): TaskStatus; - setStatus(value: TaskStatus): Task$1; + setStatus(value: TaskStatus): Task; getRepeatable(): boolean; - setRepeatable(value: boolean): Task$1; + setRepeatable(value: boolean): Task; clearExecutionsList(): void; getExecutionsList(): Array; - setExecutionsList(value: Array): Task$1; + setExecutionsList(value: Array): Task; addExecutions(value?: Execution, index?: number): Execution; serializeBinary(): Uint8Array; - toObject(includeInstance?: boolean): Task$1.AsObject; - static toObject(includeInstance: boolean, msg: Task$1): Task$1.AsObject; + toObject(includeInstance?: boolean): Task.AsObject; + static toObject(includeInstance: boolean, msg: Task): Task.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; - static serializeBinaryToWriter(message: Task$1, writer: jspb.BinaryWriter): void; - static deserializeBinary(bytes: Uint8Array): Task$1; - static deserializeBinaryFromReader(message: Task$1, reader: jspb.BinaryReader): Task$1; + static serializeBinaryToWriter(message: Task, writer: jspb.BinaryWriter): void; + static deserializeBinary(bytes: Uint8Array): Task; + static deserializeBinaryFromReader(message: Task, reader: jspb.BinaryReader): Task; } -declare namespace Task$1 { +declare namespace Task { export type AsObject = { id?: UUID.AsObject, owner: string, @@ -939,7 +939,7 @@ declare enum TriggerType { EXPRESSIONTRIGGER = 2, } -declare enum TaskType { +declare enum TaskType$1 { ETHTRANSFERTASK = 0, CONTRACTEXECUTIONTASK = 1, GRAPHQLDATAQUERYTASK = 2, @@ -1088,18 +1088,18 @@ interface IAggregatorClient { ): grpc.ClientUnaryCall; getTask( request: UUID, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; getTask( request: UUID, metadata: grpc.Metadata, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; getTask( request: UUID, metadata: grpc.Metadata, options: Partial, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; cancelTask( request: UUID, @@ -1336,18 +1336,18 @@ declare class AggregatorClient extends grpc.Client implements IAggregatorClient ): grpc.ClientUnaryCall; public getTask( request: UUID, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; public getTask( request: UUID, metadata: grpc.Metadata, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; public getTask( request: UUID, metadata: grpc.Metadata, options: Partial, - callback: (error: grpc.ServiceError | null, response: Task$1) => void + callback: (error: grpc.ServiceError | null, response: Task) => void ): grpc.ClientUnaryCall; public cancelTask( request: UUID, @@ -1466,30 +1466,58 @@ interface GetKeyResponse { } interface ClientOption { endpoint: string; - jwtApiKey?: string; } -interface Task { +interface TaskType { id: string; - status: string; - result?: any; - error?: string; + owner: string; + smartAccountAddress: string; + trigger: { + triggerType: number; + schedule?: any; + contractQuery?: any; + expression: { + expression: string; + }; + }; + nodesList: Array<{ + taskType: number; + id: string; + name: string; + nextList: any[]; + ethTransfer?: any; + contractExecution: any; + graphqlDataQuery?: any; + httpDataQuery?: any; + customCode?: any; + branch?: any; + }>; + startAt: number; + expiredAt: number; + memo: string; + completedAt: number; + status: number; + repeatable: boolean; + executionsList: any[]; } interface CreateTaskResponse { id: string; } interface ListTasksResponse { - tasks: Task[]; + tasks: { + id: string; + status: string; + }[]; +} +interface CancelTaskResponse { + value: boolean; +} +interface DeleteTaskResponse { + value: boolean; } interface GetAddressesResponse { owner: string; smart_account_address: string; } -interface TransactionResp { - hash: string; -} -interface BalanceResp { - balance: string; -} declare class BaseClient { readonly endpoint: string; @@ -1510,11 +1538,21 @@ declare class Client extends BaseClient { address: string; tokenContract: string; oracleContract: string; + }, { authKey }: { + authKey: string; }): Promise; - listTasks(address: string): Promise; - getTask(id: string): Promise; - cancelTask(id: string): Promise; - deleteTask(id: string): Promise; + listTasks(address: string, { authKey }: { + authKey: string; + }): Promise; + getTask(id: string, { authKey }: { + authKey: string; + }): Promise; + cancelTask(id: string, { authKey }: { + authKey: string; + }): Promise; + deleteTask(id: string, { authKey }: { + authKey: string; + }): Promise; } -export { AUTH_KEY_HEADER, type BalanceResp, type ClientOption, type CreateTaskResponse, type Environment, type GetAddressesResponse, type GetKeyResponse, type ListTasksResponse, type RequestOptions, type Task, type TransactionResp, Client as default, getKeyRequestMessage }; +export { AUTH_KEY_HEADER, type CancelTaskResponse, type ClientOption, type CreateTaskResponse, type DeleteTaskResponse, type Environment, type GetAddressesResponse, type GetKeyResponse, type ListTasksResponse, type RequestOptions, type TaskType, Client as default, getKeyRequestMessage }; diff --git a/dist/index.js b/dist/index.js index 7759986..457ff92 100644 --- a/dist/index.js +++ b/dist/index.js @@ -4505,20 +4505,37 @@ var AggregatorClient = grpc.makeGenericClientConstructor(AggregatorService); // src/index.ts init_avs_pb(); +// src/types.ts +var AUTH_KEY_HEADER = "authKey"; + // src/task.ts var Task2 = class { - // result?: any; - // error?: string; + // Add other missing properties here constructor(task) { - this.id = task.getId(); + this.id = task.getId()?.toString() || ""; this.status = task.getStatus().toString(); + this.owner = task.getOwner(); + this.smartAccountAddress = task.getSmartAccountAddress(); + this.trigger = { + triggerType: task.getTrigger()?.getTriggerType() || 0, + schedule: task.getTrigger()?.getSchedule()?.toObject(), + contractQuery: task.getTrigger()?.getContractQuery()?.toObject(), + expression: task.getTrigger()?.getExpression()?.toObject() || { + expression: "" + } + }; + this.nodesList = task.getNodesList(); + this.startAt = task.getStartAt(); + this.expiredAt = task.getExpiredAt(); + this.memo = task.getMemo(); + this.completedAt = task.getCompletedAt(); + this.status = task.getStatus(); + this.repeatable = task.getRepeatable(); + this.executionsList = task.getExecutionsList(); } }; var task_default = Task2; -// src/types.ts -var AUTH_KEY_HEADER = "authKey"; - // src/index.ts var BaseClient = class { constructor(opts) { @@ -4594,7 +4611,7 @@ var Client = class extends BaseClient { address, oracleContract, tokenContract - }) { + }, { authKey }) { const trigger = new TaskTrigger(); trigger.setTriggerType(TriggerType.EXPRESSIONTRIGGER); trigger.setExpression( @@ -4619,17 +4636,22 @@ var Client = class extends BaseClient { execution.setCallData(callData); action.setContractExecution(execution); const request = new CreateTaskReq().setTrigger(trigger).setActionsList([action]).setExpiredAt(Math.floor(Date.now() / 1e3) + 1e6); - const result = await this._callRPC("createTask", request); + const result = await this._callRPC("createTask", request, { authKey }); return { id: result.getId() }; } - async listTasks(address) { + async listTasks(address, { authKey }) { const request = new ListTasksReq(); - const result = await this._callRPC("listTasks", request); + const result = await this._callRPC("listTasks", request, { authKey }); const tasks = import_lodash.default.map( result.getTasksList(), - (obj) => new task_default(obj) + (obj) => { + return { + id: obj.getId(), + status: import_lodash.default.capitalize(obj.getStatus().toString()) + }; + } ); return { tasks @@ -4637,32 +4659,40 @@ var Client = class extends BaseClient { } // TODO: specify the return type to match client’s requirements // Right now we simply return the original object from the server - async getTask(id) { + async getTask(id, { authKey }) { const request = new UUID(); request.setBytes(id); + ``; const result = await this._callRPC( "getTask", - request + request, + { authKey } ); - return result.toObject(); + return new task_default(result); } - async cancelTask(id) { + async cancelTask(id, { authKey }) { const request = new UUID(); request.setBytes(id); const result = await this._callRPC( "cancelTask", - request + request, + { authKey } ); - return result.getValue(); + return { + value: result.getValue() + }; } - async deleteTask(id) { + async deleteTask(id, { authKey }) { const request = new UUID(); request.setBytes(id); const result = await this._callRPC( "deleteTask", - request + request, + { authKey } ); - return result.getValue(); + return { + value: result.getValue() + }; } }; // Annotate the CommonJS export names for ESM import in node: diff --git a/dist/index.mjs b/dist/index.mjs index f308505..328fea8 100644 --- a/dist/index.mjs +++ b/dist/index.mjs @@ -4493,20 +4493,37 @@ var AggregatorClient = grpc.makeGenericClientConstructor(AggregatorService); // src/index.ts init_avs_pb(); +// src/types.ts +var AUTH_KEY_HEADER = "authKey"; + // src/task.ts var Task2 = class { - // result?: any; - // error?: string; + // Add other missing properties here constructor(task) { - this.id = task.getId(); + this.id = task.getId()?.toString() || ""; this.status = task.getStatus().toString(); + this.owner = task.getOwner(); + this.smartAccountAddress = task.getSmartAccountAddress(); + this.trigger = { + triggerType: task.getTrigger()?.getTriggerType() || 0, + schedule: task.getTrigger()?.getSchedule()?.toObject(), + contractQuery: task.getTrigger()?.getContractQuery()?.toObject(), + expression: task.getTrigger()?.getExpression()?.toObject() || { + expression: "" + } + }; + this.nodesList = task.getNodesList(); + this.startAt = task.getStartAt(); + this.expiredAt = task.getExpiredAt(); + this.memo = task.getMemo(); + this.completedAt = task.getCompletedAt(); + this.status = task.getStatus(); + this.repeatable = task.getRepeatable(); + this.executionsList = task.getExecutionsList(); } }; var task_default = Task2; -// src/types.ts -var AUTH_KEY_HEADER = "authKey"; - // src/index.ts var BaseClient = class { constructor(opts) { @@ -4582,7 +4599,7 @@ var Client = class extends BaseClient { address, oracleContract, tokenContract - }) { + }, { authKey }) { const trigger = new TaskTrigger(); trigger.setTriggerType(TriggerType.EXPRESSIONTRIGGER); trigger.setExpression( @@ -4607,17 +4624,22 @@ var Client = class extends BaseClient { execution.setCallData(callData); action.setContractExecution(execution); const request = new CreateTaskReq().setTrigger(trigger).setActionsList([action]).setExpiredAt(Math.floor(Date.now() / 1e3) + 1e6); - const result = await this._callRPC("createTask", request); + const result = await this._callRPC("createTask", request, { authKey }); return { id: result.getId() }; } - async listTasks(address) { + async listTasks(address, { authKey }) { const request = new ListTasksReq(); - const result = await this._callRPC("listTasks", request); + const result = await this._callRPC("listTasks", request, { authKey }); const tasks = _.map( result.getTasksList(), - (obj) => new task_default(obj) + (obj) => { + return { + id: obj.getId(), + status: _.capitalize(obj.getStatus().toString()) + }; + } ); return { tasks @@ -4625,32 +4647,40 @@ var Client = class extends BaseClient { } // TODO: specify the return type to match client’s requirements // Right now we simply return the original object from the server - async getTask(id) { + async getTask(id, { authKey }) { const request = new UUID(); request.setBytes(id); + ``; const result = await this._callRPC( "getTask", - request + request, + { authKey } ); - return result.toObject(); + return new task_default(result); } - async cancelTask(id) { + async cancelTask(id, { authKey }) { const request = new UUID(); request.setBytes(id); const result = await this._callRPC( "cancelTask", - request + request, + { authKey } ); - return result.getValue(); + return { + value: result.getValue() + }; } - async deleteTask(id) { + async deleteTask(id, { authKey }) { const request = new UUID(); request.setBytes(id); const result = await this._callRPC( "deleteTask", - request + request, + { authKey } ); - return result.getValue(); + return { + value: result.getValue() + }; } }; export { diff --git a/src/index.ts b/src/index.ts index 6980e76..697feb7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,9 +6,14 @@ import { getKeyRequestMessage } from "./auth"; import { AggregatorClient } from "../grpc_codegen/avs_grpc_pb"; import * as avs_pb from "../grpc_codegen/avs_pb"; import { BoolValue } from "google-protobuf/google/protobuf/wrappers_pb"; +import { + AUTH_KEY_HEADER, + CancelTaskResponse, + DeleteTaskResponse, + RequestOptions, + TaskType, +} from "./types"; import Task from "./task"; -import { AUTH_KEY_HEADER, RequestOptions } from "./types"; - // Move interfaces to a separate file, e.g., types.ts import { ClientOption, @@ -136,15 +141,18 @@ export default class Client extends BaseClient { }; } - async createTask({ - address, - oracleContract, - tokenContract, - }: { - address: string; - tokenContract: string; - oracleContract: string; - }): Promise { + async createTask( + { + address, + oracleContract, + tokenContract, + }: { + address: string; + tokenContract: string; + oracleContract: string; + }, + { authKey }: { authKey: string } + ): Promise { const trigger = new avs_pb.TaskTrigger(); trigger.setTriggerType(avs_pb.TriggerType.EXPRESSIONTRIGGER); trigger.setExpression( @@ -180,24 +188,32 @@ export default class Client extends BaseClient { const result = await this._callRPC< avs_pb.CreateTaskResp, avs_pb.CreateTaskReq - >("createTask", request); + >("createTask", request, { authKey }); return { id: result.getId(), }; } - async listTasks(address: string): Promise { + async listTasks( + address: string, + { authKey }: { authKey: string } + ): Promise { const request = new avs_pb.ListTasksReq(); const result = await this._callRPC< avs_pb.ListTasksResp, avs_pb.ListTasksReq - >("listTasks", request); + >("listTasks", request, { authKey }); const tasks = _.map( result.getTasksList(), - (obj: avs_pb.ListTasksResp.TaskItemResp) => new Task(obj) + (obj: avs_pb.ListTasksResp.TaskItemResp) => { + return { + id: obj.getId(), + status: _.capitalize(obj.getStatus().toString()), + }; + } ); return { @@ -207,40 +223,57 @@ export default class Client extends BaseClient { // TODO: specify the return type to match client’s requirements // Right now we simply return the original object from the server - async getTask(id: string): Promise { + async getTask( + id: string, + { authKey }: { authKey: string } + ): Promise { const request = new avs_pb.UUID(); request.setBytes(id); + ``; const result = await this._callRPC( "getTask", - request + request, + { authKey } ); - return result.toObject(); + return new Task(result); } - async cancelTask(id: string): Promise { + async cancelTask( + id: string, + { authKey }: { authKey: string } + ): Promise { const request = new avs_pb.UUID(); request.setBytes(id); const result = await this._callRPC( "cancelTask", - request + request, + { authKey } ); - return result.getValue(); + return { + value: result.getValue(), + }; } - async deleteTask(id: string): Promise { + async deleteTask( + id: string, + { authKey }: { authKey: string } + ): Promise { const request = new avs_pb.UUID(); request.setBytes(id); const result = await this._callRPC( "deleteTask", - request + request, + { authKey } ); - return result.getValue(); + return { + value: result.getValue(), + }; } } diff --git a/src/task.ts b/src/task.ts index 6009fe4..a8c1e77 100644 --- a/src/task.ts +++ b/src/task.ts @@ -1,15 +1,48 @@ import * as avs_pb from "../grpc_codegen/avs_pb"; +import { TaskType } from "./types"; -class Task { +class Task implements TaskType { id: string; - status: string; -// result?: any; -// error?: string; + status: number; + owner: string; + smartAccountAddress: string; + trigger: { + triggerType: number; + schedule?: any; + contractQuery?: any; + expression: { expression: string }; + }; + nodesList: any[]; + startAt: number; + expiredAt: number; + memo: string; + completedAt: number; + repeatable: boolean; + executionsList: any[]; + // Add other missing properties here - constructor(task: avs_pb.ListTasksResp.TaskItemResp) { - this.id = task.getId(); + constructor(task: avs_pb.Task) { + this.id = task.getId()?.toString() || ""; this.status = task.getStatus().toString(); + this.owner = task.getOwner(); + this.smartAccountAddress = task.getSmartAccountAddress(); + this.trigger = { + triggerType: task.getTrigger()?.getTriggerType() || 0, + schedule: task.getTrigger()?.getSchedule()?.toObject(), + contractQuery: task.getTrigger()?.getContractQuery()?.toObject(), + expression: task.getTrigger()?.getExpression()?.toObject() || { + expression: "", + }, + }; + this.nodesList = task.getNodesList(); + this.startAt = task.getStartAt(); + this.expiredAt = task.getExpiredAt(); + this.memo = task.getMemo(); + this.completedAt = task.getCompletedAt(); + this.status = task.getStatus(); + this.repeatable = task.getRepeatable(); + this.executionsList = task.getExecutionsList(); } } -export default Task; \ No newline at end of file +export default Task; diff --git a/src/types.ts b/src/types.ts index c6b8b37..d54cf9a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,5 @@ +import { TaskStatus } from "../grpc_codegen/avs_pb"; +import _ from "lodash"; // Define the environment type export type Environment = "production" | "development" | "staging"; @@ -12,27 +14,40 @@ export interface GetKeyResponse { } export interface ClientOption { - // env?: Environment; endpoint: string; - - // used in automated manner where this key can schedule job on behalf of other user. this jwtApiKey is generated from aggregator CLI. It's a long live key. - // This currently used in our telegram bot, because the bot can schedule and manage tasks for any user - // It is just require the user to prove they own the wallet in initial onboarding. - jwtApiKey?: string; - - // used in front-end app where front-end generate the signature - // presignSignature?: string; - // signatureExpiredAt?: number; - - // env?: Environment; - // owner?: string; } -export interface Task { +export interface TaskType { id: string; - status: string; - result?: any; - error?: string; + owner: string; + smartAccountAddress: string; + trigger: { + triggerType: number; + schedule?: any; + contractQuery?: any; + expression: { + expression: string; + }; + }; + nodesList: Array<{ + taskType: number; + id: string; + name: string; + nextList: any[]; + ethTransfer?: any; + contractExecution: any; + graphqlDataQuery?: any; + httpDataQuery?: any; + customCode?: any; + branch?: any; + }>; + startAt: number; + expiredAt: number; + memo: string; + completedAt: number; + status: number; + repeatable: boolean; + executionsList: any[]; } export interface CreateTaskResponse { @@ -40,18 +55,21 @@ export interface CreateTaskResponse { } export interface ListTasksResponse { - tasks: Task[]; + tasks: { + id: string; + status: string; + }[]; } -export interface GetAddressesResponse { - owner: string; - smart_account_address: string; +export interface CancelTaskResponse { + value: boolean; } -export interface TransactionResp { - hash: string; +export interface DeleteTaskResponse { + value: boolean; } -export interface BalanceResp { - balance: string; -} +export interface GetAddressesResponse { + owner: string; + smart_account_address: string; +} \ No newline at end of file diff --git a/tests/cancelTask.test.ts b/tests/cancelTask.test.ts new file mode 100644 index 0000000..41bcaed --- /dev/null +++ b/tests/cancelTask.test.ts @@ -0,0 +1,181 @@ +import { describe, beforeAll, test, expect } from "@jest/globals"; +import Client from "../dist/index.js"; +import dotenv from "dotenv"; +import path from "path"; +import { getAddress, generateSignature, requireEnvVar } from "./utils"; + +// Update the dotenv configuration +dotenv.config({ path: path.resolve(__dirname, "..", ".env.test") }); + +// Get environment variables with type safety +const { + TEST_API_KEY, + TEST_PRIVATE_KEY, + TOKEN_CONTRACT, + ORACLE_CONTRACT, + ENDPOINT, +} = { + TEST_API_KEY: requireEnvVar("TEST_API_KEY"), + TEST_PRIVATE_KEY: requireEnvVar("TEST_PRIVATE_KEY"), + TOKEN_CONTRACT: requireEnvVar("TOKEN_CONTRACT"), + ORACLE_CONTRACT: requireEnvVar("ORACLE_CONTRACT"), + ENDPOINT: requireEnvVar("ENDPOINT"), +} as const; + +// Define EXPIRED_AT as a constant +const EXPIRED_AT = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours from now + +describe("cancelTask Tests", () => { + let ownerAddress: string; + let client: Client; + + beforeAll(async () => { + ownerAddress = await getAddress(TEST_PRIVATE_KEY); + console.log("Client endpoint:", ENDPOINT, "\nOwner address:", ownerAddress); + + // Initialize the client with test credentials + client = new Client({ + endpoint: ENDPOINT, + }); + }); + + describe("Auth with Signature", () => { + let authKey: string; + let smartWallet: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should cancel task when authenticated with signature", async () => { + const result = await client.cancelTask(createdTaskId, { authKey }); + expect(result.value).toBe(true); + + const listRes = await client.listTasks(smartWallet, { authKey }); + expect(Array.isArray(listRes.tasks)).toBe(true); + expect(listRes.tasks.some((task) => task.id === createdTaskId)).toBe( + true + ); + }); + + test("should throw error when canceling an non-existent task", async () => { + // This fails because the current error message is "2 UNKNOWN: Key not found", which is not a clear error message + await expect(client.cancelTask("non-existent-task-id", { authKey })) + .rejects.toThrow("Task Id not found"); + }); + }); + + describe("Auth with API key", () => { + let authKey: string; + let smartWallet: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with API key ..."); + const res = await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should cancel task when authenticated with API key", async () => { + const result = await client.cancelTask(createdTaskId, { authKey }); + expect(result.value).toBe(true); + + const listRes = await client.listTasks(smartWallet, { authKey }); + expect(Array.isArray(listRes.tasks)).toBe(true); + expect(listRes.tasks.some((task) => task.id === createdTaskId)).toBe( + true + ); + }); + + test("should throw error when canceling an non-existent task", async () => { + await expect(client.cancelTask("non-existent-task-id", { authKey })) + .rejects.toThrow("Task Id not found"); + }); + }); + + describe("Without authentication", () => { + let smartWallet: string; + let authKey: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should throw error when canceling a task without authentication", async () => { + await expect(client.cancelTask(createdTaskId, { authKey: "" })).rejects.toThrow("missing auth header"); + }); + }); +}); diff --git a/tests/createTask.test.ts b/tests/createTask.test.ts index d13c224..ee03367 100644 --- a/tests/createTask.test.ts +++ b/tests/createTask.test.ts @@ -25,105 +25,139 @@ const { // Define EXPIRED_AT as a constant const EXPIRED_AT = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours from now -describe("listTasks Tests", () => { +describe("createTask Tests", () => { let ownerAddress: string; - + let client: Client; beforeAll(async () => { ownerAddress = await getAddress(TEST_PRIVATE_KEY); + console.log("Client endpoint:", ENDPOINT, "\nOwner address:", ownerAddress); + + // Initialize the client with test credentials + client = new Client({ + endpoint: ENDPOINT, + }); }); describe("Auth with Signature", () => { - let client: Client; let smartWallet: string; - beforeAll(async () => { - // Initialize the client with test credentials - client = new Client({ - endpoint: ENDPOINT, - }); + let authKey: string; + beforeAll(async () => { console.log("Authenticating with signature ..."); const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); - await client.authWithSignature(ownerAddress, signature, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); - const result = await client.getAddresses(ownerAddress); + const result = await client.getAddresses(ownerAddress, { authKey }); smartWallet = result.smart_account_address; console.log(`Smart wallet created: ${smartWallet}`); }); test("should create a task when authenticated with signature", async () => { - const result = await client.createTask({ - address: smartWallet, - tokenContract: TOKEN_CONTRACT, - oracleContract: ORACLE_CONTRACT, - }); + const result = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); console.log("Create task result:", result); expect(result).toBeDefined(); expect(result).toHaveProperty("id"); }); - test("should fail when creating a task with owner address using signature", async () => { - await expect( - client.createTask({ + test("should throw error when creating a task with owner address using signature", async () => { + await expect(client.createTask( + { address: ownerAddress, tokenContract: TOKEN_CONTRACT, oracleContract: ORACLE_CONTRACT, - }) - ).rejects.toThrow("invalid address"); + }, + { authKey } + )).rejects.toThrow("invalid address"); }); }); describe("Auth with API key", () => { - let client: Client; + let authKey: string; let smartWallet: string; - beforeAll(async () => { - // Initialize the client with test credentials - client = new Client({ - endpoint: ENDPOINT, - }); + beforeAll(async () => { console.log("Authenticating with API key ..."); - await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + const res = await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + authKey = res.authKey; console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); - const result = await client.getAddresses(ownerAddress); + const result = await client.getAddresses(ownerAddress, { authKey }); smartWallet = result.smart_account_address; console.log(`Smart wallet created: ${smartWallet}`); }); test("should create a task when authenticated with API key", async () => { - const result = await client.createTask({ - address: smartWallet, - tokenContract: TOKEN_CONTRACT, - oracleContract: ORACLE_CONTRACT, - }); + const result = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); console.log("Create task result:", result); expect(result).toBeDefined(); expect(result).toHaveProperty("id"); }); - test("should fail when creating a task with owner address using API key", async () => { - await expect( - client.createTask({ + test("should throw error when creating a task with owner address using API key", async () => { + await expect(client.createTask( + { address: ownerAddress, tokenContract: TOKEN_CONTRACT, oracleContract: ORACLE_CONTRACT, - }) + }, + { authKey } + ) ).rejects.toThrow("invalid address"); }); }); - test("should throw error when creating a task without authentication", async () => { - const clientWithoutAuth = new Client({ - endpoint: ENDPOINT, + describe("Without authentication", () => { + let smartWallet: string; + let authKey: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); }); - await expect( - clientWithoutAuth.createTask({ - address: ownerAddress, - tokenContract: TOKEN_CONTRACT, - oracleContract: ORACLE_CONTRACT, - }) - ).rejects.toThrow("missing auth header"); + test("should throw error when creating a task without authentication", async () => { + await expect(client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey: "" } + ) + ).rejects.toThrow("missing auth header"); + }); }); }); diff --git a/tests/deleteTask.test.ts b/tests/deleteTask.test.ts new file mode 100644 index 0000000..ab2c995 --- /dev/null +++ b/tests/deleteTask.test.ts @@ -0,0 +1,181 @@ +import { describe, beforeAll, test, expect } from "@jest/globals"; +import Client from "../dist/index.js"; +import dotenv from "dotenv"; +import path from "path"; +import { getAddress, generateSignature, requireEnvVar } from "./utils"; + +// Update the dotenv configuration +dotenv.config({ path: path.resolve(__dirname, "..", ".env.test") }); + +// Get environment variables with type safety +const { + TEST_API_KEY, + TEST_PRIVATE_KEY, + TOKEN_CONTRACT, + ORACLE_CONTRACT, + ENDPOINT, +} = { + TEST_API_KEY: requireEnvVar("TEST_API_KEY"), + TEST_PRIVATE_KEY: requireEnvVar("TEST_PRIVATE_KEY"), + TOKEN_CONTRACT: requireEnvVar("TOKEN_CONTRACT"), + ORACLE_CONTRACT: requireEnvVar("ORACLE_CONTRACT"), + ENDPOINT: requireEnvVar("ENDPOINT"), +} as const; + +// Define EXPIRED_AT as a constant +const EXPIRED_AT = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours from now + +describe("deleteTask Tests", () => { + let ownerAddress: string; + let client: Client; + + beforeAll(async () => { + ownerAddress = await getAddress(TEST_PRIVATE_KEY); + console.log("Client endpoint:", ENDPOINT, "\nOwner address:", ownerAddress); + + // Initialize the client with test credentials + client = new Client({ + endpoint: ENDPOINT, + }); + }); + + describe("Auth with Signature", () => { + let authKey: string; + let smartWallet: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should delete task when authenticated with signature", async () => { + const result = await client.deleteTask(createdTaskId, { authKey }); + expect(result.value).toBe(true); + + const listRes = await client.listTasks(smartWallet, { authKey }); + expect(Array.isArray(listRes.tasks)).toBe(true); + expect(listRes.tasks.some((task) => task.id === createdTaskId)).toBe( + false + ); + }); + + test("should throw error when deleting an non-existent task", async () => { + // This fails because the current error message is "2 UNKNOWN: Key not found", which is not a clear error message + await expect(client.deleteTask("non-existent-task-id", { authKey })) + .rejects.toThrow("Task Id not found"); + }); + }); + + describe("Auth with API key", () => { + let authKey: string; + let smartWallet: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with API key ..."); + const res = await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should delete task when authenticated with API key", async () => { + const result = await client.deleteTask(createdTaskId, { authKey }); + expect(result.value).toBe(true); + + const listRes = await client.listTasks(smartWallet, { authKey }); + expect(Array.isArray(listRes.tasks)).toBe(true); + expect(listRes.tasks.some((task) => task.id === createdTaskId)).toBe( + false + ); + }); + + test("should throw error when deleting an non-existent task", async () => { + await expect(client.deleteTask("non-existent-task-id", { authKey })) + .rejects.toThrow("Task Id not found"); + }); + }); + + describe("Without authentication", () => { + let smartWallet: string; + let authKey: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should throw error when deleting a task without authentication", async () => { + await expect(client.deleteTask(createdTaskId, { authKey: "" })).rejects.toThrow("missing auth header"); + }); + }); +}); diff --git a/tests/getTask.test.ts b/tests/getTask.test.ts new file mode 100644 index 0000000..acf18ec --- /dev/null +++ b/tests/getTask.test.ts @@ -0,0 +1,186 @@ +import { describe, beforeAll, test, expect } from "@jest/globals"; +import Client from "../dist/index.js"; +import dotenv from "dotenv"; +import path from "path"; +import { getAddress, generateSignature, requireEnvVar } from "./utils"; + +// Update the dotenv configuration +dotenv.config({ path: path.resolve(__dirname, "..", ".env.test") }); + +// Get environment variables with type safety +const { + TEST_API_KEY, + TEST_PRIVATE_KEY, + TOKEN_CONTRACT, + ORACLE_CONTRACT, + ENDPOINT, +} = { + TEST_API_KEY: requireEnvVar("TEST_API_KEY"), + TEST_PRIVATE_KEY: requireEnvVar("TEST_PRIVATE_KEY"), + TOKEN_CONTRACT: requireEnvVar("TOKEN_CONTRACT"), + ORACLE_CONTRACT: requireEnvVar("ORACLE_CONTRACT"), + ENDPOINT: requireEnvVar("ENDPOINT"), +} as const; + +// Define EXPIRED_AT as a constant +const EXPIRED_AT = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours from now + +describe("getTask Tests", () => { + let ownerAddress: string; + let client: Client; + + beforeAll(async () => { + ownerAddress = await getAddress(TEST_PRIVATE_KEY); + console.log("Client endpoint:", ENDPOINT, "\nOwner address:", ownerAddress); + + // Initialize the client with test credentials + client = new Client({ + endpoint: ENDPOINT, + }); + }); + + describe("Auth with Signature", () => { + let authKey: string; + let smartWallet: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should get task when authenticated with signature", async () => { + const result = await client.getTask(createdTaskId, { authKey }); + console.log("first test", result); + + // Check if the result is an object and has the expected properties + expect(result).toBeDefined(); + expect(result.status).toBe(0); + expect(result.id).toBe(createdTaskId); + expect(result.smartAccountAddress).toBe(smartWallet); + expect(result.trigger).toBeDefined(); + expect(result.expiredAt).toBeDefined(); + }); + + test("should return undefined when getting an non-existent task", async () => { + // This fails because the current error message is "2 UNKNOWN: Key not found", which is not a clear error message + const result = await client.getTask("non-existent-task-id", { authKey }); + + expect(result).toEqual(undefined); + }); + }); + + describe("Auth with API key", () => { + let authKey: string; + let smartWallet: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with API key ..."); + const res = await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should get task when authenticated with API key", async () => { + const result = await client.getTask(createdTaskId, { authKey }); + expect(result).toBe(true); + + const listRes = await client.listTasks(smartWallet, { authKey }); + expect(Array.isArray(listRes.tasks)).toBe(true); + expect(listRes.tasks.some((task) => task.id === createdTaskId)).toBe( + false + ); + }); + + test("should return undefined when getting an non-existent task", async () => { + const result = await client.getTask("non-existent-task-id", { authKey }); + expect(result).toEqual(undefined); + }); + }); + + describe("Without authentication", () => { + let smartWallet: string; + let authKey: string; + let createdTaskId: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + + createdTaskId = createTaskRes.id; + }); + + test("should throw error when getting a task without authentication", async () => { + await expect( + client.getTask(createdTaskId, { authKey: "" }) + ).rejects.toThrow("missing auth header"); + }); + }); +}); diff --git a/tests/listTasks.test.ts b/tests/listTasks.test.ts index afbdbca..b3e09b0 100644 --- a/tests/listTasks.test.ts +++ b/tests/listTasks.test.ts @@ -15,11 +15,11 @@ const { ORACLE_CONTRACT, ENDPOINT, } = { - TEST_API_KEY: requireEnvVar('TEST_API_KEY'), - TEST_PRIVATE_KEY: requireEnvVar('TEST_PRIVATE_KEY'), - TOKEN_CONTRACT: requireEnvVar('TOKEN_CONTRACT'), - ORACLE_CONTRACT: requireEnvVar('ORACLE_CONTRACT'), - ENDPOINT: requireEnvVar('ENDPOINT'), + TEST_API_KEY: requireEnvVar("TEST_API_KEY"), + TEST_PRIVATE_KEY: requireEnvVar("TEST_PRIVATE_KEY"), + TOKEN_CONTRACT: requireEnvVar("TOKEN_CONTRACT"), + ORACLE_CONTRACT: requireEnvVar("ORACLE_CONTRACT"), + ENDPOINT: requireEnvVar("ENDPOINT"), } as const; // Define EXPIRED_AT as a constant @@ -27,109 +27,135 @@ const EXPIRED_AT = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours fro describe("listTasks Tests", () => { let ownerAddress: string; + let client: Client; beforeAll(async () => { ownerAddress = await getAddress(TEST_PRIVATE_KEY); + console.log("Client endpoint:", ENDPOINT, "\nOwner address:", ownerAddress); + + // Initialize the client with test credentials + client = new Client({ + endpoint: ENDPOINT, + }); }); describe("Auth with Signature", () => { - let client: Client; - let createdTaskId: string; + let authKey: string; let smartWallet: string; + let createdTaskId: string; beforeAll(async () => { - // Initialize the client with test credentials - client = new Client({ - endpoint: ENDPOINT, - }); - - console.log("Authenticating with signature ...") - const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); - await client.authWithSignature(ownerAddress, signature, EXPIRED_AT); - + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); - const getAddressesRes = await client.getAddresses(ownerAddress); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); smartWallet = getAddressesRes.smart_account_address; console.log(`Smart wallet created: ${smartWallet}`); - console.log("Creating a task to use for the following tests") - const createTaskRes = await client.createTask({ - address: smartWallet, - tokenContract: TOKEN_CONTRACT, - oracleContract: ORACLE_CONTRACT, - }); - + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + createdTaskId = createTaskRes.id; }); - + test("should list tasks when authenticated with signature", async () => { - const result = await client.listTasks(smartWallet); + const result = await client.listTasks(smartWallet, { authKey }); expect(Array.isArray(result.tasks)).toBe(true); - expect(result.tasks.some(task => task.id === createdTaskId)).toBe(true); + expect(result.tasks.some((task) => task.id === createdTaskId)).toBe(true); }); test("should return empty when listing owner address using signature", async () => { - const result = await client.listTasks(ownerAddress); + const result = await client.listTasks(ownerAddress, { authKey }); expect(Array.isArray(result.tasks)).toBe(true); expect(result.tasks.length).toBe(0); }); }); describe("Auth with API key", () => { - let client: Client; - let createdTaskId: string; + let authKey: string; let smartWallet: string; + let createdTaskId: string; beforeAll(async () => { - // Initialize the client with test credentials - client = new Client({ - endpoint: ENDPOINT, - }); - - console.log("Authenticating with API key ...") - await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + console.log("Authenticating with API key ..."); + const res = await client.authWithAPIKey(TEST_API_KEY, EXPIRED_AT); + authKey = res.authKey; console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); - const getAddressesRes = await client.getAddresses(ownerAddress); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); smartWallet = getAddressesRes.smart_account_address; console.log(`Smart wallet created: ${smartWallet}`); - console.log("Creating a task to use for the following tests") - const createTaskRes = await client.createTask({ - address: smartWallet, - tokenContract: TOKEN_CONTRACT, - oracleContract: ORACLE_CONTRACT, - }); - + console.log("Creating a task to use for the following tests"); + const createTaskRes = await client.createTask( + { + address: smartWallet, + tokenContract: TOKEN_CONTRACT, + oracleContract: ORACLE_CONTRACT, + }, + { authKey } + ); + createdTaskId = createTaskRes.id; }); - + test("should list tasks when authenticated with API key", async () => { - const result = await client.listTasks(smartWallet); + const result = await client.listTasks(smartWallet, { authKey }); expect(Array.isArray(result.tasks)).toBe(true); - expect(result.tasks.some(task => task.id === createdTaskId)).toBe(true); + expect(result.tasks.some((task) => task.id === createdTaskId)).toBe(true); }); test("should return empty when listing owner address using API key", async () => { - const result = await client.listTasks(ownerAddress); + const result = await client.listTasks(ownerAddress, { authKey }); expect(Array.isArray(result.tasks)).toBe(true); expect(result.tasks.length).toBe(0); }); }); - test("should throw error when creating a task without authentication", async () => { - const clientWithoutAuth = new Client({ - endpoint: ENDPOINT, - }); + describe("Without authentication", () => { + let smartWallet: string; + let authKey: string; + + beforeAll(async () => { + console.log("Authenticating with signature ..."); + const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT); + const res = await client.authWithSignature( + ownerAddress, + signature, + EXPIRED_AT + ); + authKey = res.authKey; - const smartWallet = await getAddress(TEST_PRIVATE_KEY); + console.log(`Retrieving smart wallet for owner ${ownerAddress} ...`); + const getAddressesRes = await client.getAddresses(ownerAddress, { + authKey, + }); + smartWallet = getAddressesRes.smart_account_address; + console.log(`Smart wallet created: ${smartWallet}`); + }); - await expect(clientWithoutAuth.createTask({ - address: smartWallet, - tokenContract: TOKEN_CONTRACT, - oracleContract: ORACLE_CONTRACT, - })).rejects.toThrow( - "missing auth header" - ); + test("should throw error when listing tasks without authentication", async () => { + await expect( + client.listTasks(smartWallet, { authKey: "" }) + ).rejects.toThrow("missing auth header"); + }); }); });