Skip to content

Commit

Permalink
[onchain-ai-chat] Create room with message
Browse files Browse the repository at this point in the history
  • Loading branch information
jolestar committed Feb 10, 2025
1 parent 1b07dd1 commit 3dbd9c2
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 30 deletions.
43 changes: 42 additions & 1 deletion examples/onchain_ai_chat/sources/ai_service.move
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ module onchain_ai_chat::ai_service {
let option_min_amount = registry::estimated_cost(ORACLE_ADDRESS, url, string::length(&body), 1024);

let oracle_fee: u256 = if(option::is_some(&option_min_amount)) {
option::destroy_some(option_min_amount)*30
option::destroy_some(option_min_amount)*40
} else {
DEFAULT_ORACLE_FEE
};
Expand Down Expand Up @@ -152,4 +152,45 @@ module onchain_ai_chat::ai_service {
assert!(string::index_of(&body, &string::utf8(b"messages")) != 18446744073709551615, 2);
assert!(string::index_of(&body, &string::utf8(b"user")) != 18446744073709551615, 3);
}

#[test]
fun test_oracle_fee_operations() {
oracles::init_for_test();

// Initialize test accounts
let alice = account::create_signer_for_testing(@0x77);
let alice_addr = signer::address_of(&alice);

// Setup test account with initial RGas
let fee_amount: u256 = 1000000000; // 10 RGas
rooch_framework::gas_coin::faucet_entry(&alice, fee_amount);

// Test Case 1: Check initial balance
{
let initial_balance = get_user_oracle_fee_balance(alice_addr);
assert!(initial_balance == 0, 1);
};

// Test Case 2: Deposit and check balance
{
deposit_user_oracle_fee(&alice, fee_amount);
let balance = get_user_oracle_fee_balance(alice_addr);
assert!(balance == fee_amount, 2);
};

// Test Case 3: Partial withdrawal
{
let withdraw_amount = fee_amount / 2;
withdraw_user_oracle_fee(&alice, withdraw_amount);
let balance = get_user_oracle_fee_balance(alice_addr);
assert!(balance == withdraw_amount, 3);
};

// Test Case 4: Withdraw all remaining balance
{
withdraw_all_user_oracle_fee(&alice);
let balance = get_user_oracle_fee_balance(alice_addr);
assert!(balance == 0, 4);
};
}
}
28 changes: 26 additions & 2 deletions examples/onchain_ai_chat/sources/room.move
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,6 @@ module onchain_ai_chat::room {
) {
let room_id = object::id(room_obj);
let is_ai_room = object::borrow(room_obj).room_type == ROOM_TYPE_AI;
send_message(account, room_obj, content);

// If it's an AI room, request AI response
if (is_ai_room) {
Expand All @@ -357,7 +356,8 @@ module onchain_ai_chat::room {
content,
prev_messages
);
}
};
send_message(account, room_obj, content);
}

/// Add a member to a private room - entry function
Expand Down Expand Up @@ -397,6 +397,30 @@ module onchain_ai_chat::room {
room_mut.status = new_status;
}

/// Create a AI room and send the first message in one transaction
public entry fun create_ai_room_with_message_entry(
account: &signer,
title: String,
is_public: bool,
first_message: String,
) {

// Create the room
let room_id = create_room(account, title, is_public, ROOM_TYPE_AI);

// Get room object and send message
let room_obj = object::borrow_mut_object_shared<Room>(room_id);

let prev_messages = vector::empty();
ai_service::request_ai_response(
account,
room_id,
first_message,
prev_messages
);
send_message(account, room_obj, first_message);
}

#[test_only]
/// Test helper function to delete a room
public fun delete_room_for_testing(account: &signer, room_id: ObjectID) {
Expand Down
2 changes: 1 addition & 1 deletion examples/onchain_ai_chat/web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<RoochProvider networks={networkConfig} sessionConf={
{
appName: "Onchain AI Chat",
appUrl: "https://test.com",
appUrl: "https://onchain-ai-chat.vercel.app/",
scopes: [`${PACKAGE_ID}::*::*`],
maxInactiveInterval: 3600,
}
Expand Down
33 changes: 8 additions & 25 deletions examples/onchain_ai_chat/web/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { RoomListContainer } from '../containers/RoomListContainer'
import {
useCurrentSession,
useRoochClient,
SessionKeyGuard
} from '@roochnetwork/rooch-sdk-kit'
import { useNetworkVariable } from '../networks'
import { Args, Transaction } from '@roochnetwork/rooch-sdk'
Expand All @@ -20,18 +19,19 @@ export function Home() {
const [loading, setLoading] = useState(false)

const handleCreateRoom = async (message: string) => {
console.log('Creating room with message:', message, client, sessionKey, loading)
console.log('Creating room with message:', message, client, sessionKey, loading)

if (!client || !sessionKey || loading) return
setLoading(true)

try {
const tx = new Transaction()
tx.callFunction({
target: `${packageId}::room::create_ai_room_entry`,
target: `${packageId}::room::create_ai_room_with_message_entry`,
args: [
Args.string("new_chat"),
Args.bool( true), // public room
Args.string("new_chat"), // title
Args.bool(true), // is_public
Args.string(message), // first_message
],
})

Expand All @@ -41,7 +41,7 @@ export function Home() {
})

if (result?.execution_info.status.type !== 'executed') {
throw new Error('Create room failed')
throw new Error(`Failed to create room and send message, ${JSON.stringify(result.execution_info)}`);
}

// Find the Room object from changeset
Expand All @@ -54,25 +54,8 @@ export function Home() {
}

const roomId = roomChange.metadata.id
console.log('Created room:', roomId)

// Send initial message
const messageTx = new Transaction()
messageTx.callFunction({
target: `${packageId}::room::send_message_entry`,
args: [Args.objectId(roomId), Args.string(message)],
})

const messageResult = await client.signAndExecuteTransaction({
transaction: messageTx,
signer: sessionKey,
});

if (messageResult?.execution_info.status.type !== 'executed') {
throw new Error('Failed to send message');
}

navigate(`/chat/${roomId}`); // Navigate to the new room
console.log('Created room with ID:', roomId)
navigate(`/chat/${roomId}`)
} catch (error) {
console.error('Failed to create chat:', error)
} finally {
Expand Down
1 change: 0 additions & 1 deletion examples/onchain_ai_chat/web/src/pages/Room.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
useCurrentSession,
useRoochClient,
useRoochClientQuery,
SessionKeyGuard
} from '@roochnetwork/rooch-sdk-kit'
import { Layout } from '../components/Layout'
import { ChatInput } from '../components/ChatInput'
Expand Down

0 comments on commit 3dbd9c2

Please sign in to comment.