Skip to content

Commit f5e1859

Browse files
threewebcodegoalongwaygoalongway
authored
feat: Adding plugin for B² Network (#2010)
* feat: b2-network plugin * docs:update readme and package description * fix: solve build error * modify * modify * feat: transfer action * modify README.md * docs: update readme * chore: update env file * modify b2 plugin * modify b2 plugin * modify b2 plugin * modify b2 plugin * modify b2 plugin * modify b2 plugin * fix: default empty value and resolve type error --------- Co-authored-by: goalongway <goalongway@163.com> Co-authored-by: goalongway <36787789+goalongway@users.noreply.github.com> Co-authored-by: goalongway <ma_huaibo@163.com>
1 parent 9bbb555 commit f5e1859

30 files changed

+1834
-0
lines changed

.env.example

+3
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,9 @@ ECHOCHAMBERS_MAX_MESSAGES=10
512512
ALLORA_API_KEY= # Allora API key, format: UP-f8db7d6558ab432ca0d92716
513513
ALLORA_CHAIN_SLUG= # must be one of mainnet, testnet. If not specified, it will use testnet by default
514514

515+
# B2 Network
516+
B2_PRIVATE_KEY= # Private key of the B2 Network account to use for the agent
517+
515518
# Opacity zkTLS
516519
OPACITY_TEAM_ID=f309ac8ae8a9a14a7e62cd1a521b1c5f
517520
OPACITY_CLOUDFLARE_NAME=eigen-test

agent/src/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import { aptosPlugin } from "@elizaos/plugin-aptos";
4646
import { artheraPlugin } from "@elizaos/plugin-arthera";
4747
import { availPlugin } from "@elizaos/plugin-avail";
4848
import { avalanchePlugin } from "@elizaos/plugin-avalanche";
49+
import { b2Plugin } from "@elizaos/plugin-b2";
4950
import { binancePlugin } from "@elizaos/plugin-binance";
5051
import {
5152
advancedTradePlugin,
@@ -822,6 +823,7 @@ export async function createAgent(
822823
getSecret(character, "ABSTRACT_PRIVATE_KEY")
823824
? abstractPlugin
824825
: null,
826+
getSecret(character, "B2_PRIVATE_KEY") ? b2Plugin: null,
825827
getSecret(character, "BINANCE_API_KEY") &&
826828
getSecret(character, "BINANCE_SECRET_KEY")
827829
? binancePlugin

packages/plugin-b2/.npmignore

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
*
2+
3+
!dist/**
4+
!package.json
5+
!readme.md
6+
!tsup.config.ts

packages/plugin-b2/README.md

+169
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
# @elizaos/plugin-b2
2+
3+
A plugin for interacting with the B2-Network within the ElizaOS ecosystem.
4+
5+
## Description
6+
7+
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.
8+
9+
## Installation
10+
11+
```bash
12+
pnpm install @elizaos/plugin-b2
13+
```
14+
15+
## Configuration
16+
17+
The plugin requires the following environment variable:
18+
19+
```typescript
20+
B2_PRIVATE_KEY=<Your B2 private key>
21+
```
22+
23+
## Features
24+
25+
### 1. Token Transfers
26+
27+
- Send native B2-BTC and ERC20 tokens
28+
- Support for multiple token standards
29+
- Built-in address validation
30+
31+
## Supported Tokens
32+
33+
```typescript
34+
const TOKENS = {
35+
"B2-BTC": "0x0000000000000000000000000000000000000000",
36+
uBTC: "0x796e4D53067FF374B89b2Ac101ce0c1f72ccaAc2",
37+
USDC: "0xE544e8a38aDD9B1ABF21922090445Ba93f74B9E5",
38+
USDT: "0x681202351a488040Fa4FdCc24188AfB582c9DD62",
39+
// ... and more
40+
};
41+
```
42+
43+
## Usage Examples
44+
45+
### Token Transfer
46+
47+
```typescript
48+
// Send B2-BTC
49+
"Send 1 B2-BTC to 0x4f9e2dc50B4Cd632CC2D24edaBa3Da2a9338832a";
50+
51+
// Send ERC20
52+
"Transfer 100 USDC to [address]";
53+
```
54+
55+
## Providers
56+
57+
### 1. Wallet Provider
58+
59+
- Displays wallet balances
60+
- Real-time balance updates
61+
62+
### 2. Tokens Provider
63+
64+
- Lists supported tokens
65+
- Shows token addresses
66+
67+
## Development
68+
69+
1. Clone the repository
70+
2. Install dependencies:
71+
3. Build the plugin:
72+
73+
```bash
74+
pnpm run build
75+
```
76+
77+
4. Run linting:
78+
79+
```bash
80+
pnpm run lint
81+
```
82+
83+
## Dependencies
84+
85+
- viem: ^2.21.49
86+
- @elizaos/core: workspace:\*
87+
88+
## Future Enhancements
89+
90+
1. **Advanced DeFi Operations**
91+
92+
- Multi-hop yield strategies
93+
- Auto-compounding features
94+
- Yield optimization algorithms
95+
- Risk assessment tools
96+
- Portfolio rebalancing automation
97+
- Cross-chain yield farming
98+
99+
2. **Enhanced Token Management**
100+
101+
- Batch token operations
102+
- Advanced token creation templates
103+
- Token migration tools
104+
- Automated token listing
105+
- Token analytics dashboard
106+
- Custom tokenomics implementation
107+
108+
3. **YAK Protocol Integration**
109+
110+
- Advanced routing algorithms
111+
- MEV protection features
112+
- Gas optimization strategies
113+
- Liquidity analysis tools
114+
- Price impact predictions
115+
- Custom trading strategies
116+
117+
4. **Benqi Protocol Features**
118+
119+
- Collateral optimization
120+
- Liquidation protection
121+
- Interest rate monitoring
122+
- Position management tools
123+
- Risk assessment dashboard
124+
- Auto-repayment features
125+
126+
5. **Token Mill Improvements**
127+
128+
- Advanced token customization
129+
- Automated market making
130+
- Token distribution tools
131+
- Vesting schedule management
132+
- Governance token features
133+
- Token upgrade mechanisms
134+
135+
6. **Security Enhancements**
136+
137+
- Transaction simulation
138+
- Smart contract auditing tools
139+
- Real-time monitoring
140+
- Automated safety checks
141+
- Emergency shutdown features
142+
- Multi-signature support
143+
144+
7. **Developer Tools**
145+
146+
- Enhanced debugging capabilities
147+
- Testing framework improvements
148+
- Documentation generator
149+
- CLI tools for common operations
150+
- Integration templates
151+
- Performance monitoring
152+
153+
8. **Analytics and Reporting**
154+
- Portfolio tracking
155+
- Performance metrics
156+
- Gas usage optimization
157+
- Transaction history analysis
158+
- Yield comparison tools
159+
- Risk assessment reports
160+
161+
We welcome community feedback and contributions to help prioritize these enhancements.
162+
163+
## Contributing
164+
165+
Contributions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information.
166+
167+
## License
168+
169+
This plugin is part of the Eliza project. See the main project repository for license information.

packages/plugin-b2/eslint.config.mjs

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import eslintGlobalConfig from "../../eslint.config.mjs";
2+
3+
export default [...eslintGlobalConfig];

packages/plugin-b2/package.json

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
{
2+
"name": "@elizaos/plugin-b2",
3+
"version": "0.1.7",
4+
"type": "module",
5+
"main": "dist/index.js",
6+
"module": "dist/index.js",
7+
"types": "dist/index.d.ts",
8+
"exports": {
9+
"./package.json": "./package.json",
10+
".": {
11+
"import": {
12+
"@elizaos/source": "./src/index.ts",
13+
"types": "./dist/index.d.ts",
14+
"default": "./dist/index.js"
15+
}
16+
}
17+
},
18+
"files": [
19+
"dist"
20+
],
21+
"dependencies": {
22+
"@elizaos/core": "workspace:*",
23+
"tsup": "8.3.5"
24+
},
25+
"devDependencies": {
26+
"tsup": "8.3.5"
27+
},
28+
"scripts": {
29+
"build": "tsup src/index.ts --format esm --no-dts",
30+
"dev": "tsup --format esm --dts --watch",
31+
"lint": "eslint --fix --cache .",
32+
"test": "vitest run"
33+
},
34+
"peerDependencies": {
35+
"whatwg-url": "7.1.0"
36+
}
37+
}
+147
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import {
2+
Action,
3+
ActionExample,
4+
IAgentRuntime,
5+
generateObjectDeprecated,
6+
Memory,
7+
State,
8+
HandlerCallback,
9+
elizaLogger,
10+
composeContext,
11+
ModelClass,
12+
} from "@elizaos/core";
13+
import { getTxReceipt, sendNativeAsset, sendToken, depositBTC } from "../utils";
14+
import { Address, Hash } from "viem";
15+
import { validateB2NetworkConfig } from "../environment";
16+
import { stakeTemplate } from "../templates";
17+
import { WalletProvider } from "../providers";
18+
import { StakeParams } from "../types";
19+
import { initWalletProvider } from "../providers";
20+
import { FARM_ADDRESS } from "../utils/constants";
21+
22+
// Exported for tests
23+
export class StakeAction {
24+
25+
constructor(private walletProvider: WalletProvider) {}
26+
27+
async stake(params: StakeParams): Promise<Hash> {
28+
try {
29+
const balance = await this.walletProvider.getNativeBalance(this.walletProvider.getAddress());
30+
if ( balance == BigInt(0) ) {
31+
throw new Error(`The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.`);
32+
}
33+
const txHash = await depositBTC(
34+
this.walletProvider,
35+
FARM_ADDRESS,
36+
params.amount,
37+
);
38+
return txHash;
39+
} catch(error) {
40+
elizaLogger.error(`Stake failed: ${error.message}`);
41+
throw new Error(`Stake failed: ${error.message}`);
42+
}
43+
}
44+
45+
async txReceipt(tx: Hash) {
46+
const receipt = await getTxReceipt(this.walletProvider, tx);
47+
if (receipt.status === "success") {
48+
return true;
49+
} else {
50+
return false;
51+
}
52+
}
53+
54+
async buildStakeDetails(
55+
state: State,
56+
runtime: IAgentRuntime,
57+
): Promise<StakeParams> {
58+
const context = composeContext({
59+
state,
60+
template: stakeTemplate,
61+
});
62+
63+
const stakeDetails = (await generateObjectDeprecated({
64+
runtime,
65+
context,
66+
modelClass: ModelClass.SMALL,
67+
})) as StakeParams;
68+
69+
return stakeDetails;
70+
}
71+
}
72+
73+
export const stakeAction: Action = {
74+
name: "STAKE",
75+
similes: [
76+
"STAKE_BTC_ON_B2",
77+
"STAKE_NATIVE_BTC_ON_B2",
78+
"DEPOSIT_BTC_ON_B2",
79+
"DEPOSIT_NATIVE_BTC_ON_B2",
80+
],
81+
validate: async (runtime: IAgentRuntime, _message: Memory) => {
82+
await validateB2NetworkConfig(runtime);
83+
return true;
84+
},
85+
description:
86+
"stake B2-BTC.",
87+
handler: async (
88+
runtime: IAgentRuntime,
89+
message: Memory,
90+
state: State,
91+
_options: { [key: string]: unknown },
92+
callback?: HandlerCallback
93+
) => {
94+
elizaLogger.debug("Starting STAKE handler...");
95+
96+
// Initialize or update state
97+
if (!state) {
98+
state = (await runtime.composeState(message)) as State;
99+
} else {
100+
state = await runtime.updateRecentMessageState(state);
101+
}
102+
103+
elizaLogger.debug("stake action handler called");
104+
const walletProvider = await initWalletProvider(runtime);
105+
const action = new StakeAction(walletProvider);
106+
107+
// Compose stake context
108+
const paramOptions = await action.buildStakeDetails(
109+
state,
110+
runtime,
111+
);
112+
113+
elizaLogger.debug("Stake paramOptions:", paramOptions);
114+
115+
const txHash = await action.stake(paramOptions);
116+
if (txHash) {
117+
const result = await action.txReceipt(txHash);
118+
if (result) {
119+
callback?.({
120+
text: "stake successful",
121+
content: { success: true, txHash: txHash },
122+
});
123+
} else {
124+
callback?.({
125+
text: "stake failed",
126+
content: { error: "Stake failed" },
127+
});
128+
}
129+
} else {
130+
callback?.({
131+
text: "stake failed",
132+
content: { error: "Stake failed" },
133+
});
134+
}
135+
return true;
136+
},
137+
examples: [
138+
[
139+
{
140+
user: "{{user1}}",
141+
content: {
142+
text: "Stake 1 B2-BTC",
143+
},
144+
},
145+
],
146+
] as ActionExample[][],
147+
};

0 commit comments

Comments
 (0)