Skip to content

Commit

Permalink
Added decrypt and combine Functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
Hephaestus-V committed Sep 3, 2024
1 parent e584a0c commit 1c3d64d
Show file tree
Hide file tree
Showing 2 changed files with 278 additions and 58 deletions.
330 changes: 274 additions & 56 deletions packages/nextjs/scripts/strategyExecutor.js
Original file line number Diff line number Diff line change
@@ -1,92 +1,310 @@
import { ethers } from 'ethers';
import { encryptStrategy } from '../utils/lit-protocol/strategyEncryption.js';
import strategyAction from '../utils/lit-protocol/strategyAction.js';
import * as LitJsSdk from "@lit-protocol/lit-node-client-nodejs";
import { LitAccessControlConditionResource,createSiweMessageWithRecaps, LitActionResource, LitAbility, generateAuthSig } from "@lit-protocol/auth-helpers";
// import { ethers } from 'ethers';
// import { encryptStrategy } from '../utils/lit-protocol/strategyEncryption.js';
// import strategyAction from '../utils/lit-protocol/strategyAction.js';
// import * as LitJsSdk from "@lit-protocol/lit-node-client-nodejs";
// import { LitAccessControlConditionResource,LitPKPResource,createSiweMessageWithRecaps, LitActionResource, LitAbility, generateAuthSig } from "@lit-protocol/auth-helpers";
// import { LitContracts } from "@lit-protocol/contracts-sdk";
// import { LitNetwork } from "@lit-protocol/constants";
// import { LitNodeClient } from "@lit-protocol/lit-node-client";

// async function main() {
// const strategy = {
// threshold: 0.5
// };
// const ONE_WEEK_FROM_NOW = new Date(
// Date.now() + 1000 * 60 * 60 * 24 * 7
// ).toISOString();

// const wallet = new ethers.Wallet('6e5903d22b6717cc4d809b07f2df78f22ffe24a0568f1f8d099a2bd54a91327a', new ethers.providers.JsonRpcProvider('https://yellowstone-rpc.litprotocol.com/'));
// console.log(wallet.address,"wallet address");
// const client = new LitNodeClient({
// litNetwork: LitNetwork.DatilTest,
// debug: false,
// });
// await client.connect();

// console.log("clientConnected");

// const litContractClient = new LitContracts({
// signer: wallet,
// network: LitNetwork.DatilTest,
// });
// await litContractClient.connect();

// console.log("litContractClientConnected");
// const capacityCreditInfo = await litContractClient.mintCapacityCreditsNFT({
// requestsPerKilosecond: 80,
// // requestsPerDay: 14400,
// // requestsPerSecond: 10,
// daysUntilUTCMidnightExpiration: 10,
// });
// console.log(capacityCreditInfo, "capacityCreditInfo");
// console.log(capacityCreditInfo.capacityTokenId, "capacityCreditInfo.capacityTokenId");

// const { capacityDelegationAuthSig } = await client.createCapacityDelegationAuthSig({
// dAppOwnerWallet: wallet,
// capacityTokenId: capacityCreditInfo.capacityTokenIdStr,
// delegateeAddresses: [wallet.address],
// uses: "1",
// expiration: new Date(Date.now() + 1000 * 60 * 30).toISOString(), // 10 minutes
// });

// console.log(capacityDelegationAuthSig, "capacityDelegationAuthSig");

// const { ciphertext, dataToEncryptHash, accsResourceString } = await encryptStrategy(JSON.stringify(strategy));
// console.log("Strategy Encrypted");



// let blockHash = await client.getLatestBlockhash();
// const message = await createSiweMessageWithRecaps({
// walletAddress: wallet.address,
// nonce: blockHash,
// litNodeClient: client,
// expiration:ONE_WEEK_FROM_NOW,
// resources: [{
// resource: new LitActionResource("*"),
// ability: LitAbility.LitActionExecution,
// },{
// resource: new LitAccessControlConditionResource("*"),
// ability: LitAbility.AccessControlConditionDecryption,
// }],
// litNodeClient: client,
// })
// const authSig = await generateAuthSig({
// signer: wallet,
// toSign: message,

// });

// console.log(authSig, "authSig");

// const sessionSigs = await client.getLitActionSessionSigs({
// chain: "ethereum",
// resourceAbilityRequests: [
// {
// resource: new LitActionResource('*'),
// ability: LitAbility.LitActionExecution,
// },
// {
// resource: new LitAccessControlConditionResource("*"),
// ability: LitAbility.AccessControlConditionDecryption,
// },
// {
// resource: new LitPKPResource("*"),
// ability: LitAbility.PKPSigning,
// },
// ],
// authNeededCallback : async (params) => {
// return authSig;
// },

// capabilityAuthSigs:[capacityDelegationAuthSig],

// litActionCode : `(async () => {console.log("This is my Lit Action!");})();`,
// jsParams: {}

// });

// console.log(sessionSigs, "sessionSigs");

// await client.executeJs({
// sessionSigs,
// code:`(async () => {console.log("This is my Lit Action!");})();`,
// });

// // const results = await client.executeJs({
// // code: strategyAction,
// // sessionSigs,
// // jsParams: {
// // ciphertext,
// // dataToEncryptHash,
// // arbitrumYield: await getArbitrumYield(),
// // optimismYield: await getOptimismYield(),
// // currentChain: await getCurrentChain()
// // }
// // });

// // const { shouldMove, targetChain } = JSON.parse(results.response);

// // if (shouldMove) {
// // // Execute the strategy on the contract
// // const provider = new ethers.providers.JsonRpcProvider('YOUR_RPC_URL');
// // const signer = new ethers.Wallet('YOUR_PRIVATE_KEY', provider);
// // // const hyperHarvest = new ethers.Contract('YOUR_CONTRACT_ADDRESS', HyperHarvest.abi, signer);

// // // const destinationChainSelector = getChainSelector(targetChain);
// // const receiver = 'RECEIVER_ADDRESS_ON_TARGET_CHAIN';
// // const gasFeeAmount = 'ESTIMATED_GAS_FEE';

// // // await hyperHarvest.executeStrategy(receiver, gasFeeAmount, destinationChainSelector);
// // }
// }
// main().catch((error) => {
// console.error(error);
// process.exit(1);
// });

import * as ethers from "ethers";
import {
LitAccessControlConditionResource,
createSiweMessage,
LitActionResource,
LitAbility,
generateAuthSig,
} from "@lit-protocol/auth-helpers";
import { LitContracts } from "@lit-protocol/contracts-sdk";
import { LitNetwork } from "@lit-protocol/constants";
import { LitNodeClient } from "@lit-protocol/lit-node-client";
import { encryptString } from "@lit-protocol/encryption";

async function main() {
const strategy = {
threshold: 0.5
threshold: 0.5,
};

const strategyString=JSON.stringify(strategy);
const ONE_WEEK_FROM_NOW = new Date(
Date.now() + 1000 * 60 * 60 * 24 * 7
).toISOString();

const client = new LitJsSdk.LitNodeClientNodeJs({
litNetwork: "datil-test"
const wallet = new ethers.Wallet(
"f6b82019ef782c18b67f33f096111d12f5dce74817df4faf56cf399dcb4df2ef",
new ethers.providers.JsonRpcProvider(
"https://yellowstone-rpc.litprotocol.com/"
)
);
console.log(wallet.address, "wallet address");
const client = new LitNodeClient({
litNetwork: LitNetwork.DatilTest,
debug: false,
});
await client.connect();

const { ciphertext, dataToEncryptHash, accsResourceString } = await encryptStrategy(JSON.stringify(strategy));
console.log("Strategy Encrypted");
console.log("clientConnected");

const wallet = new ethers.Wallet('6e5903d22b6717cc4d809b07f2df78f22ffe24a0568f1f8d099a2bd54a91327a', new ethers.providers.JsonRpcProvider('https://yellowstone-rpc.litprotocol.com/'));

console.log(wallet.address,"wallet address");

let blockHash = await client.getLatestBlockhash();
const message = await createSiweMessageWithRecaps({
walletAddress: wallet.address,
nonce: blockHash,
litNodeClient: client,
expiration:ONE_WEEK_FROM_NOW,
})
const authSig = await generateAuthSig({
signer: wallet,
toSign: message,
address: wallet.address
const litContractClient = new LitContracts({
signer: wallet,
network: LitNetwork.DatilTest,
});
await litContractClient.connect();

console.log("litContractClientConnected");
const capacityCreditInfo = await litContractClient.mintCapacityCreditsNFT({
requestsPerKilosecond: 80,
// requestsPerDay: 14400,
// requestsPerSecond: 10,
daysUntilUTCMidnightExpiration: 10,
});
console.log(capacityCreditInfo, "capacityCreditInfo");
console.log(
capacityCreditInfo.capacityTokenId,
"capacityCreditInfo.capacityTokenId"
);

console.log(authSig, "authSig");
const { capacityDelegationAuthSig } =
await client.createCapacityDelegationAuthSig({
dAppOwnerWallet: wallet,
capacityTokenId: capacityCreditInfo.capacityTokenIdStr,
delegateeAddresses: [wallet.address],
uses: "1",
expiration: new Date(Date.now() + 1000 * 60 * 30).toISOString(), // 10 minutes
});

console.log(capacityDelegationAuthSig, "capacityDelegationAuthSig");

const accessControlConditions = [
{
contractAddress: "",
standardContractType: "",
chain: "ethereum",
method: "eth_getBalance",
parameters: [":userAddress", "latest"],
returnValueTest: {
comparator: ">=",
value: "0",
},
},
];

const { ciphertext, dataToEncryptHash } = await encryptString(
{
accessControlConditions,
dataToEncrypt:strategyString,
// "f6b82019ef782c18b67f33f096111d12f5dce74817df4faf56cf399dcb4df2ef",
},
client
);
console.log("Strategy Encrypted");

console.log("🔄 Getting Session Sigs via an Auth Sig...");
const sessionSigs = await client.getSessionSigs({
chain: "ethereum",
expiration: new Date(Date.now() + 1000 * 60 * 10).toISOString(), // 10 minutes
capabilityAuthSigs: [capacityDelegationAuthSig],
resourceAbilityRequests: [
{
resource: new LitActionResource('*'),
ability: LitAbility.LitActionExecution,
resource: new LitAccessControlConditionResource("*"),
ability: LitAbility.AccessControlConditionDecryption,
},
{
resource: new LitAccessControlConditionResource('*'),
ability: LitAbility.AccessControlConditionDecryption,
}
resource: new LitActionResource("*"),
ability: LitAbility.LitActionExecution,
},
],
authNeededCallback : async (params) => {
return authSig;
}
authNeededCallback: async ({
uri,
expiration,
resourceAbilityRequests,
}) => {
const toSign = await createSiweMessage({
uri,
expiration,
resources: resourceAbilityRequests,
walletAddress: wallet.address,
nonce: await client.getLatestBlockhash(),
litNodeClient: client,
});

return await generateAuthSig({
signer: wallet,
toSign,
});
},
});
console.log("✅ Got Session Sigs via an Auth Sig");

console.log(sessionSigs, "sessionSigs");
const code = `(async () => {
const resp = await Lit.Actions.decryptAndCombine({
accessControlConditions,
ciphertext,
dataToEncryptHash,
authSig: null,
chain: 'ethereum',
});
const results = await client.executeJs({
code: strategyAction,
const a=JSON.parse(resp);
console.log(a);
console.log(meriYield);
Lit.Actions.setResponse({ response: resp });
})();`;

const meriYield=0.5 ;
const res = await client.executeJs({
sessionSigs,
code,
jsParams: {
accessControlConditions,
ciphertext,
dataToEncryptHash,
arbitrumYield: await getArbitrumYield(),
optimismYield: await getOptimismYield(),
currentChain: await getCurrentChain()
}
meriYield,
},
});

const { shouldMove, targetChain } = JSON.parse(results.response);

// if (shouldMove) {
// // Execute the strategy on the contract
// const provider = new ethers.providers.JsonRpcProvider('YOUR_RPC_URL');
// const signer = new ethers.Wallet('YOUR_PRIVATE_KEY', provider);
// // const hyperHarvest = new ethers.Contract('YOUR_CONTRACT_ADDRESS', HyperHarvest.abi, signer);

// // const destinationChainSelector = getChainSelector(targetChain);
// const receiver = 'RECEIVER_ADDRESS_ON_TARGET_CHAIN';
// const gasFeeAmount = 'ESTIMATED_GAS_FEE';

// // await hyperHarvest.executeStrategy(receiver, gasFeeAmount, destinationChainSelector);
// }
console.log("Result:", res);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
});
6 changes: 4 additions & 2 deletions packages/nextjs/utils/lit-protocol/strategyEncryption.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as LitJsSdk from "@lit-protocol/lit-node-client-nodejs";
import { LitAccessControlConditionResource, LitActionResource, LitAbility } from "@lit-protocol/auth-helpers";
import { LitNodeClient } from "@lit-protocol/lit-node-client";
import { LitNetwork } from "@lit-protocol/constants";

const chain = 'ethereum';
const accessControlConditions = [
Expand All @@ -17,8 +19,8 @@ const accessControlConditions = [
];

export async function encryptStrategy(strategy) {
const client = new LitJsSdk.LitNodeClientNodeJs({
litNetwork: "datil-test"
const client = new LitNodeClient({
litNetwork: LitNetwork.DatilTest,
});
await client.connect();

Expand Down

0 comments on commit 1c3d64d

Please sign in to comment.