Skip to content

Commit 02cc6b0

Browse files
committed
removed bet and game mentions
1 parent cdae2a5 commit 02cc6b0

File tree

7 files changed

+443
-546
lines changed

7 files changed

+443
-546
lines changed

examples/cointoss/README.md

+42-103
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ A decentralized toss agent built using CDP AgentKit that operates over the XMTP
55
## Features
66

77
- XMTP group chat support (responds to @toss mentions)
8-
- Natural language bet creation (e.g., "Will it rain tomorrow for 10 USDC")
9-
- Support for custom betting topics and options
8+
- Natural language toss creation (e.g., "Will it rain tomorrow for 10 USDC")
9+
- Support for custom toss topics and options
1010
- Multiple player support with option-based prize distribution
1111
- Wallet address display for transparency and accountability
1212
- Transaction hash links for payment verification
@@ -19,94 +19,31 @@ A decentralized toss agent built using CDP AgentKit that operates over the XMTP
1919
- [OpenAI](https://platform.openai.com/) API key
2020
- [Coinbase Developer Platform](https://portal.cdp.coinbase.com) (CDP) API credentials
2121

22-
## Quick Start Guide
23-
24-
Follow these steps to get your CoinToss agent up and running quickly:
25-
26-
1. **Clone the repository**:
27-
28-
```bash
29-
git clone https://github.com/ephemeraHQ/xmtp-agent-examples.git
30-
cd integrations/cointoss
31-
```
32-
33-
2. **Install dependencies**:
34-
35-
```bash
36-
yarn install
37-
```
38-
39-
3. **Generate XMTP keys**:
40-
41-
```bash
42-
yarn build
43-
yarn gen:keys
44-
```
45-
46-
This will generate random wallet and encryption keys for your agent and output them to the console. Copy these values to your `.env` file.
47-
48-
49-
4. **Set up your environment variables**:
50-
Create a `.env` file with the following variables:
51-
52-
```
53-
# Required: OpenAI API Key
54-
OPENAI_API_KEY=your_openai_api_key_here
55-
56-
# Required: Coinbase Developer Platform credentials
57-
CDP_KEY_NAME=your_api_key_name_here
58-
CDP_API_KEY_PRIVATE_KEY=your_api_key_private_key_here
59-
60-
# Required: XMTP wallet and encryption keys (from step 3)
61-
WALLET_KEY=your_wallet_private_key_here
62-
ENCRYPTION_KEY=your_encryption_key_here
63-
64-
# Optional: Network ID (defaults to base-sepolia if not specified)
65-
NETWORK_ID=base-sepolia
66-
67-
# Optional: Redis for persistent storage (if not provided, local file storage will be used)
68-
REDIS_URL=redis://localhost:6379
69-
```
70-
71-
5. **Build and start the agent**:
72-
73-
```bash
74-
yarn build
75-
yarn start
76-
```
77-
78-
For development with more detailed logs:
79-
```bash
80-
yarn dev
81-
```
82-
83-
6. **Invite the agent to your XMTP group chat**:
84-
The agent responds when tagged with `@toss` in a group chat.
85-
8622
## Usage Examples
8723

8824
The agent responds to commands in group chats when tagged with `@toss`:
8925

9026
### Available Commands
9127

92-
- `@toss create <amount>` - Create a new betting game with specified USDC amount
93-
- `@toss join <gameId> <option>` - Join a game and select your option
94-
- `@toss execute <gameId>` - Execute the bet resolution (creator only)
95-
- `@toss status <gameId>` - Check game status and participants
96-
- `@toss list` - List all active games
28+
- `@toss create <amount>` - Create a new toss with specified USDC amount
29+
- `@toss join <tossId> <option>` - Join a toss and select your option
30+
- `@toss execute <tossId>` - Execute the toss resolution (creator only)
31+
- `@toss status <tossId>` - Check toss status and participants
32+
- `@toss list` - List all active tosses
9733
- `@toss balance` - Check your wallet balance
98-
- `@toss <natural language bet>` - Create a bet using natural language
34+
- `@toss <natural language toss>` - Create a toss using natural language
9935

10036
### Natural Language Examples
101-
- `@toss Will it rain tomorrow for 5` - Creates a yes/no bet with 5 USDC
102-
- `@toss Lakers vs Celtics game for 10` - Creates a bet with Lakers and Celtics as options
37+
38+
- `@toss Will it rain tomorrow for 5` - Creates a yes/no toss with 5 USDC
39+
- `@toss Lakers vs Celtics game for 10` - Creates a toss with Lakers and Celtics as options
10340

10441
### Example Flow
10542

106-
1. **Create a game**: `@toss Will Bitcoin hit $100k this year for 5`
107-
2. **Join the game**: `@toss join 1 yes` (each player must choose an option)
43+
1. **Create a toss**: `@toss Will Bitcoin hit $100k this year for 5`
44+
2. **Join the toss**: `@toss join 1 yes` (each player must choose an option)
10845
3. **Check status**: `@toss status 1`
109-
4. **Execute the bet**: `@toss execute 1` (creator only)
46+
4. **Execute the toss**: `@toss execute 1` (creator only)
11047
5. **View results**: All players who chose the winning option share the prize pool
11148

11249
## How It Works
@@ -115,20 +52,21 @@ This CoinToss agent combines several technologies:
11552

11653
1. **XMTP Protocol**: For group chat messaging interface
11754
2. **Coinbase AgentKit**: For wallet management and payments
118-
3. **Storage Options**: Redis or local file storage for game and wallet data
119-
4. **LLM Integration**: For natural language bet parsing
55+
3. **Storage Options**: Redis or local file storage for toss and wallet data
56+
4. **LLM Integration**: For natural language toss parsing
12057

12158
The agent workflow:
122-
1. Users create or join betting games in group chats
123-
2. Each player is assigned a unique wallet
124-
3. The game creator determines when to execute the bet
59+
60+
1. Users create or join tosses in group chats
61+
2. Each player is assigned a unique wallet
62+
3. The toss creator determines when to execute the toss
12563
4. A random option is selected as the winner
12664
5. Prize money is split among all players who chose the winning option
12765

12866
## Prize Distribution
12967

130-
- All bets are collected in a dedicated game wallet
131-
- When the game is executed, a winning option is randomly selected
68+
- All tosses are collected in a dedicated toss wallet
69+
- When the toss is executed, a winning option is randomly selected
13270
- All players who chose the winning option share the prize pool equally
13371
- Automatic transfers are sent to each winner's wallet
13472
- Transaction confirmations are provided in the chat
@@ -139,7 +77,8 @@ The agent workflow:
13977

14078
If you see errors like `Failed to create wallet: APIError`:
14179

142-
1. **Coinbase API Keys**:
80+
1. **Coinbase API Keys**:
81+
14382
- Verify your API key name matches exactly as shown in the Coinbase Developer Dashboard
14483
- Ensure your private key includes the complete PEM format with BEGIN/END lines
14584
- Format multiline keys properly for your .env file
@@ -149,6 +88,7 @@ If you see errors like `Failed to create wallet: APIError`:
14988
- Verify there are no Coinbase service outages
15089

15190
If you're still encountering issues, try clearing your local wallet data:
91+
15292
```bash
15393
rm -rf .data/wallets
15494
```
@@ -157,34 +97,33 @@ rm -rf .data/wallets
15797

15898
- **Wallet Management**: Coinbase SDK for wallet creation and transfers
15999
- **XMTP Integration**: Group chat support with @toss tag handling
160-
- **Unified Agent System**:
100+
- **Unified Agent System**:
161101
- Single AI agent for both natural language parsing and wallet operations
162-
- **Game Logic**:
102+
- **Toss Logic**:
163103
- Random selection of winning option
164104
- Fair prize distribution among winners
165105
- **Storage Options**: Local file storage or Redis
166106

167107
## Security
168108

169-
- Each user and game gets a dedicated Coinbase wallet
109+
- Each user and toss gets a dedicated Coinbase wallet
170110
- Encrypted wallet storage
171111
- Transparent wallet address display
172112
- Transaction verification through block explorer links
173113
- Advanced randomness for fair winner selection
174114

175-
## License
176-
177-
MIT
178-
179-
## Code Structure
115+
## Run the agent
180116

181-
The CoinToss agent codebase is organized with a modular design:
182-
183-
- **src/index.ts**: Main entry point that initializes the system and handles XMTP message routing
184-
- **src/commands.ts**: Command processor that handles all explicit commands and natural language bets
185-
- **src/cdp.ts**: Agent for natural language processing and wallet operations
186-
- **src/game.ts**: Game logic implementation
187-
- **src/storage.ts**: Storage layer for persisting games and wallet data
188-
- **src/walletService.ts**: Wallet functions for creating and managing game wallets
189-
- **src/xmtp.ts**: XMTP integration for messaging
190-
- **src/types.ts**: Type definitions
117+
```bash
118+
# git clone repo
119+
git clone https://github.com/ephemeraHQ/xmtp-agent-examples.git
120+
# go to the folder
121+
cd xmtp-agent-examples
122+
cd examples/cointoss
123+
# install packages
124+
yarn
125+
# generate random xmtp keys (optional)
126+
yarn gen:keys
127+
# run the example
128+
yarn dev
129+
```

examples/cointoss/src/cdp.ts

+33-33
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import { createReactAgent } from "@langchain/langgraph/prebuilt";
1313
import { ChatOpenAI } from "@langchain/openai";
1414
import type { StorageProvider } from "./types";
1515

16-
// Interface for parsed bet information
17-
export interface ParsedBet {
16+
// Interface for parsed toss information
17+
export interface ParsedToss {
1818
topic: string;
1919
options: string[];
2020
amount: string;
@@ -40,7 +40,7 @@ interface ToolsChunk {
4040
type StreamChunk = AgentChunk | ToolsChunk;
4141

4242
// Interface for parsed JSON response
43-
interface BetJsonResponse {
43+
interface TossJsonResponse {
4444
topic?: string;
4545
options?: string[];
4646
amount?: string;
@@ -78,7 +78,7 @@ export async function getOrCreateWalletForUser(
7878
return { walletProvider, config };
7979
}
8080

81-
export async function createGameWallet(_storage: StorageProvider) {
81+
export async function createTossWallet(_storage: StorageProvider) {
8282
const config = {
8383
apiKeyName: process.env.CDP_API_KEY_NAME ?? "",
8484
apiKeyPrivateKey: process.env.CDP_API_KEY_PRIVATE_KEY?.replace(
@@ -144,21 +144,21 @@ export async function initializeAgent(
144144
tools,
145145
checkpointSaver: memory,
146146
messageModifier: `
147-
You are a CoinToss Agent that helps users participate in coin toss betting games.
147+
You are a CoinToss Agent that helps users participate in coin toss activities.
148148
149149
You have two main functions:
150-
1. Process natural language bet requests and structure them
151-
2. Handle coin toss game management commands
150+
1. Process natural language toss requests and structure them
151+
2. Handle coin toss management commands
152152
153-
When parsing natural language bets:
154-
- Extract the bet topic (what people are betting on)
153+
When parsing natural language tosses:
154+
- Extract the toss topic (what people are tossing on)
155155
- Identify options (default to "yes" and "no" if not provided)
156-
- Determine bet amount (default to 0.1 USDC if not specified)
157-
- Enforce a maximum bet amount of 10 USDC
156+
- Determine toss amount (default to 0.1 USDC if not specified)
157+
- Enforce a maximum toss amount of 10 USDC
158158
159159
For example:
160-
- "Will it rain tomorrow for 5" should be interpreted as a bet on "Will it rain tomorrow" with options ["yes", "no"] and amount "5"
161-
- "Lakers vs Celtics for 10" should be interpreted as a bet on "Lakers vs Celtics game" with options ["Lakers", "Celtics"] and amount "10"
160+
- "Will it rain tomorrow for 5" should be interpreted as a toss on "Will it rain tomorrow" with options ["yes", "no"] and amount "5"
161+
- "Lakers vs Celtics for 10" should be interpreted as a toss on "Lakers vs Celtics game" with options ["Lakers", "Celtics"] and amount "10"
162162
163163
When checking payments or balances:
164164
1. Use the USDC token at 0x5dEaC602762362FE5f135FA5904351916053cF70 on Base.
@@ -168,24 +168,24 @@ export async function initializeAgent(
168168
- The correct addresses were used
169169
3. For balance checks, show the exact USDC amount available.
170170
4. When transferring winnings, ensure:
171-
- The game wallet has sufficient balance
171+
- The toss wallet has sufficient balance
172172
- The transfer is completed successfully
173173
- Provide transaction details
174174
175175
Available commands:
176-
/create <amount> - Create a new coin toss game with specified USDC bet amount
177-
/join <gameId> - Join an existing game with the specified ID
178-
/list - List all active games
176+
/create <amount> - Create a new coin toss with specified USDC amount
177+
/join <tossId> - Join an existing toss with the specified ID
178+
/list - List all active tosses
179179
/balance - Check your wallet balance
180180
/help - Show available commands
181181
182182
Before executing any action:
183183
1. Check if the user has sufficient balance for the requested action
184-
2. Verify game exists when joining
185-
3. Ensure proper game state transitions
184+
2. Verify toss exists when joining
185+
3. Ensure proper toss state transitions
186186
4. Handle any errors gracefully
187187
188-
Keep responses concise and clear, focusing on payment verification and game status.
188+
Keep responses concise and clear, focusing on payment verification and toss status.
189189
If there is a 5XX (internal) HTTP error, ask the user to try again later.
190190
`,
191191
});
@@ -238,20 +238,20 @@ export async function processMessage(
238238
}
239239

240240
/**
241-
* Parse a natural language bet prompt to extract structured information
241+
* Parse a natural language toss prompt to extract structured information
242242
* @param agent - The agent
243243
* @param config - Agent configuration
244244
* @param prompt - The natural language prompt
245-
* @returns Parsed bet information
245+
* @returns Parsed toss information
246246
*/
247-
export async function parseNaturalLanguageBet(
247+
export async function parseNaturalLanguageToss(
248248
agent: ReturnType<typeof createReactAgent>,
249249
config: { configurable: { thread_id: string } },
250250
prompt: string,
251-
): Promise<ParsedBet> {
251+
): Promise<ParsedToss> {
252252
try {
253253
// Default values in case parsing fails
254-
const defaultResult: ParsedBet = {
254+
const defaultResult: ParsedToss = {
255255
topic: prompt,
256256
options: ["yes", "no"],
257257
amount: "0.1",
@@ -261,17 +261,17 @@ export async function parseNaturalLanguageBet(
261261
return defaultResult;
262262
}
263263

264-
console.log(`🔄 Parsing natural language bet: "${prompt}"`);
264+
console.log(`🔄 Parsing natural language toss: "${prompt}"`);
265265

266266
// Format specific request for parsing
267267
const parsingRequest = `
268-
Parse this bet request into structured format: "${prompt}"
268+
Parse this toss request into structured format: "${prompt}"
269269
270270
Return only a valid JSON object with these fields:
271271
{
272-
"topic": "the betting topic",
272+
"topic": "the tossing topic",
273273
"options": ["option1", "option2"],
274-
"amount": "bet amount"
274+
"amount": "toss amount"
275275
}
276276
`;
277277

@@ -283,10 +283,10 @@ export async function parseNaturalLanguageBet(
283283
// Find JSON in the response
284284
const jsonMatch = response.match(/\{[\s\S]*\}/);
285285
if (jsonMatch) {
286-
const parsedJson = JSON.parse(jsonMatch[0]) as BetJsonResponse;
286+
const parsedJson = JSON.parse(jsonMatch[0]) as TossJsonResponse;
287287

288288
// Validate and provide defaults if needed
289-
const result: ParsedBet = {
289+
const result: ParsedToss = {
290290
topic: parsedJson.topic ?? prompt,
291291
options:
292292
Array.isArray(parsedJson.options) && parsedJson.options.length >= 2
@@ -296,7 +296,7 @@ export async function parseNaturalLanguageBet(
296296
};
297297

298298
console.log(
299-
`✅ Parsed bet: "${result.topic}" with options [${result.options.join(", ")}] for ${result.amount} USDC`,
299+
`✅ Parsed toss: "${result.topic}" with options [${result.options.join(", ")}] for ${result.amount} USDC`,
300300
);
301301
return result;
302302
}
@@ -306,7 +306,7 @@ export async function parseNaturalLanguageBet(
306306

307307
return defaultResult;
308308
} catch (error) {
309-
console.error("Error parsing natural language bet:", error);
309+
console.error("Error parsing natural language toss:", error);
310310
return {
311311
topic: prompt,
312312
options: ["yes", "no"],

0 commit comments

Comments
 (0)