@avaprotocol/sdk-js 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.cjs DELETED
@@ -1,18 +0,0 @@
1
- require('dotenv').config();
2
-
3
- module.exports = {
4
- preset: 'ts-jest/presets/default-esm',
5
- testEnvironment: 'node',
6
- moduleFileExtensions: ['ts', 'js'],
7
- testMatch: ['**/__tests__/**/*.test.ts'],
8
- transform: {
9
- '^.+\\.ts$': ['ts-jest', {
10
- useESM: true,
11
- }],
12
- },
13
- extensionsToTreatAsEsm: ['.ts'],
14
- moduleNameMapper: {
15
- '^(\\.{1,2}/.*)\\.js$': '$1',
16
- },
17
- setupFiles: ['dotenv/config'],
18
- };
@@ -1,27 +0,0 @@
1
- import { ethers } from "ethers";
2
- import { getKeyRequestMessage } from "../dist/index.js";
3
-
4
- const mnemonic = process.env.TEST_MNEMONIC;
5
- const expiredAtEpoch = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
6
-
7
- if (!mnemonic) {
8
- throw new Error("Mnemonic is required; Please set the TEST_MNEMONIC environment variable.");
9
- }
10
-
11
- const wallet = ethers.Wallet.fromPhrase(mnemonic);
12
-
13
- console.log("Address:", wallet.address, "Expired at epoch:", expiredAtEpoch);
14
- console.log("Private key:", wallet.privateKey);
15
-
16
- // Generate the key request message
17
- const message = getKeyRequestMessage(wallet.address, expiredAtEpoch);
18
-
19
- async function main() {
20
- const signature = await wallet.signMessage(message);
21
- console.log("Message:", message);
22
- console.log("Signature:", signature);
23
- }
24
-
25
- main()
26
- .catch(console.error)
27
- .finally(() => process.exit());
@@ -1,175 +0,0 @@
1
- import { describe, beforeAll, test, expect } from "@jest/globals";
2
- import Client from "../index";
3
- import dotenv from "dotenv";
4
- import path from "path";
5
- import { ethers } from "ethers";
6
- import { getKeyRequestMessage } from "../auth";
7
- import { getRpcEndpoint } from "../config";
8
-
9
- // Load environment variables from .env.test file
10
- dotenv.config({ path: path.resolve(__dirname, "../../.env.test") });
11
-
12
- const { TEST_JWT_TOKEN, TEST_PRIVATE_KEY } = process.env;
13
- const EXPIRED_AT = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
14
-
15
- // Add signature generation logic
16
- async function getAddress(privateKey: string): Promise<string> {
17
- const wallet = new ethers.Wallet(privateKey);
18
-
19
- console.log("Wallet address:", wallet.address);
20
- return wallet.address;
21
- }
22
-
23
- // Add signature generation logic
24
- async function generateSignature(
25
- privateKey: string,
26
- expiredAt: number
27
- ): Promise<string> {
28
- const wallet = new ethers.Wallet(privateKey);
29
- const message = getKeyRequestMessage(wallet.address, expiredAt);
30
-
31
- console.log("Signing message:", message, "Expired at:", expiredAt);
32
-
33
- const signature = await wallet.signMessage(message);
34
-
35
- return signature;
36
- }
37
-
38
- describe("Client E2E Tests", () => {
39
- let client: Client;
40
- let walletAddress: string; // Add this line to declare the variable
41
-
42
- beforeAll(async () => {
43
- // Initialize the client with test credentials
44
- client = new Client({
45
- endpoint: getRpcEndpoint("staging"),
46
- });
47
-
48
- if (!TEST_PRIVATE_KEY) {
49
- throw new Error("TEST_PRIVATE_KEY is not set in the .env.test file");
50
- }
51
-
52
- // Generate the address here
53
- const address = await getAddress(TEST_PRIVATE_KEY);
54
- walletAddress = address;
55
- });
56
-
57
- // test("authWithJwtToken", async () => {
58
- // if (!TEST_JWT_TOKEN) {
59
- // throw new Error("TEST_JWT_TOKEN is not set in the .env.test file");
60
- // }
61
-
62
- // const response = await client.authWithJwtToken(
63
- // walletAddress,
64
- // TEST_JWT_TOKEN,
65
- // EXPIRED_AT
66
- // );
67
-
68
- // console.log("authWithJwtToken response:", response);
69
- // expect(response).toBeDefined();
70
- // });
71
-
72
- test("authWithSignature", async () => {
73
- if (!TEST_PRIVATE_KEY) {
74
- throw new Error("TEST_PRIVATE_KEY is not set in the .env.test file");
75
- }
76
-
77
- if (!EXPIRED_AT) {
78
- throw new Error("EXPIRED_AT is not set.");
79
- }
80
-
81
- const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT);
82
-
83
- if (!signature) {
84
- throw new Error(
85
- "Signature could not be generated. Make sure TEST_PRIVATE_KEY is set in the .env.test file"
86
- );
87
- }
88
-
89
- const response = await client.authWithSignature(
90
- walletAddress,
91
- signature,
92
- EXPIRED_AT
93
- );
94
-
95
- console.log("authWithSignature response:", response);
96
-
97
- expect(response).toBeDefined();
98
- expect(response).toHaveProperty("key");
99
- expect(typeof response.key).toBe("string");
100
-
101
- // Check if the key is a valid JWT token
102
- const jwtParts = response.key.split(".");
103
- expect(jwtParts).toHaveLength(3);
104
-
105
- // Decode the base64 token and check the payload
106
- const payload = JSON.parse(Buffer.from(jwtParts[1], "base64").toString());
107
- expect(payload).toHaveProperty("iss", "AvaProtocol");
108
- expect(payload).toHaveProperty("sub");
109
- expect(payload.sub).toMatch(/^0x[a-fA-F0-9]{40}$/); // Ethereum address format
110
- expect(payload).toHaveProperty("exp", EXPIRED_AT);
111
- });
112
-
113
- // describe("Authenticated Tests", () => {
114
- // let walletAddress: string;
115
- // let client: Client;
116
-
117
- // beforeAll(async () => {
118
- // // Initialize the client with test credentials
119
- // client = new Client({
120
- // endpoint: getRpcEndpoint("staging"),
121
- // });
122
-
123
- // if (!TEST_PRIVATE_KEY) {
124
- // throw new Error("TEST_PRIVATE_KEY is not set in the .env.test file");
125
- // }
126
-
127
- // walletAddress = await getAddress(TEST_PRIVATE_KEY);
128
-
129
- // if (!EXPIRED_AT) {
130
- // throw new Error("EXPIRED_AT is not set");
131
- // }
132
-
133
- // const signature = await generateSignature(TEST_PRIVATE_KEY, EXPIRED_AT);
134
-
135
- // if (!signature) {
136
- // throw new Error(
137
- // "Signature could not be generated. Make sure TEST_PRIVATE_KEY is set in the .env.test file"
138
- // );
139
- // }
140
-
141
- // await client.authWithSignature(walletAddress, signature, EXPIRED_AT);
142
- // });
143
-
144
- // test("listTask", async () => {
145
- // const result = await client.listTask();
146
- // console.log("List task result:", result);
147
- // expect(result).toBeDefined();
148
- // // expect(Array.isArray(result)).toBe(true);
149
- // });
150
-
151
- // test("getSmartWalletAddress", async () => {
152
- // const result = await client.getSmartWalletAddress(walletAddress);
153
- // console.log("Get smart wallet address result:", result);
154
- // expect(result).toBeDefined();
155
- // expect(result.getSmartAccountAddress()).toMatch(/^0x[a-fA-F0-9]{40}$/); // Ethereum address format
156
- // expect(result).toHaveProperty("nonce");
157
- // });
158
-
159
- // test("getTask", async () => {
160
- // // First, list tasks to get a valid task ID
161
- // const listResult = await client.listTask();
162
-
163
- // console.log("List task result:", listResult);
164
- // if (listResult.getTasksList().length > 0) {
165
- // const taskId = listResult.getTasksList()[0].getId();
166
- // const result = await client.getTask(taskId);
167
- // console.log("Get task result:", result);
168
- // expect(result).toBeDefined();
169
- // expect(result.getId()).toBe(taskId);
170
- // } else {
171
- // console.warn("No tasks available to test getTask");
172
- // }
173
- // });
174
- // });
175
- });
package/src/auth.ts DELETED
@@ -1,3 +0,0 @@
1
- export const getKeyRequestMessage = (address: string, expiredAt: number): string => {
2
- return `key request for ${address} expired at ${expiredAt}`;
3
- }
package/src/config.ts DELETED
@@ -1,27 +0,0 @@
1
- import { Environment } from "./types";
2
-
3
- export const DEFAULT_JWT_EXPIRATION = 24 * 60 * 60; // 24 hours
4
- interface Config {
5
- endpoint: string;
6
- }
7
-
8
- // Define the configs object with typed keys
9
- const configs: Record<Environment, Config> = {
10
- development: {
11
- endpoint: process.env.AVS_RPC_URL || "localhost:2206",
12
- },
13
- staging: {
14
- endpoint: "aggregator-holesky.avaprotocol.org:2206",
15
- },
16
- production: {
17
- endpoint: "aggregator.avaprotocol.org:2206",
18
- },
19
- };
20
-
21
- // Function to get RPC endpoint with improved type safety
22
- export function getRpcEndpoint(env: Environment): string {
23
- return configs[env].endpoint;
24
- }
25
-
26
- // Export the configs only
27
- export { configs };
package/src/index.ts DELETED
@@ -1,198 +0,0 @@
1
- import * as grpc from "@grpc/grpc-js";
2
- import { Metadata } from "@grpc/grpc-js";
3
- import { DEFAULT_JWT_EXPIRATION, getRpcEndpoint } from "./config";
4
- import { Environment } from "./types";
5
- import { getKeyRequestMessage } from "./auth";
6
- import { AggregatorClient } from "../grpc_codegen/avs_grpc_pb";
7
- import {
8
- AddressRequest,
9
- AddressResp,
10
- GetKeyReq,
11
- KeyResp,
12
- ListTasksReq,
13
- ListTasksResp,
14
- Task,
15
- UUID,
16
- } from "../grpc_codegen/avs_pb";
17
-
18
- const grpcMetadata = new Metadata();
19
-
20
- // Move interfaces to a separate file, e.g., types.ts
21
- import { KeyExchangeResp, ClientParams } from "./types";
22
-
23
- class BaseClient {
24
- readonly endpoint: string;
25
- readonly rpcClient: AggregatorClient;
26
- // protected owner?: string;
27
- // readonly opts: ClientParams;
28
- protected adminToken?: string; // A JWT token for admin operations
29
- // protected wallet?: any;
30
-
31
- constructor(config: ClientParams) {
32
- // if (!config.jwtApiKey && !config.owner) {
33
- // throw new Error("missing jwtApiKey or owner");
34
- // }
35
-
36
- this.endpoint = config.endpoint;
37
- this.rpcClient = new AggregatorClient(
38
- config.endpoint,
39
- grpc.credentials.createInsecure()
40
- );
41
-
42
- // this.opts = clientConfig;
43
- // this.owner = clientConfig.owner ?? undefined;
44
- }
45
-
46
- // async authWithJwtToken(
47
- // address: string,
48
- // jwtToken: string,
49
- // expiredAt?: number
50
- // ): Promise<KeyExchangeResp> {
51
- // console.log("Authenticating with JWT token: ", jwtToken);
52
-
53
- // const expirationTime =
54
- // expiredAt || Math.floor(Date.now() / 1000) + DEFAULT_JWT_EXPIRATION;
55
-
56
- // const method = this.rpcClient.getKey.bind(this.rpcClient) as (
57
- // request: GetKeyReq,
58
- // metadata: Metadata | undefined,
59
- // callback: (error: grpc.ServiceError | null, response: KeyResp) => void
60
- // ) => grpc.ClientUnaryCall;
61
-
62
- // const request = new GetKeyReq()
63
- // .setOwner(address)
64
- // .setExpiredAt(expirationTime)
65
- // .setSignature(jwtToken);
66
-
67
- // const response = await this._callRPC<KeyResp, GetKeyReq>(method, request);
68
-
69
- // console.log("response:", response.getKey());
70
- // return { key: response.getKey() };
71
- // }
72
-
73
- async authWithSignature(
74
- address: string,
75
- signature: string,
76
- expiredAtEpoch: number
77
- ): Promise<KeyExchangeResp> {
78
- console.log(
79
- "Authenticating with signature:",
80
- signature,
81
- "Expired at epoch:",
82
- expiredAtEpoch
83
- );
84
-
85
- const request = new GetKeyReq()
86
- .setOwner(address)
87
- .setExpiredAt(expiredAtEpoch)
88
- .setSignature(signature);
89
-
90
- console.log("request:", request);
91
-
92
- const response = await this._callRPC<KeyResp, GetKeyReq>("getKey", request);
93
-
94
- console.log("response:", response.getKey());
95
- return { key: response.getKey() };
96
- }
97
-
98
- // protected async sendRequest<TResponse, TRequest extends object = {}>(
99
- // method: string,
100
- // request: TRequest = {} as TRequest,
101
- // metadata?: Metadata
102
- // ): Promise<TResponse> {
103
- // if (metadata === undefined) {
104
- // metadata = new grpc.Metadata();
105
- // }
106
-
107
- // if (!this.adminToken) {
108
- // throw new Error(
109
- // "Authentication required. Please call authWithJwtToken() or authWithSignature() before making requests."
110
- // );
111
- // }
112
-
113
- // metadata.add("adminToken", this.adminToken);
114
-
115
- // return this._callRPC<TResponse, TRequest>(
116
- // method as (
117
- // request: TRequest,
118
- // metadata: grpc.Metadata | undefined,
119
- // callback: (error: grpc.ServiceError | null, response: TResponse) => void
120
- // ),
121
- // request,
122
- // metadata
123
- // );
124
- // }
125
-
126
- public isAuthenticated(): boolean {
127
- return !!this.adminToken;
128
- }
129
-
130
- protected _callRPC<TResponse, TRequest extends object = {}>(
131
- methodName: string,
132
- request: TRequest,
133
- ): Promise<TResponse> {
134
- return new Promise((resolve, reject) => {
135
-
136
- const method = (this.rpcClient as any)[methodName] as (
137
- request: TRequest,
138
- metadata: grpc.Metadata | undefined,
139
- callback: (error: grpc.ServiceError | null, response: TResponse) => void
140
- ) => grpc.ClientUnaryCall;
141
-
142
- method.call(
143
- this.rpcClient,
144
- request,
145
- grpcMetadata,
146
- (error: grpc.ServiceError | null, response: TResponse) => {
147
- if (error) {
148
- reject(error);
149
- } else {
150
- resolve(response);
151
- }
152
- }
153
- );
154
- });
155
- }
156
- }
157
-
158
- export default class Client extends BaseClient {
159
- constructor(config: ClientParams) {
160
- super(config);
161
- }
162
-
163
- async listTask(): Promise<ListTasksResp> {
164
- console.log("Listing tasks");
165
-
166
- const request = new ListTasksReq();
167
-
168
- const response = await this._callRPC<ListTasksResp, ListTasksReq>(
169
- "listTasks",
170
- request
171
- );
172
-
173
- console.log("response:", response);
174
- return response;
175
- }
176
-
177
- async getSmartWalletAddress(address: string): Promise<AddressResp> {
178
- const request = new AddressRequest().setOwner(address);
179
- const response = await this._callRPC<AddressResp, AddressRequest>(
180
- "getSmartAccountAddress",
181
- request
182
- );
183
-
184
- return response;
185
- }
186
-
187
- async getTask(taskId: string): Promise<any> {
188
- const request = new UUID().setBytes(taskId);
189
- const response = await this._callRPC<Task, UUID>("getTask", request);
190
- return response;
191
- }
192
- }
193
-
194
- // Export types for easier use
195
- export * from "./types";
196
-
197
- // Add this line at the end of the file
198
- export { getKeyRequestMessage };
package/src/types.ts DELETED
@@ -1,31 +0,0 @@
1
- // Define the environment type
2
- export type Environment = "production" | "development" | "staging";
3
-
4
- export interface KeyExchangeResp {
5
- key: string;
6
- }
7
-
8
- export interface ClientParams {
9
- // used primary in backend where owner own the key
10
- // privateKey?: string;
11
-
12
- // 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.
13
- // This currently used in our telegram bot, because the bot can schedule and manage tasks for any user
14
- // It is just require the user to prove they own the wallet in initial onboarding.
15
- adminToken?: string;
16
-
17
- // used in front-end app where front-end generate the signature
18
- // presignSignature?: string;
19
- // signatureExpiredAt?: number;
20
-
21
- // env?: Environment;
22
- endpoint: string;
23
- // owner?: string;
24
- }
25
- export interface TransactionResp {
26
- hash: string;
27
- }
28
-
29
- export interface BalanceResp {
30
- balance: string;
31
- }
package/tsconfig.json DELETED
@@ -1,19 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "ESNext",
5
- "moduleResolution": "node",
6
- "esModuleInterop": true,
7
- "strict": true,
8
- "outDir": "./dist",
9
- "declaration": true,
10
- "rootDir": "src",
11
- "paths": {
12
- "@avaprotocol/*": ["./packages/*"]
13
- }
14
- },
15
- "include": ["src/**/*"],
16
- "ts-node": {
17
- "esm": true
18
- }
19
- }