Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
vishal-kanna committed Dec 31, 2024
1 parent 905e012 commit 902280a
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 199 deletions.
7 changes: 6 additions & 1 deletion agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,12 @@ export async function createAgent(
evaluators: [],
character,
// character.plugins are handled when clients are added
plugins: [teePlugin, cosmosPlugin].filter(Boolean),
plugins: [
...(teeMode !== TEEMode.OFF && walletSecretSalt
? [teePlugin, cosmosPlugin]
: []),
cosmosPlugin,
].filter(Boolean),
providers: [],
actions: [],
services: [],
Expand Down
17 changes: 7 additions & 10 deletions packages/plugin-cosmos/src/actions/transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ export default {
_options: { [key: string]: unknown },
callback?: HandlerCallback
): Promise<boolean> => {
console.log("??????????????????????????????????????????????????????");
elizaLogger.log("Starting COSMOS_SEND_TOKEN handler...");

// Ensure we have a state with recent user messages
Expand Down Expand Up @@ -185,26 +184,24 @@ export default {
}
return false;
}

console.log("------------------1");
// Convert string or number to string minimal units
// You might need to handle decimals for a real chain
const sendAmount = String(amount);

console.log("send amount>>>>>>>>.", sendAmount);

try {
console.log("before getcosmoswalletKey>>>>>>>>>.");
const CosmosTeeAddr = await getCosmosWalletKey(runtime, true);

console.log(
"CosmosTeeAddr>>>>>>>>>>>>>>>>>>.",
CosmosTeeAddr.address
);
// 1) Connect to the chain
const { stargateClient, signerAddress, chainInfo } =
await connectWallet(runtime, CosmosTeeAddr.privateKey);

console.log(
"stargateclien>>>>>>",
stargateClient,
signerAddress,
chainInfo
);

// 2) Estimate Gas
const cosmosBankMsgForFees = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
Expand Down
183 changes: 14 additions & 169 deletions packages/plugin-cosmos/src/keypairUtils.ts
Original file line number Diff line number Diff line change
@@ -1,116 +1,3 @@
// import { DirectSecp256k1Wallet } from "@cosmjs/proto-signing";
// import { Point } from "@noble/secp256k1";
// import { IAgentRuntime } from "@elizaos/core";
// import { DeriveKeyProvider, TEEMode } from "@elizaos/plugin-cosmos-tee";
// import { fromBase64, fromHex } from "@cosmjs/encoding";
// // import { Pubkey } from "@cosmjs/amino";

// export interface WalletResult {
// wallet?: DirectSecp256k1Wallet;
// publicKey?: any;
// }

// /**
// * Gets either a wallet or public key based on TEE mode and runtime settings
// * @param runtime The agent runtime
// * @param requirePrivateKey Whether to return a full wallet (true) or just public key (false)
// * @returns WalletResult containing either wallet or public key
// */
// export async function getCosmosWalletKey(
// runtime: IAgentRuntime,
// requirePrivateKey: boolean = true
// ): Promise<WalletResult> {
// const teeMode = runtime.getSetting("TEE_MODE") || TEEMode.OFF;

// if (teeMode !== TEEMode.OFF) {
// const walletSecretSalt = runtime.getSetting("WALLET_SECRET_SALT");
// if (!walletSecretSalt) {
// throw new Error(
// "WALLET_SECRET_SALT required when TEE_MODE is enabled"
// );
// }

// const deriveKeyProvider = new DeriveKeyProvider(teeMode);
// const deriveKeyResult =
// await deriveKeyProvider.deriveSecp256k1KeypairForCosmos(
// "/",
// walletSecretSalt,
// runtime.agentId
// );

// const privateKey = fromHex(deriveKeyResult.keypair.privateKey); // Assuming it's in hex
// const publicKey = fromHex(deriveKeyResult.keypair.publicKey); // Assuming it's in hex

// return requirePrivateKey
// ? {
// wallet: await DirectSecp256k1Wallet.fromKey(privateKey),
// }
// : {
// publicKey: {
// type: "tendermint/PubKeySecp256k1",
// value: Buffer.from(publicKey).toString("base64"),
// },
// };
// }

// // TEE mode is OFF
// const privateKeyString =
// runtime.getSetting("COSMOS_PRIVATE_KEY") ??
// runtime.getSetting("WALLET_PRIVATE_KEY");

// if (!privateKeyString) {
// throw new Error("Private key not found in settings");
// }

// if (requirePrivateKey) {
// try {
// // Try decoding as base64
// const privateKey = fromBase64(privateKeyString);
// return {
// wallet: await DirectSecp256k1Wallet.fromKey(privateKey),
// };
// } catch (e) {
// console.log("Error decoding base64 private key:", e);
// try {
// // Then try decoding as hex
// console.log("Try decoding hex instead");
// const privateKey = fromHex(privateKeyString);
// return {
// wallet: await DirectSecp256k1Wallet.fromKey(privateKey),
// };
// } catch (e2) {
// console.error("Error decoding private key:", e2);
// throw new Error("Invalid private key format");
// }
// }
// } else {
// const publicKeyString =
// runtime.getSetting("COSMOS_PUBLIC_KEY") ??
// runtime.getSetting("WALLET_PUBLIC_KEY");

// if (!publicKeyString) {
// throw new Error("Public key not found in settings");
// }

// try {
// const publicKeyBytes = fromBase64(publicKeyString);

// // Validate public key using noble-secp256k1's Point class
// Point.fromHex(publicKeyBytes);

// return {
// publicKey: {
// type: "tendermint/PubKeySecp256k1",
// value: publicKeyString,
// },
// };
// } catch (e) {
// console.error("Error decoding or validating public key:", e);
// throw new Error("Invalid public key format");
// }
// }
// }

import secp256k1 from "secp256k1";
import bech32 from "bech32";
import crypto from "crypto";
Expand All @@ -129,19 +16,19 @@ export interface CosmosKeypairResult {
* @param prefix The Bech32 prefix (e.g., "cosmos").
* @returns The Bech32-encoded address.
*/
function generateCosmosAddress(
publicKey: Uint8Array,
prefix: string = "cosmos"
): string {
// Take SHA256 hash of the public key
const sha256 = crypto.createHash("sha256").update(publicKey).digest();

// Take RIPEMD160 of the SHA256 hash
const ripemd160 = crypto.createHash("ripemd160").update(sha256).digest();

// Encode the result in Bech32
return bech32.encode(prefix, bech32.toWords(ripemd160));
}
// function generateCosmosAddress(
// publicKey: Uint8Array,
// prefix: string = "cosmos"
// ): string {
// // Take SHA256 hash of the public key
// const sha256 = crypto.createHash("sha256").update(publicKey).digest();

// // Take RIPEMD160 of the SHA256 hash
// const ripemd160 = crypto.createHash("ripemd160").update(sha256).digest();

// // Encode the result in Bech32
// return bech32.encode(prefix, bech32.toWords(ripemd160));
// }

/**
* Gets either a keypair or public key based on TEE mode and runtime settings
Expand All @@ -156,7 +43,6 @@ export async function getCosmosWalletKey(
const teeMode = runtime.getSetting("TEE_MODE") || TEEMode.OFF;

if (teeMode !== TEEMode.OFF) {
console.log("here>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
const walletSecretSalt = runtime.getSetting("WALLET_SECRET_SALT");
if (!walletSecretSalt) {
throw new Error(
Expand Down Expand Up @@ -190,46 +76,5 @@ export async function getCosmosWalletKey(
? { privateKey, publicKey, address }
: { publicKey, address };
}

// TEE mode is OFF
if (requirePrivateKey) {
const privateKeyString =
runtime.getSetting("COSMOS_PRIVATE_KEY") ??
runtime.getSetting("WALLET_PRIVATE_KEY");

if (!privateKeyString) {
throw new Error("Private key not found in settings");
}

try {
const privateKey = Uint8Array.from(
Buffer.from(privateKeyString, "base64")
);
const publicKey = secp256k1.publicKeyCreate(privateKey, true);
const address = generateCosmosAddress(publicKey);
return { privateKey, publicKey, address };
} catch (e) {
console.error("Error creating wallet from private key: ", e);
throw new Error("Invalid private key format");
}
} else {
const publicKeyString =
runtime.getSetting("COSMOS_PUBLIC_KEY") ??
runtime.getSetting("WALLET_PUBLIC_KEY");

if (!publicKeyString) {
throw new Error("Public key not found in settings");
}

try {
const publicKey = Uint8Array.from(
Buffer.from(publicKeyString, "base64")
);
const address = generateCosmosAddress(publicKey);
return { publicKey, address };
} catch (e) {
console.error("Error decoding public key: ", e);
throw new Error("Invalid public key format");
}
}
return {};
}
25 changes: 6 additions & 19 deletions packages/plugin-cosmos/src/providers/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ export interface CosmosToken {
valueUsd: string;
}

// export async function loadCosmjsSigning() {
// return (await import("@cosmjs/proto-signing")).DirectSecp256k1Wallet;
// }

/** Portfolio interface showing total USD plus an array of tokens */
interface WalletPortfolio {
totalUsd: string;
Expand Down Expand Up @@ -121,11 +117,6 @@ export async function connectWallet(
}> {
const teeMode = runtime.getSetting("TEE_MODE") || TEEMode.OFF;

console.log(
"Teemode>>>>>>>>>>>>>>>>>>>.",
teeMode,
teeMode !== TEEMode.OFF
);
// Build chain info from environment or chain-registry
const chainInfo = buildChainInfo(runtime);

Expand All @@ -140,29 +131,19 @@ export async function connectWallet(

const flag = teeMode !== TEEMode.OFF;

console.log("flag>>>>>>>>>.", flag);
if (flag) {
console.log("helo>>>>>>>>>>>>>>>>>>>>>>>>");

if (!privateKey || privateKey.length !== 32) {
throw new Error(
"TEE_MODE is enabled. A valid 32-byte private key is required."
);
}

const wallet = await DirectSecp256k1Wallet.fromKey(
privateKey,
chainInfo.bech32_prefix
);
signer = wallet;
const accounts = await wallet.getAccounts();
signerAddress = accounts[0].address;

const walletPubKey = (await wallet.getAccounts())[0].pubkey;
console.log(
"Wallet Public Key:>>>>>>>>>",
Buffer.from(walletPubKey).toString("hex")
);
} else {
// Non-TEE Mode requires a mnemonic
const mnemonic = runtime.getSetting("COSMOS_MNEMONIC");
Expand All @@ -177,8 +158,12 @@ export async function connectWallet(
mnemonic,
chain: chainInfo,
});

console.log("signer>>>>>>>>>>>>..", signer);
}

console.log("signer>>>>>>>>.", signer);

// Connect Stargate client
const stargateClient = await SigningStargateClient.connectWithSigner(
rpcUrl,
Expand All @@ -189,6 +174,8 @@ export async function connectWallet(
const [account] = await signer.getAccounts();
signerAddress = account.address;

console.log("signerAddress>>>>>>", signerAddress);

console.log(
`connectWallet: Connected to chain '${chainInfo.chain_name}', address: ${signerAddress}`
);
Expand Down

0 comments on commit 902280a

Please sign in to comment.