Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adding plugin for B² Network #2010

Merged
merged 43 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
17d06f1
feat: b2-network plugin
threewebcode Jan 8, 2025
d1b830f
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 8, 2025
92a6fa5
docs:update readme and package description
threewebcode Jan 8, 2025
2afe606
docs: update readme and package description
threewebcode Jan 8, 2025
b72151c
fix: solve build error
threewebcode Jan 8, 2025
cdb5b01
modify
Jan 8, 2025
195c57b
modify
Jan 8, 2025
de31440
feat: transfer action
threewebcode Jan 8, 2025
8c6aa4d
Merge pull request #1 from threewebcode/develop
threewebcode Jan 8, 2025
3b9006c
modify b2 plugin
Jan 8, 2025
8ebf789
modify b2 plugin
Jan 8, 2025
f5b3b56
modify README.md
Jan 8, 2025
b0282ca
docs: update readme
threewebcode Jan 8, 2025
2970514
Merge pull request #2 from threewebcode/develop
threewebcode Jan 8, 2025
615a299
chore: update env file
threewebcode Jan 8, 2025
1a6fdc0
chore: update env file
threewebcode Jan 8, 2025
0d9cf53
modify b2 plugin
Jan 8, 2025
ed3fa5a
Merge branch 'develop' of github.com:b2network/eliza into develop
Jan 8, 2025
5386f3d
chore: merge env file
threewebcode Jan 8, 2025
972cc5d
modify b2 plugin
Jan 8, 2025
d2cbfa5
Merge branch 'develop' of github.com:b2network/eliza into develop
Jan 8, 2025
13e1abc
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 8, 2025
ea2d523
Merge branch 'elizaOS:develop' into develop
goalongway Jan 8, 2025
2a80ff6
Merge branch 'develop' into develop
goalongway Jan 8, 2025
5be7eb4
modify b2 plugin
Jan 8, 2025
900ec3e
Merge branch 'develop' into develop
goalongway Jan 9, 2025
2333d56
merge latest env file
threewebcode Jan 9, 2025
b0e9d43
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 10, 2025
065160d
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 10, 2025
fc0dc5c
modify b2 plugin
goalongway Jan 11, 2025
a265dd8
Merge branch 'elizaOS:develop' into develop
goalongway Jan 11, 2025
6cb190d
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 11, 2025
cc28c48
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 12, 2025
f8495b1
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 13, 2025
46eb7f1
modify b2 plugin
goalongway Jan 13, 2025
2cf397f
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 13, 2025
396bb8c
modify b2 plugin
goalongway Jan 13, 2025
3a2cecc
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 13, 2025
a80c4fd
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 13, 2025
daf7ac9
fix: default empty value and resolve type error
threewebcode Jan 14, 2025
8e5c04e
Merge branch 'elizaOS:develop' into develop
threewebcode Jan 14, 2025
2cfc56d
chore: merge latest changes.
threewebcode Jan 14, 2025
7a033d7
Merge pull request #3 from threewebcode/develop
threewebcode Jan 14, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,9 @@ ECHOCHAMBERS_MAX_MESSAGES=10
ALLORA_API_KEY= # Allora API key, format: UP-f8db7d6558ab432ca0d92716
ALLORA_CHAIN_SLUG= # must be one of mainnet, testnet. If not specified, it will use testnet by default

# B2 Network
B2_PRIVATE_KEY= # Private key of the B2 Network account to use for the agent

# Opacity zkTLS
OPACITY_TEAM_ID=f309ac8ae8a9a14a7e62cd1a521b1c5f
OPACITY_CLOUDFLARE_NAME=eigen-test
Expand Down
2 changes: 2 additions & 0 deletions agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { aptosPlugin } from "@elizaos/plugin-aptos";
import { artheraPlugin } from "@elizaos/plugin-arthera";
import { availPlugin } from "@elizaos/plugin-avail";
import { avalanchePlugin } from "@elizaos/plugin-avalanche";
import { b2Plugin } from "@elizaos/plugin-b2";
import { binancePlugin } from "@elizaos/plugin-binance";
import {
advancedTradePlugin,
Expand Down Expand Up @@ -822,6 +823,7 @@ export async function createAgent(
getSecret(character, "ABSTRACT_PRIVATE_KEY")
? abstractPlugin
: null,
getSecret(character, "B2_PRIVATE_KEY") ? b2Plugin: null,
getSecret(character, "BINANCE_API_KEY") &&
getSecret(character, "BINANCE_SECRET_KEY")
? binancePlugin
Expand Down
6 changes: 6 additions & 0 deletions packages/plugin-b2/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*

!dist/**
!package.json
!readme.md
!tsup.config.ts
169 changes: 169 additions & 0 deletions packages/plugin-b2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
# @elizaos/plugin-b2

A plugin for interacting with the B2-Network within the ElizaOS ecosystem.

## Description

The B2 Network Plugin offers a set of features that can be integrated into the Eliza platform to enhance its capabilities. This plugin enables seamless token transfers on the B2-Network. It provides functionality to transfer both native B2-BTC and ERC20 tokens using secure wallet operations.

## Installation

```bash
pnpm install @elizaos/plugin-b2
```

## Configuration

The plugin requires the following environment variable:

```typescript
B2_PRIVATE_KEY=<Your B2 private key>
```

## Features

### 1. Token Transfers

- Send native B2-BTC and ERC20 tokens
- Support for multiple token standards
- Built-in address validation

## Supported Tokens

```typescript
const TOKENS = {
"B2-BTC": "0x0000000000000000000000000000000000000000",
uBTC: "0x796e4D53067FF374B89b2Ac101ce0c1f72ccaAc2",
USDC: "0xE544e8a38aDD9B1ABF21922090445Ba93f74B9E5",
USDT: "0x681202351a488040Fa4FdCc24188AfB582c9DD62",
// ... and more
};
```

## Usage Examples

### Token Transfer

```typescript
// Send B2-BTC
"Send 1 B2-BTC to 0x4f9e2dc50B4Cd632CC2D24edaBa3Da2a9338832a";

// Send ERC20
"Transfer 100 USDC to [address]";
```

## Providers

### 1. Wallet Provider

- Displays wallet balances
- Real-time balance updates

### 2. Tokens Provider

- Lists supported tokens
- Shows token addresses

## Development

1. Clone the repository
2. Install dependencies:
3. Build the plugin:

```bash
pnpm run build
```

4. Run linting:

```bash
pnpm run lint
```

## Dependencies

- viem: ^2.21.49
- @elizaos/core: workspace:\*

## Future Enhancements

1. **Advanced DeFi Operations**

- Multi-hop yield strategies
- Auto-compounding features
- Yield optimization algorithms
- Risk assessment tools
- Portfolio rebalancing automation
- Cross-chain yield farming

2. **Enhanced Token Management**

- Batch token operations
- Advanced token creation templates
- Token migration tools
- Automated token listing
- Token analytics dashboard
- Custom tokenomics implementation

3. **YAK Protocol Integration**

- Advanced routing algorithms
- MEV protection features
- Gas optimization strategies
- Liquidity analysis tools
- Price impact predictions
- Custom trading strategies

4. **Benqi Protocol Features**

- Collateral optimization
- Liquidation protection
- Interest rate monitoring
- Position management tools
- Risk assessment dashboard
- Auto-repayment features

5. **Token Mill Improvements**

- Advanced token customization
- Automated market making
- Token distribution tools
- Vesting schedule management
- Governance token features
- Token upgrade mechanisms

6. **Security Enhancements**

- Transaction simulation
- Smart contract auditing tools
- Real-time monitoring
- Automated safety checks
- Emergency shutdown features
- Multi-signature support

7. **Developer Tools**

- Enhanced debugging capabilities
- Testing framework improvements
- Documentation generator
- CLI tools for common operations
- Integration templates
- Performance monitoring

8. **Analytics and Reporting**
- Portfolio tracking
- Performance metrics
- Gas usage optimization
- Transaction history analysis
- Yield comparison tools
- Risk assessment reports

We welcome community feedback and contributions to help prioritize these enhancements.

## Contributing

Contributions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information.

## License

This plugin is part of the Eliza project. See the main project repository for license information.
3 changes: 3 additions & 0 deletions packages/plugin-b2/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import eslintGlobalConfig from "../../eslint.config.mjs";

export default [...eslintGlobalConfig];
37 changes: 37 additions & 0 deletions packages/plugin-b2/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@elizaos/plugin-b2",
"version": "0.1.7",
"type": "module",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"@elizaos/source": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
},
"files": [
"dist"
],
"dependencies": {
"@elizaos/core": "workspace:*",
"tsup": "8.3.5"
},
"devDependencies": {
"tsup": "8.3.5"
},
"scripts": {
"build": "tsup src/index.ts --format esm --no-dts",
"dev": "tsup --format esm --dts --watch",
"lint": "eslint --fix --cache .",
"test": "vitest run"
},
"peerDependencies": {
"whatwg-url": "7.1.0"
}
}
147 changes: 147 additions & 0 deletions packages/plugin-b2/src/actions/stake.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import {
Action,
ActionExample,
IAgentRuntime,
generateObjectDeprecated,
Memory,
State,
HandlerCallback,
elizaLogger,
composeContext,
ModelClass,
} from "@elizaos/core";
import { getTxReceipt, sendNativeAsset, sendToken, depositBTC } from "../utils";
import { Address, Hash } from "viem";
import { validateB2NetworkConfig } from "../environment";
import { stakeTemplate } from "../templates";
import { WalletProvider } from "../providers";
import { StakeParams } from "../types";
import { initWalletProvider } from "../providers";
import { FARM_ADDRESS } from "../utils/constants";

// Exported for tests
export class StakeAction {

constructor(private walletProvider: WalletProvider) {}

async stake(params: StakeParams): Promise<Hash> {
try {
const balance = await this.walletProvider.getNativeBalance(this.walletProvider.getAddress());
if ( balance == BigInt(0) ) {
throw new Error(`The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.`);
}
const txHash = await depositBTC(
this.walletProvider,
FARM_ADDRESS,
params.amount,
);
return txHash;
} catch(error) {
elizaLogger.error(`Stake failed: ${error.message}`);
throw new Error(`Stake failed: ${error.message}`);
}
}

async txReceipt(tx: Hash) {
const receipt = await getTxReceipt(this.walletProvider, tx);
if (receipt.status === "success") {
return true;
} else {
return false;
}
}

async buildStakeDetails(
state: State,
runtime: IAgentRuntime,
): Promise<StakeParams> {
const context = composeContext({
state,
template: stakeTemplate,
});

const stakeDetails = (await generateObjectDeprecated({
runtime,
context,
modelClass: ModelClass.SMALL,
})) as StakeParams;

return stakeDetails;
}
}

export const stakeAction: Action = {
name: "STAKE",
similes: [
"STAKE_BTC_ON_B2",
"STAKE_NATIVE_BTC_ON_B2",
"DEPOSIT_BTC_ON_B2",
"DEPOSIT_NATIVE_BTC_ON_B2",
],
validate: async (runtime: IAgentRuntime, _message: Memory) => {
await validateB2NetworkConfig(runtime);
return true;
},
description:
"stake B2-BTC.",
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
_options: { [key: string]: unknown },
callback?: HandlerCallback
) => {
elizaLogger.debug("Starting STAKE handler...");

// Initialize or update state
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
state = await runtime.updateRecentMessageState(state);
}

elizaLogger.debug("stake action handler called");
const walletProvider = await initWalletProvider(runtime);
const action = new StakeAction(walletProvider);

// Compose stake context
const paramOptions = await action.buildStakeDetails(
state,
runtime,
);

elizaLogger.debug("Stake paramOptions:", paramOptions);

const txHash = await action.stake(paramOptions);
if (txHash) {
const result = await action.txReceipt(txHash);
if (result) {
callback?.({
text: "stake successful",
content: { success: true, txHash: txHash },
});
} else {
callback?.({
text: "stake failed",
content: { error: "Stake failed" },
});
}
} else {
callback?.({
text: "stake failed",
content: { error: "Stake failed" },
});
}
return true;
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Stake 1 B2-BTC",
},
},
],
] as ActionExample[][],
};
Loading
Loading