Skip to content

Commit

Permalink
PRT-751 Fixing issue with first LOL relay adding and reorganizing a f…
Browse files Browse the repository at this point in the history
…ew methods / classes (#610)
  • Loading branch information
ranlavanet authored Jul 12, 2023
1 parent 8b6232c commit 608b427
Show file tree
Hide file tree
Showing 20 changed files with 656 additions and 322 deletions.
2 changes: 1 addition & 1 deletion ecosystem/lava-sdk/bin/src/badge/fetchBadge.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class BadgeManager {
if (code == grpc_web_1.grpc.Code.OK || msg == undefined) {
return;
}
reject(new Error(msg));
reject(new Error("Failed fetching a badge from the badge server, message: " + msg));
},
});
});
Expand Down
18 changes: 16 additions & 2 deletions ecosystem/lava-sdk/bin/src/lavaOverLava/providers.d.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
import { ConsumerSessionWithProvider, SessionManager } from "../types/types";
import Relayer from "../relayer/relayer";
import { Badge } from "../grpc_web_services/pairing/relay_pb";
import { QueryShowAllChainsResponse } from "../codec/spec/query";
export interface LavaProvidersOptions {
accountAddress: string;
network: string;
relayer: Relayer | null;
geolocation: string;
debug?: boolean;
}
export declare class LavaProviders {
private providers;
private network;
private index;
private accountAddress;
private relayer;
private geolocation;
constructor(accountAddress: string, network: string, relayer: Relayer | null, geolocation: string);
private debugMode;
constructor(options: LavaProvidersOptions);
updateLavaProvidersRelayersBadge(badge: Badge | undefined): void;
init(pairingListConfig: string): Promise<void>;
showAllChains(): Promise<QueryShowAllChainsResponse>;
initDefaultConfig(): Promise<any>;
initLocalConfig(path: string): Promise<any>;
GetLavaProviders(): ConsumerSessionWithProvider[];
GetNextLavaProvider(): ConsumerSessionWithProvider;
getSession(chainID: string, rpcInterface: string): Promise<SessionManager>;
getSession(chainID: string, rpcInterface: string, badge?: Badge): Promise<SessionManager>;
private debugPrint;
pickRandomProviders(providers: Array<ConsumerSessionWithProvider>): ConsumerSessionWithProvider[];
pickRandomProvider(providers: Array<ConsumerSessionWithProvider>): ConsumerSessionWithProvider;
private getPairingFromChain;
private getMaxCuForUser;
private getServiceApis;
convertRestApiName(name: string): string;
SendRelayToAllProvidersAndRace(options: any, relayCu: number, rpcInterface: string): Promise<any>;
SendRelayWithRetry(options: any, lavaRPCEndpoint: ConsumerSessionWithProvider, relayCu: number, rpcInterface: string): Promise<any>;
private extractBlockNumberFromError;
}
208 changes: 146 additions & 62 deletions ecosystem/lava-sdk/bin/src/lavaOverLava/providers.js

Large diffs are not rendered by default.

16 changes: 14 additions & 2 deletions ecosystem/lava-sdk/bin/src/lavaOverLava/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ it("Test convertRestApiName method", () => {
output: "/lavanet/lava/pairing/verify_pairing/[^/s]+/[^/s]+/[^/s]+/[^/s]+",
},
];
const lavaProviders = new providers_1.LavaProviders("", "", null, default_1.DEFAULT_GEOLOCATION);
const options = {
accountAddress: "",
network: "",
relayer: null,
geolocation: default_1.DEFAULT_GEOLOCATION,
};
const lavaProviders = new providers_1.LavaProviders(options);
testCasses.map((test) => {
expect(lavaProviders.convertRestApiName(test.name)).toBe(test.output);
});
Expand All @@ -49,7 +55,13 @@ it("Test pickRandomProvider method", () => {
shouldFail: true,
},
];
const lavaProviders = new providers_1.LavaProviders("", "", null, default_1.DEFAULT_GEOLOCATION);
const options = {
accountAddress: "",
network: "",
relayer: null,
geolocation: default_1.DEFAULT_GEOLOCATION,
};
const lavaProviders = new providers_1.LavaProviders(options);
testCasses.map((test) => {
const consumerSessionWithProviderArr = [
// default consumer session with provider with only compute units set
Expand Down
1 change: 1 addition & 0 deletions ecosystem/lava-sdk/bin/src/relayer/relayer.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ declare class Relayer {
private prefix;
private badge?;
constructor(chainID: string, privKey: string, lavaChainId: string, secure: boolean, badge?: Badge);
setBadge(badge: Badge | undefined): void;
sendRelay(options: SendRelayOptions, consumerProviderSession: ConsumerSessionWithProvider, cuSum: number, apiInterface: string): Promise<RelayReply>;
extractErrorMessage(error: string): string;
relayWithTimeout(timeLimit: number, task: any): Promise<any>;
Expand Down
10 changes: 9 additions & 1 deletion ecosystem/lava-sdk/bin/src/relayer/relayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ class Relayer {
}
this.badge = badge;
}
// when an epoch changes we need to update the badge
setBadge(badge) {
if (this.badge && !badge) {
// we have a badge and trying to set it to undefined
throw new Error("Trying to set an undefined badge to an existing badge, bad flow");
}
this.badge = badge;
}
sendRelay(options, consumerProviderSession, cuSum, apiInterface) {
return __awaiter(this, void 0, void 0, function* () {
// Extract attributes from options
Expand Down Expand Up @@ -129,7 +137,7 @@ class Relayer {
},
});
});
return this.relayWithTimeout(2000, requestPromise);
return this.relayWithTimeout(5000, requestPromise);
});
}
extractErrorMessage(error) {
Expand Down
9 changes: 7 additions & 2 deletions ecosystem/lava-sdk/bin/src/sdk/sdk.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,24 @@ export interface LavaSDKOptions {
geolocation?: string;
lavaChainId?: string;
secure?: boolean;
debug?: boolean;
}
export declare class LavaSDK {
private privKey;
private walletAddress;
private chainID;
private rpcInterface;
private network;
private pairingListConfig;
private geolocation;
private lavaChainId;
private badgeManager;
private currentEpochBadge;
private lavaProviders;
private account;
private relayer;
private secure;
private debugMode;
private activeSessionManager;
/**
* Create Lava-SDK instance
Expand All @@ -54,6 +58,9 @@ export declare class LavaSDK {
*/
constructor(options: LavaSDKOptions);
static create(options: LavaSDKOptions): Promise<LavaSDK>;
private debugPrint;
private fetchNewBadge;
private initLavaProviders;
private init;
private handleRpcRelay;
private handleRestRelay;
Expand All @@ -68,11 +75,9 @@ export declare class LavaSDK {
*
*/
sendRelay(options: SendRelayOptions | SendRestRelayOptions): Promise<string>;
private generateRPCData;
private decodeRelayResponse;
private getCuSumForMethod;
private getConsumerProviderSession;
private newEpochStarted;
private isRest;
private base64ToUint8Array;
}
136 changes: 72 additions & 64 deletions ecosystem/lava-sdk/bin/src/sdk/sdk.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ const errors_1 = __importDefault(require("./errors"));
const relayer_1 = __importDefault(require("../relayer/relayer"));
const fetchBadge_1 = require("../badge/fetchBadge");
const chains_1 = require("../util/chains");
const common_1 = require("../util/common");
const providers_1 = require("../lavaOverLava/providers");
const default_1 = require("../config/default");
const query_1 = require("../codec/spec/query");
class LavaSDK {
/**
* Create Lava-SDK instance
Expand All @@ -33,10 +33,6 @@ class LavaSDK {
* @returns A promise that resolves when the LavaSDK has been successfully initialized, returns LavaSDK object.
*/
constructor(options) {
this.base64ToUint8Array = (str) => {
const buffer = Buffer.from(str, "base64");
return new Uint8Array(buffer);
};
// Extract attributes from options
const { privateKey, badge, chainID, rpcInterface } = options;
let { pairingListConfig, network, geolocation, lavaChainId } = options;
Expand All @@ -59,6 +55,7 @@ class LavaSDK {
this.chainID = chainID;
this.rpcInterface = rpcInterface ? rpcInterface : "";
this.privKey = privateKey ? privateKey : "";
this.walletAddress = "";
this.badgeManager = new fetchBadge_1.BadgeManager(badge);
this.network = network;
this.geolocation = geolocation;
Expand All @@ -68,6 +65,7 @@ class LavaSDK {
this.relayer = errors_1.default.errRelayerServiceNotInitialized;
this.lavaProviders = errors_1.default.errLavaProvidersNotInitialized;
this.activeSessionManager = errors_1.default.errSessionNotInitialized;
this.debugMode = options.debug ? options.debug : false; // enabling debug prints mainly used for development / debugging
// Init sdk
return (() => __awaiter(this, void 0, void 0, function* () {
yield this.init();
Expand All @@ -83,64 +81,80 @@ class LavaSDK {
return yield new LavaSDK(options);
});
}
init() {
debugPrint(message, ...optionalParams) {
if (this.debugMode) {
console.log(message, ...optionalParams);
}
}
fetchNewBadge() {
return __awaiter(this, void 0, void 0, function* () {
let wallet;
let badge;
if (this.badgeManager.isActive()) {
const { wallet, privKey } = yield (0, wallet_1.createDynamicWallet)();
this.privKey = privKey;
const walletAddress = (yield wallet.getConsumerAccount()).address;
const badgeResponse = yield this.badgeManager.fetchBadge(walletAddress);
if (badgeResponse instanceof Error) {
throw fetchBadge_1.TimoutFailureFetchingBadgeError;
}
badge = badgeResponse.getBadge();
const badgeSignerAddress = badgeResponse.getBadgeSignerAddress();
this.account = {
algo: "secp256k1",
address: badgeSignerAddress,
pubkey: new Uint8Array([]),
};
const badgeResponse = yield this.badgeManager.fetchBadge(this.walletAddress);
if (badgeResponse instanceof Error) {
throw fetchBadge_1.TimoutFailureFetchingBadgeError;
}
else {
wallet = yield (0, wallet_1.createWallet)(this.privKey);
this.account = yield wallet.getConsumerAccount();
return badgeResponse;
});
}
initLavaProviders(start) {
return __awaiter(this, void 0, void 0, function* () {
if (this.account instanceof Error) {
throw new Error("initLavaProviders failed: " + String(this.account));
}
// Init relayer for lava providers
const lavaRelayer = new relayer_1.default(default_1.LAVA_CHAIN_ID, this.privKey, this.lavaChainId, this.secure, badge);
// Create new instance of lava providers
const lavaProviders = yield new providers_1.LavaProviders(this.account.address, this.network, lavaRelayer, this.geolocation);
this.lavaProviders = yield new providers_1.LavaProviders({
accountAddress: this.account.address,
network: this.network,
relayer: new relayer_1.default(default_1.LAVA_CHAIN_ID, this.privKey, this.lavaChainId, this.secure, this.currentEpochBadge),
geolocation: this.geolocation,
debug: this.debugMode,
});
this.debugPrint("time took lava providers", performance.now() - start);
// Init lava providers
yield lavaProviders.init(this.pairingListConfig);
const sendRelayOptions = {
data: this.generateRPCData("abci_query", [
"/lavanet.lava.spec.Query/ShowAllChains",
"",
"0",
false,
]),
url: "",
connectionType: "",
};
const info = yield lavaProviders.SendRelayWithRetry(sendRelayOptions, lavaProviders.GetNextLavaProvider(), 10, "tendermintrpc");
const byteArrayResponse = this.base64ToUint8Array(info.result.response.value);
const parsedChainList = query_1.QueryShowAllChainsResponse.decode(byteArrayResponse);
yield this.lavaProviders.init(this.pairingListConfig);
this.debugPrint("time took lava providers init", performance.now() - start);
const parsedChainList = yield this.lavaProviders.showAllChains();
// Validate chainID
if (!(0, chains_1.isValidChainID)(this.chainID, parsedChainList)) {
throw errors_1.default.errChainIDUnsupported;
}
this.debugPrint("time took ShowAllChains", performance.now() - start);
// If rpc is not defined use default for specified chainID
this.rpcInterface =
this.rpcInterface || (0, chains_1.fetchRpcInterface)(this.chainID, parsedChainList);
this.debugPrint("time took fetchRpcInterface", performance.now() - start);
// Validate rpc interface with chain id
(0, chains_1.validateRpcInterfaceWithChainID)(this.chainID, parsedChainList, this.rpcInterface);
// Save lava providers as local attribute
this.lavaProviders = lavaProviders;
this.debugPrint("time took validateRpcInterfaceWithChainID", performance.now() - start);
// Get pairing list for current epoch
this.activeSessionManager = yield this.lavaProviders.getSession(this.chainID, this.rpcInterface);
this.activeSessionManager = yield this.lavaProviders.getSession(this.chainID, this.rpcInterface, this.currentEpochBadge);
this.debugPrint("time took getSession", performance.now() - start);
});
}
init() {
return __awaiter(this, void 0, void 0, function* () {
const start = performance.now();
if (this.badgeManager.isActive()) {
const { wallet, privKey } = yield (0, wallet_1.createDynamicWallet)();
this.privKey = privKey;
this.walletAddress = (yield wallet.getConsumerAccount()).address;
const badgeResponse = yield this.fetchNewBadge();
this.currentEpochBadge = badgeResponse.getBadge();
const badgeSignerAddress = badgeResponse.getBadgeSignerAddress();
this.account = {
algo: "secp256k1",
address: badgeSignerAddress,
pubkey: new Uint8Array([]),
};
this.debugPrint("time took to get badge from badge server", performance.now() - start);
// this.debugPrint("badge", badge);
}
else {
const wallet = yield (0, wallet_1.createWallet)(this.privKey);
this.account = yield wallet.getConsumerAccount();
}
// Create relayer for querying network
this.relayer = new relayer_1.default(this.chainID, this.privKey, this.lavaChainId, this.secure, badge);
this.relayer = new relayer_1.default(this.chainID, this.privKey, this.lavaChainId, this.secure, this.currentEpochBadge);
yield this.initLavaProviders(start);
});
}
handleRpcRelay(options) {
Expand All @@ -155,7 +169,7 @@ class LavaSDK {
const pairingList = yield this.getConsumerProviderSession();
// Get cuSum for specified method
const cuSum = this.getCuSumForMethod(method);
const data = this.generateRPCData(method, params);
const data = (0, common_1.generateRPCData)(method, params);
// Check if relay was initialized
if (this.relayer instanceof Error) {
throw errors_1.default.errRelayerServiceNotInitialized;
Expand Down Expand Up @@ -253,21 +267,6 @@ class LavaSDK {
return yield this.handleRpcRelay(options);
});
}
generateRPCData(method, params) {
const stringifyMethod = JSON.stringify(method);
const stringifyParam = JSON.stringify(params, (key, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
});
// TODO make id changable
return ('{"jsonrpc": "2.0", "id": 1, "method": ' +
stringifyMethod +
', "params": ' +
stringifyParam +
"}");
}
decodeRelayResponse(relayResponse) {
// Decode relay response
const dec = new TextDecoder();
Expand Down Expand Up @@ -303,7 +302,16 @@ class LavaSDK {
}
// Check if new epoch has started
if (this.newEpochStarted()) {
this.activeSessionManager = yield this.lavaProviders.getSession(this.chainID, this.rpcInterface);
// fetch a new badge:
if (this.badgeManager.isActive()) {
const badgeResponse = yield this.fetchNewBadge();
this.currentEpochBadge = badgeResponse.getBadge();
if (this.relayer instanceof relayer_1.default) {
this.relayer.setBadge(this.currentEpochBadge);
}
this.lavaProviders.updateLavaProvidersRelayersBadge(this.currentEpochBadge);
}
this.activeSessionManager = yield this.lavaProviders.getSession(this.chainID, this.rpcInterface, this.currentEpochBadge);
}
// Return randomized pairing list
return this.lavaProviders.pickRandomProviders(this.activeSessionManager.PairingList);
Expand Down
2 changes: 1 addition & 1 deletion ecosystem/lava-sdk/bin/src/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export declare class SessionManager {
getCuSumFromApi(name: string, chainID: string): number | undefined;
}
export declare class ConsumerSessionWithProvider {
Acc: string;
ConsumerAddress: string;
Endpoints: Array<Endpoint>;
Session: SingleConsumerSession;
MaxComputeUnits: number;
Expand Down
2 changes: 1 addition & 1 deletion ecosystem/lava-sdk/bin/src/types/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class SessionManager {
exports.SessionManager = SessionManager;
class ConsumerSessionWithProvider {
constructor(acc, endpoints, session, maxComputeUnits, usedComputeUnits, reliabilitySent) {
this.Acc = acc;
this.ConsumerAddress = acc;
this.Endpoints = endpoints;
this.Session = session;
this.MaxComputeUnits = maxComputeUnits;
Expand Down
2 changes: 2 additions & 0 deletions ecosystem/lava-sdk/bin/src/util/common.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export declare function base64ToUint8Array(str: string): Uint8Array;
export declare function generateRPCData(method: string, params: Array<any>): string;
Loading

0 comments on commit 608b427

Please sign in to comment.