Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Ansonhkg committed Dec 20, 2024
1 parent d97f177 commit b532c39
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 110 deletions.
104 changes: 56 additions & 48 deletions packages/contracts-sdk/src/lib/contracts-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1083,7 +1083,7 @@ export class LitContracts {
* "https://192.168.1.1:443",
* "http://192.168.1.2:80"
* ]
*/
*/
public static generateValidatorURLs({
activeValidatorStructs,
nodeProtocol,
Expand Down Expand Up @@ -1132,7 +1132,7 @@ export class LitContracts {
networkContext,
rpcUrl,
nodeProtocol,
sortByPrice
sortByPrice,
}: {
litNetwork: LIT_NETWORKS_KEYS;
networkContext?: LitContractContext | LitContractResolverContext;
Expand All @@ -1146,7 +1146,6 @@ export class LitContracts {
bootstrapUrls: string[];
priceByNetwork: Record<string, number>;
}> => {

// 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;
Expand Down Expand Up @@ -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,
Expand All @@ -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;
Expand All @@ -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<string, number> = networks.reduce((acc: any, network, index) => {
acc[network] = prices[index];
return acc;
}, {});
const networkPriceMap: Record<string, number> = 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 {
Expand All @@ -1317,10 +1325,10 @@ export class LitContracts {
minNodeCount,
networkPrices: {
arr: networkPriceObjArr,
mapByAddress: networkPriceMap
mapByAddress: networkPriceMap,
},
}
}
};
};

private static async _resolveContractContext(
network: LIT_NETWORK_VALUES
Expand Down
39 changes: 23 additions & 16 deletions packages/core/src/lib/lit-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export type LitNodeClientConfigWithDefaults = Required<
nodeProtocol?: typeof HTTP | typeof HTTPS | null;
} & {
priceByNetwork: Record<string, number>; // eg. <nodeAddress, price>
}
};

// 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;
Expand Down Expand Up @@ -260,14 +260,19 @@ export class LitCore {
bootstrapUrls: string[];
priceByNetwork: Record<string, number>;
}> {
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) {
Expand Down Expand Up @@ -297,7 +302,7 @@ export class LitCore {
epochInfo,
minNodeCount,
bootstrapUrls,
priceByNetwork
priceByNetwork,
};
}

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1068,7 +1075,7 @@ export class LitCore {
data,
requestId,
}: // eslint-disable-next-line @typescript-eslint/no-explicit-any
SendNodeCommand): Promise<any> => {
SendNodeCommand): Promise<any> => {
// FIXME: Replace <any> usage with explicit, strongly typed handlers
data = { ...data, epoch: this.currentEpochNumber };

Expand Down
23 changes: 11 additions & 12 deletions packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AuthSig>;

// ========== Constructor ==========
Expand Down Expand Up @@ -1164,8 +1165,8 @@ export class LitNodeClientNodeJs
// -- optional params
...(params.authMethods &&
params.authMethods.length > 0 && {
authMethods: params.authMethods,
}),
authMethods: params.authMethods,
}),

nodeSet,
};
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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 = {
Expand Down
Loading

0 comments on commit b532c39

Please sign in to comment.