diff --git a/packages/contracts-sdk/src/lib/contracts-sdk.ts b/packages/contracts-sdk/src/lib/contracts-sdk.ts index a616a2f79..44582a271 100644 --- a/packages/contracts-sdk/src/lib/contracts-sdk.ts +++ b/packages/contracts-sdk/src/lib/contracts-sdk.ts @@ -620,18 +620,18 @@ export class LitContracts { }; /** - * Retrieves the PriceFeed contract instance based on the provided network, context, and RPC URL. - * If a context is provided, it determines if a contract resolver is used for bootstrapping contracts. - * If a resolver address is present in the context, it retrieves the PriceFeed contract from the contract resolver instance. - * Otherwise, it retrieves the PriceFeed contract using the contract address and ABI. - * Throws an error if required contract data is missing or if the PriceFeed contract cannot be obtained. - * - * @param network - The network key. - * @param context - The contract context or contract resolver context. - * @param rpcUrl - The RPC URL. - * @returns The PriceFeed contract instance. - * @throws Error if required contract data is missing or if the PriceFeed contract cannot be obtained. - */ + * Retrieves the PriceFeed contract instance based on the provided network, context, and RPC URL. + * If a context is provided, it determines if a contract resolver is used for bootstrapping contracts. + * If a resolver address is present in the context, it retrieves the PriceFeed contract from the contract resolver instance. + * Otherwise, it retrieves the PriceFeed contract using the contract address and ABI. + * Throws an error if required contract data is missing or if the PriceFeed contract cannot be obtained. + * + * @param network - The network key. + * @param context - The contract context or contract resolver context. + * @param rpcUrl - The RPC URL. + * @returns The PriceFeed contract instance. + * @throws Error if required contract data is missing or if the PriceFeed contract cannot be obtained. + */ public static async getPriceFeedContract( network: LIT_NETWORKS_KEYS, context?: LitContractContext | LitContractResolverContext, @@ -1083,7 +1083,7 @@ export class LitContracts { * "https://192.168.1.1:443", * "http://192.168.1.2:80" * ] - */ + */ public static generateValidatorURLs({ activeValidatorStructs, nodeProtocol, @@ -1132,7 +1132,7 @@ export class LitContracts { networkContext, rpcUrl, nodeProtocol, - sortByPrice + sortByPrice, }: { litNetwork: LIT_NETWORKS_KEYS; networkContext?: LitContractContext | LitContractResolverContext; @@ -1146,7 +1146,6 @@ export class LitContracts { bootstrapUrls: string[]; priceByNetwork: Record; }> => { - // if it's true, we will sort the networks by price feed from lowest to highest // if it's false, we will not sort the networks let _sortByPrice = sortByPrice || true; @@ -1202,9 +1201,10 @@ export class LitContracts { const unsortedNetworks = LitContracts.generateValidatorURLs({ activeValidatorStructs, litNetwork, - }) + }); - // networks are all the nodes we know, but we also want to sort it by price feed + // networks are all the nodes we know from the `getActiveUnkickedValidatorStructsAndCounts` function, but we also want to sort it by price feed + // which we need to call the price feed contract const priceFeedInfo = await LitContracts.getPriceFeedInfo({ litNetwork, networkContext, @@ -1220,13 +1220,13 @@ export class LitContracts { const PRICE_BY_NETWORK = priceFeedInfo.networkPrices.mapByAddress; // sorted networks by prices (lowest to highest) - // [ + // [ // 'http://xxx:7470', <-- lowest price // 'http://zzz:7472', <-- middle price // 'http://yyy:7471' <-- highest price // ] - const sortedNetworks = unsortedNetworks.sort((a, b) => - PRICE_BY_NETWORK[a] - PRICE_BY_NETWORK[b] + const sortedNetworks = unsortedNetworks.sort( + (a, b) => PRICE_BY_NETWORK[a] - PRICE_BY_NETWORK[b] ); const bootstrapUrls = _sortByPrice ? sortedNetworks : unsortedNetworks; @@ -1246,64 +1246,72 @@ export class LitContracts { rpcUrl, productIds, // Array of product IDs }: { - litNetwork: LIT_NETWORKS_KEYS, + litNetwork: LIT_NETWORKS_KEYS; networkContext?: LitContractContext | LitContractResolverContext; rpcUrl?: string; nodeProtocol?: typeof HTTP | typeof HTTPS | null; productIds?: number[]; }) => { - if (!productIds || productIds.length === 0) { log('No product IDs provided. Defaulting to 0'); // You should use all [0,1,2] because we fetch the price first to connect to the cheapest node. And after that the user calls the actual function - productIds = [0, 1, 2] + productIds = [0, 1, 2]; } const priceFeedContract = await LitContracts.getPriceFeedContract( litNetwork, networkContext, - rpcUrl, - ) + rpcUrl + ); - const nodesForRequest = await priceFeedContract['getNodesForRequest'](productIds); + const nodesForRequest = await priceFeedContract['getNodesForRequest']( + productIds + ); const epochId = nodesForRequest[0].toNumber(); const minNodeCount = nodesForRequest[1].toNumber(); const nodesAndPrices = nodesForRequest[2]; - const activeValidatorStructs: ValidatorStruct[] = nodesAndPrices.map((item: any) => { - return { - ip: item.validator.ip, - ipv6: item.validator.ipv6, - port: item.validator.port, - nodeAddress: item.validator.nodeAddress, - reward: item.validator.reward, - seconderPubkey: item.validator.seconderPubkey, - receiverPubkey: item.validator.receiverPubkey, + const activeValidatorStructs: ValidatorStruct[] = nodesAndPrices.map( + (item: any) => { + return { + ip: item.validator.ip, + ipv6: item.validator.ipv6, + port: item.validator.port, + nodeAddress: item.validator.nodeAddress, + reward: item.validator.reward, + seconderPubkey: item.validator.seconderPubkey, + receiverPubkey: item.validator.receiverPubkey, + }; } - }); + ); const networks = LitContracts.generateValidatorURLs({ activeValidatorStructs, litNetwork, - }) + }); - console.log("networks:", networks); + console.log('networks:', networks); const prices = nodesAndPrices.flatMap((item: any) => { // Flatten the nested prices array and convert BigNumber to number - return item.prices.map((price: ethers.BigNumber) => parseFloat(price.toString())); + return item.prices.map((price: ethers.BigNumber) => + parseFloat(price.toString()) + ); }); - console.log("Prices as numbers:", prices); + console.log('Prices as numbers:', prices); - const networkPriceMap: Record = networks.reduce((acc: any, network, index) => { - acc[network] = prices[index]; - return acc; - }, {}); + const networkPriceMap: Record = networks.reduce( + (acc: any, network, index) => { + acc[network] = prices[index]; + return acc; + }, + {} + ); - console.log("Network to Price Map:", networkPriceMap); + console.log('Network to Price Map:', networkPriceMap); const networkPriceObjArr = networks.map((network, index) => { return { @@ -1317,10 +1325,10 @@ export class LitContracts { minNodeCount, networkPrices: { arr: networkPriceObjArr, - mapByAddress: networkPriceMap + mapByAddress: networkPriceMap, }, - } - } + }; + }; private static async _resolveContractContext( network: LIT_NETWORK_VALUES diff --git a/packages/core/src/lib/lit-core.ts b/packages/core/src/lib/lit-core.ts index d17684631..2f296e690 100644 --- a/packages/core/src/lib/lit-core.ts +++ b/packages/core/src/lib/lit-core.ts @@ -116,7 +116,7 @@ export type LitNodeClientConfigWithDefaults = Required< nodeProtocol?: typeof HTTP | typeof HTTPS | null; } & { priceByNetwork: Record; // eg. - } + }; // On epoch change, we wait this many seconds for the nodes to update to the new epoch before using the new epoch # const EPOCH_PROPAGATION_DELAY = 45_000; @@ -260,14 +260,19 @@ export class LitCore { bootstrapUrls: string[]; priceByNetwork: Record; }> { - const { stakingContract, epochInfo, minNodeCount, bootstrapUrls, priceByNetwork } = - await LitContracts.getConnectionInfo({ - litNetwork: this.config.litNetwork, - networkContext: this.config.contractContext, - rpcUrl: this.config.rpcUrl, - nodeProtocol: this.config.nodeProtocol, - sortByPrice: true - }); + const { + stakingContract, + epochInfo, + minNodeCount, + bootstrapUrls, + priceByNetwork, + } = await LitContracts.getConnectionInfo({ + litNetwork: this.config.litNetwork, + networkContext: this.config.contractContext, + rpcUrl: this.config.rpcUrl, + nodeProtocol: this.config.nodeProtocol, + sortByPrice: true, + }); // Validate minNodeCount if (!minNodeCount) { @@ -297,7 +302,7 @@ export class LitCore { epochInfo, minNodeCount, bootstrapUrls, - priceByNetwork + priceByNetwork, }; } @@ -706,9 +711,11 @@ export class LitCore { await Promise.race([ new Promise((_resolve, reject) => { timeoutHandle = setTimeout(() => { - const msg = `Error: Could not handshake with nodes after timeout of ${this.config.connectTimeout - }ms. Could only connect to ${Object.keys(serverKeys).length} of ${this.config.bootstrapUrls.length - } nodes. Please check your network connection and try again. Note that you can control this timeout with the connectTimeout config option which takes milliseconds.`; + const msg = `Error: Could not handshake with nodes after timeout of ${ + this.config.connectTimeout + }ms. Could only connect to ${Object.keys(serverKeys).length} of ${ + this.config.bootstrapUrls.length + } nodes. Please check your network connection and try again. Note that you can control this timeout with the connectTimeout config option which takes milliseconds.`; try { throw new InitError({}, msg); @@ -1036,8 +1043,8 @@ export class LitCore { this._epochCache.currentNumber && this._epochCache.startTime && Math.floor(Date.now() / 1000) < - this._epochCache.startTime + - Math.floor(EPOCH_PROPAGATION_DELAY / 1000) && + this._epochCache.startTime + + Math.floor(EPOCH_PROPAGATION_DELAY / 1000) && this._epochCache.currentNumber >= 3 // FIXME: Why this check? ) { return this._epochCache.currentNumber - 1; @@ -1068,7 +1075,7 @@ export class LitCore { data, requestId, }: // eslint-disable-next-line @typescript-eslint/no-explicit-any - SendNodeCommand): Promise => { + SendNodeCommand): Promise => { // FIXME: Replace usage with explicit, strongly typed handlers data = { ...data, epoch: this.currentEpochNumber }; diff --git a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts index ecdc9f9ee..b0cfc219e 100644 --- a/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts +++ b/packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts @@ -137,7 +137,8 @@ import { LitContracts } from '@lit-protocol/contracts-sdk'; export class LitNodeClientNodeJs extends LitCore - implements LitClientSessionManager, ILitNodeClient { + implements LitClientSessionManager, ILitNodeClient +{ defaultAuthCallback?: (authSigParams: AuthCallbackParams) => Promise; // ========== Constructor ========== @@ -1164,8 +1165,8 @@ export class LitNodeClientNodeJs // -- optional params ...(params.authMethods && params.authMethods.length > 0 && { - authMethods: params.authMethods, - }), + authMethods: params.authMethods, + }), nodeSet, }; @@ -1898,8 +1899,8 @@ export class LitNodeClientNodeJs const sessionCapabilityObject = params.sessionCapabilityObject ? params.sessionCapabilityObject : await this.generateSessionCapabilityObjectWithWildcards( - params.resourceAbilityRequests.map((r) => r.resource) - ); + params.resourceAbilityRequests.map((r) => r.resource) + ); const expiration = params.expiration || LitNodeClientNodeJs.getExpiration(); // -- (TRY) to get the wallet signature @@ -1981,19 +1982,18 @@ export class LitNodeClientNodeJs const capabilities = params.capacityDelegationAuthSig ? [ - ...(params.capabilityAuthSigs ?? []), - params.capacityDelegationAuthSig, - authSig, - ] + ...(params.capabilityAuthSigs ?? []), + params.capacityDelegationAuthSig, + authSig, + ] : [...(params.capabilityAuthSigs ?? []), authSig]; - // Get new price feed info from the contract if user wants to let priceByNetwork = this.config.priceByNetwork; if (params.getNewPrices) { - log(`Getting new prices from the contract`) + log(`Getting new prices from the contract`); const priceFeedInfo = await LitContracts.getPriceFeedInfo({ litNetwork: this.config.litNetwork, networkContext: this.config.contractContext, @@ -2002,7 +2002,6 @@ export class LitNodeClientNodeJs priceByNetwork = priceFeedInfo.networkPrices.mapByAddress; } - // This is the template that will be combined with the node address as a single object, then signed by the session key // so that the node can verify the session signature const sessionSigningTemplate = { diff --git a/packages/types/src/lib/interfaces.ts b/packages/types/src/lib/interfaces.ts index f1b3ee7c0..81524d0c6 100644 --- a/packages/types/src/lib/interfaces.ts +++ b/packages/types/src/lib/interfaces.ts @@ -251,7 +251,7 @@ export interface JsonPkpSignSdkParams extends BaseJsonPkpSignRequest { */ export interface JsonPkpSignRequest extends BaseJsonPkpSignRequest, - NodeSetRequired { + NodeSetRequired { authSig: AuthSig; /** @@ -296,8 +296,8 @@ export interface NodeSetRequired { export interface JsonSignSessionKeyRequestV1 extends Pick, - Pick, - NodeSetRequired { + Pick, + NodeSetRequired { sessionKey: string; authMethods: AuthMethod[]; pkpPublicKey?: string; @@ -481,7 +481,7 @@ export interface JsonExecutionSdkParamsTargetNode export interface JsonExecutionSdkParams extends Pick, - ExecuteJsAdvancedOptions { + ExecuteJsAdvancedOptions { /** * JS code to run on the nodes */ @@ -527,7 +527,7 @@ export interface JsonExecutionRequestTargetNode extends JsonExecutionRequest { export interface JsonExecutionRequest extends Pick, - NodeSetRequired { + NodeSetRequired { authSig: AuthSig; /** @@ -558,7 +558,7 @@ export interface SessionSigsOrAuthSig { export interface DecryptRequestBase extends SessionSigsOrAuthSig, - MultipleAccessControlConditions { + MultipleAccessControlConditions { /** * The chain name of the chain that this contract is deployed on. See LIT_CHAINS for currently supported chains. */ @@ -604,7 +604,7 @@ export interface EncryptFileRequest extends DecryptRequestBase { file: AcceptedFileType; } -export interface DecryptRequest extends EncryptResponse, DecryptRequestBase { } +export interface DecryptRequest extends EncryptResponse, DecryptRequestBase {} export interface DecryptResponse { // The decrypted data as a Uint8Array @@ -626,10 +626,10 @@ export interface SigResponse { export interface ExecuteJsResponseBase { signatures: - | { - sig: SigResponse; - } - | any; + | { + sig: SigResponse; + } + | any; } /** @@ -659,7 +659,7 @@ export interface ExecuteJsNoSigningResponse extends ExecuteJsResponseBase { logs: string; } -export interface LitNodePromise { } +export interface LitNodePromise {} export interface SendNodeCommand { url: string; @@ -668,11 +668,11 @@ export interface SendNodeCommand { } export interface SigShare { sigType: - | 'BLS' - | 'K256' - | 'ECDSA_CAIT_SITH' // Legacy alias of K256 - | 'EcdsaCaitSithP256' - | 'EcdsaK256Sha256'; + | 'BLS' + | 'K256' + | 'ECDSA_CAIT_SITH' // Legacy alias of K256 + | 'EcdsaCaitSithP256' + | 'EcdsaK256Sha256'; signatureShare: string; shareIndex?: number; @@ -1117,7 +1117,7 @@ export interface CommonGetSessionSigsProps { export interface BaseProviderGetSessionSigsProps extends CommonGetSessionSigsProps, - LitActionSdkParams { + LitActionSdkParams { /** * This is a callback that will be used to generate an AuthSig within the session signatures. It's inclusion is required, as it defines the specific resources and abilities that will be allowed for the current session. */ @@ -1126,7 +1126,7 @@ export interface BaseProviderGetSessionSigsProps export interface GetSessionSigsProps extends CommonGetSessionSigsProps, - LitActionSdkParams { + LitActionSdkParams { /** * This is a callback that will be used to generate an AuthSig within the session signatures. It's inclusion is required, as it defines the specific resources and abilities that will be allowed for the current session. */ @@ -1627,7 +1627,7 @@ export interface BaseProviderSessionSigsParams { resourceAbilityRequests?: LitResourceAbilityRequest[]; } -export interface BaseAuthenticateOptions { } +export interface BaseAuthenticateOptions {} export interface EthWalletAuthenticateOptions extends BaseAuthenticateOptions { /** @@ -1693,9 +1693,9 @@ export interface MintCapacityCreditsPerKilosecond } export interface MintCapacityCreditsContext extends MintCapacityCreditsPerDay, - MintCapacityCreditsPerSecond, - MintCapacityCreditsPerKilosecond, - GasLimitParam { } + MintCapacityCreditsPerSecond, + MintCapacityCreditsPerKilosecond, + GasLimitParam {} export interface MintCapacityCreditsRes { rliTxHash: string; capacityTokenId: any; @@ -1818,12 +1818,12 @@ export interface LitActionSdkParams { * An object that contains params to expose to the Lit Action. These will be injected to the JS runtime before your code runs, so you can use any of these as normal variables in your Lit Action. */ jsParams?: - | { - [key: string]: any; - publicKey?: string; - sigName?: string; - } - | any; + | { + [key: string]: any; + publicKey?: string; + sigName?: string; + } + | any; } export interface LitEndpoint { @@ -1845,7 +1845,7 @@ export interface SignerLike { export interface GetPkpSessionSigs extends CommonGetSessionSigsProps, - LitActionSdkParams { + LitActionSdkParams { pkpPublicKey: string; /** @@ -1871,11 +1871,11 @@ export type GetLitActionSessionSigs = CommonGetSessionSigsProps & Pick, 'jsParams'> & ( | (Pick, 'litActionCode'> & { - litActionIpfsId?: never; - }) + litActionIpfsId?: never; + }) | (Pick, 'litActionIpfsId'> & { - litActionCode?: never; - }) + litActionCode?: never; + }) ) & { ipfsOptions?: IpfsOptions; };